ltdev
ltdev

Reputation: 4457

Docker & docker-compose setting environment variables

This is how typically a docker-compose.yml file would be structured:

version: "3.7"
services:
    serv1:
        build: ./serv1
        ports:
            - 4040:40
        env_file:
            - ./docker.env
    serv2:
        build: ./serv2
        ports:
            - 3000:3000
        env_file:
            - ./docker.env
    serv3:
        build: ./serv3
        ports:
            - 5000:5000
        env_file:
            - ./docker.env

I have setup some env variables inside a docker.env file which I would like to use and I'm having two questions:

  1. Trying to use the port on the host, so
serv1:
   ports:
      - "${SERV1_PORT}:40"
   env_file:
      - ./docker.env
...

serv2:
   ports:
      - "${SERV2_PORT}:40"
   env_file:
      - ./docker.env

but when I build I'm getting the following:

WARN[0000] The "SERV1_PORT" variable is not set. Defaulting to a blank string.
  1. Instead of including on each service the env_file: is there a way to specify "globally" the env file on my docker-compose by including it only once? Mean something like this:
services:
  serv1: ...
  serv2: ...
  ...
env_file:
   - ./docker.env # these variables to be accessible in all

Upvotes: 1

Views: 8804

Answers (3)

SmartDoggy
SmartDoggy

Reputation: 1

Adding to the correct answer I would highly suggest you include "sensible" defaults to the docker compose stack. This will allow your team and other developers to spin up the stack to develop with quicker, while also providing them with the opportunity to customize.

This can be done like:

    environment:
      NODE_ENV: ${NODE_ENV:-development}

Upvotes: 0

Robert Alexander
Robert Alexander

Reputation: 1151

On top of the previous valid answer, you can also issue a docker compose config command to see how any ENV has been (or not) substituted as you wished.

Upvotes: 1

larsks
larsks

Reputation: 311238

The env_file sets environment variables that are available inside the container, not inside your docker-compose.yml. For that, you want the .env file; read more about Environment variables in docker compose.

Substitute environment variables in Compose files

It’s possible to use environment variables in your shell to populate values inside a Compose file:

web:
   image: "webapp:${TAG}"

If you have multiple environment variables, you can substitute them by adding them to a default environment variable file named .env or by providing a path to your environment variables file using the --env-file command line option.

Upvotes: 2

Related Questions