27

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?

2 Answers 2

28

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.

25

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

2
  • 1
    Makes sense. Then again, I wanted to use env variables here so the EXPOSE and the inner application have the same port. I guess I will have to use a script to run the docker run command with the same env variable.
    – Momo
    May 4, 2018 at 15:46
  • 2
    Script is a good idea. Normally if you manage your containers using a docker compose, kubernetes etc they allowing configuring these options so you should be fine. May 4, 2018 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.