My Dockerfile sets some defaults for environment variables, then later exposes two ports that should be the provided environment variables:
FROM python:3.6.5-stretch
[ ... ]
ENV MY_SERVICE_PORT 8080
ENV MY_SERVICE_PORT_RPC 50051
[ ... ]
EXPOSE ${MY_SERVICE_PORT}
EXPOSE ${MY_SERVICE_PORT_RPC}
My application inside the container reads the environment variable correctly when starting the container. If I run my image using:
docker run -e "MY_SERVICE_PORT=80" -d -t image_tag
Then I use docker ps
:
0fb14e12d43d image_tag "/bin/sh -c 'python3…" 8080/tcp, 50051/tcp
As you can see, EXPOSE
used the build-time environment variables (defaulting to 8080 and 50051). If I execute set
inside the container terminal, I get:
MY_SERVICE_PORT=80
MY_SERVICE_PORT_RPC=50051
How can I make sure EXPOSE
is only set to a run-time environment variable? Is it possible?
The command used to launch Docker containers, docker run , accepts ENV variables as arguments. Simply run it with the -e flag, shorthand for --env , and pass in the key=value pair: sudo docker run -e POSTGRES_USER='postgres' -e POSTGRES_PASSWORD='password' ...
docker pull alpine:3. When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e).
Fetch Using docker exec Command Here, we are executing the /usr/bin/env utility inside the Docker container. Using this utility, you can view all the environment variables set inside Docker containers. Notice that our my_env_var is also present in the output.
Need of exposing ports. In order to make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, we can use the -P or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host to the outside world.
A little late but you could also use build args and change your code to:
FROM python:3.6.5-stretch
[ ... ]
ARG MY_SERVICE_PORT=8080
ARG MY_SERVICE_PORT_RPC=50051
# 8080 and 50051 would be the defaults
[ ... ]
# Still functions like environment variables :)
EXPOSE ${MY_SERVICE_PORT}
EXPOSE ${MY_SERVICE_PORT_RPC}
Then you can build with docker build --build-arg MY_SERVICE_PORT=80 -t image_tag
before you run.
This way you could have your containerized application and your container running with the same ports without getting too complex.
If you are not sure what your exposed ports will be then don't set them in the dockerfile. Just use --expose
with docker run
to specify ports at run time along with environment variable for details:
https://docs.docker.com/engine/reference/run/#expose-incoming-ports
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With