See this:
You can set environment variables in a service’s containers with the 'environment' key, just like with docker run -e VARIABLE=VALUE ...
Also, you can use ENV in dockerfile to define a environment variable.
The difference is:
Environment variable define in Dockerfile
will not only used in docker build
, it will also persist into container. This means if you did not set -e
when docker run
, it will still have environment variable same as defined in Dockerfile
.
While environment variable define in docker-compose.yaml
just used for docker run
.
Maybe next example could make you understand more clear:
Dockerfile:
FROM alpine
ENV http_proxy http://123
docker-compose.yaml:
app:
environment:
- http_proxy=http://123
If you define environment variable in Dockerfile
, all containers used this image will also has the http_proxy
as http://123
. But the real situation maybe when you build the image, you need this proxy. But, the container maybe run by other people maybe not need this proxy or just have another http_proxy, so they had to remove the http_proxy
in entrypoint or just change to another value in docker-compose.yaml
.
If you define environment variable in docker-compose.yaml
, then user could just choose his own http_proxy when do docker-compose up
, http_proxy
will not be set if user did not configure it docker-compose.yaml
.