22

I have writte a docker-compose.yml file to create a multi-container app with nodejs and mongodb (so 2 containers), and I want to make some options configurable, as the choice of server address and port. To do that, I have written what follows in docker-compose.yml to set them as env variables:

..
    web:
      environment:
        - PORT=3000
        - ADDRESS=xxx.xxx.xxx.xxx
..

Within the source code of my application, I use process.env.PORT and process.env.ADDRESS to refer to these variables.

But how can I do if I want to change those values, and for example set PORT=3001? I have to use docker-compose build and docker-compose up again and build all the application, included mongodb container?

2
  • 4
    Environment variables are runtime instructions, just change them in the docker-compose.yml then re-run docker-compose up. Commented May 8, 2017 at 14:44
  • 1
    As johnharris85 mentioned, re-running docker-compose up would be enough. Alternatively to using the environment variables in docker-compose.yml, you could use an environment file: docs.docker.com/compose/env-file Commented May 9, 2017 at 16:37

1 Answer 1

27

I have to use docker-compose build and docker-compose up again and build all the application, included mongodb container?

Not build, just up. They are runtime options, not build options. Changing them in the docker-compose.yml file and then doing a docker-compose up again should recreate the containers with the new environment variables.

Alternatively, you can specify environment variables outside the docker-compose.yml file to make for easier changes:

  1. One of these methods is to use a .env file in the same folder that you execute docker-compose form (see https://docs.docker.com/compose/env-file/ for information on it).
  2. Another option is to interpolate environment variables from your shell. You could specify them such as - PORT=${APP_PORT} and then export APP_PORT=3000 on your shell before running docker-compose. See https://docs.docker.com/compose/environment-variables/ for more information.
Sign up to request clarification or add additional context in comments.

2 Comments

why docker-compose restart won't reload the .env variables changes?
Because environment is set at container creation. You will need to recreate the containers using something like docker-compose up --force-recreate.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.