I have these 3 files.
▶ ls
.env docker-compose.yml Dockerfile
These are the contents.
▶ cat .env
ABC=123
▶ cat docker-compose.yml
version: "3.7"
services:
test:
env_file:
- .env
build:
context: .
▶ cat Dockerfile
FROM alpine:latest
RUN printenv
When I try to build an image with .env
through docker-compose, printenv
in the building image doesn't print ABC
▶ docker-compose build --no-cache test
Building test
Sending build context to Docker daemon 4.096kB
Step 1/2 : FROM alpine:latest
---> d4ff818577bc
Step 2/2 : RUN printenv
---> Running in a2ddef17b235
HOSTNAME=a2ddef17b235
SHLVL=1
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/
Removing intermediate container a2ddef17b235
---> 05b8242e2d25
Successfully built 05b8242e2d25
Successfully tagged doenv-in-compose_test:latest
I know I can use ARG
and --build-arg
to embed env vars in the building image.
*notice the ABC=777
▶ cat Dockerfile
FROM alpine:latest
ARG ABC
RUN printenv
▶ docker-compose build --no-cache --build-arg ABC=777 test
Building test
Sending build context to Docker daemon 4.096kB
Step 1/3 : FROM alpine:latest
---> d4ff818577bc
Step 2/3 : ARG ABC
---> Running in e6aed0723b7b
Removing intermediate container e6aed0723b7b
---> 92e4a7350e24
Step 3/3 : RUN printenv
---> Running in b20a3a4418ca
HOSTNAME=b20a3a4418ca
SHLVL=1
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ABC=777
PWD=/
Removing intermediate container b20a3a4418ca
---> 4386eb200523
Successfully built 4386eb200523
Successfully tagged doenv-in-compose_test:latest
However, in my real case, I have some 10 different variables in the dotenv file, it's not really suitable to list them all in Dockerfile and command line.
Is there a way to load .env file into the image when to build?