我尝试按照 Dockerfile 和 docker compose 的参考文档传递环境变量给 Docker 镜像,但均未成功。
当使用 docker-compose 进行构建时,我希望在构建过程中将此环境变量传递给 Docker。
在 Docker 主机上,我有:
export BUILD_VERSION=1.0
app.js
console.log('BUILD_VERSION: ' + process.env.BUILD_VERSION);
Dockerfile:
FROM node
ADD app.js /
ARG BUILD_VERSION
ENV BUILD_VERSION=$BUILD_VERSION
RUN echo Build Time: $BUILD_VERSION
RUN node /app.js
CMD echo Run Time: $BUILD_VERSION
docker-compose.yml:
version: '3'
services:
app:
build:
context: .
args:
- BUILD_VERSION
如果直接构建图像,则环境变量会被正确传递:
docker build -t test --no-cache --build-arg BUILD_VERSION .
并且也可以在运行时使用:
$ docker run --rm test
Run Time: 1.0
$ docker run --rm test node /app
BUILD_VERSION: 1.0
但是不能使用Docker Compose。
docker-compose up --build
...
Step 5/7 : RUN echo Build Time: $BUILD_VERSION
---> Running in 6115161f33bf
Build Time:
---> c691c619018a
Removing intermediate container 6115161f33bf
Step 6/7 : RUN node /app.js
---> Running in f51831cc5e1e
BUILD_VERSION:
它只能在运行时使用:
$ docker run --rm test
Run Time: 1.0
$ docker run --rm test node /app
BUILD_VERSION: 1.0
我也尝试在docker-compose.yml中使用
environment
,如下所示,但这只能在运行时而不是构建时使其可用:version: '3'
services:
app:
build:
context: .
environment:
- BUILD_VERSION
请指导,如何以最简单的方式使其工作?