Docker compose using environment variables to set

2019-05-09 10:46发布

问题:

I'm using docker compose to run my application. And for do that I need to set the hosts inside container (it's depends on the environment i'm running).

My approach was:

Create an environment file and set the variable:

#application.env
SERVER_IP=10.10.9.134

My docker compose file looks like:

version: '2'
services:

  api:
    container_name: myApplication
    env_file:
      - application.env
    build: ./myApplication/
    entrypoint: ./docker/api-startup.sh
    ports:
      - "8080:8080"
    depends_on:
      - redis    
    extra_hosts: &extra_hosts
      myip: $SERVER_IP

But my problem is that the variable SERVER_IP is never replaced.

When I run docker-compose config I see:

services:
  api:
    build:
      context: /...../myApplication
    container_name: myApplication
    depends_on:
    - redis
    entrypoint: ./docker/api-startup.sh
    environment:
      SERVER_IP: 10.10.9.134
    extra_hosts:
      myip: ''
    ports:
    - 8080:8080

I've tried to replace the variable reference using $SERVER_IP or ${SERVER_IP} but it didn't work.

回答1:

I created a file .env, added single line HOST=test.example.com, then did this in docker-compose:

extra_hosts:
- myip:${HOST}

docker-compose config then shows

  extra_hosts:
      myip: test.example.com

To do this I followed the documentation from Docker-compose environment variables the section about .env file

UPDATE

According to the Docker documentation,

Note: If your service specifies a build option, variables defined in environment files will not be automatically visible during the build. Use the args sub-option of build to define build-time environment variables.

It basically means if you place your variables in .env file, you can use them for substitution in docker-compose.yml, but if you use env_file option for the particular container, you can only see the variables inside the Docker container, not during the build. It is also logical, env_file replaces docker run --env-file=FILE ... and nothing else.

So, you can only place your values into .env. Alternatively, as William described, you can use host's environment variables.



回答2:

EDIT

Try the following:

version: '2'
services:
  api:
    container_name: myApplication
    env_file:
      - application.env
    build: ./myApplication/
    entrypoint: ./docker/api-startup.sh
    ports:
      - "8080:8080"
    depends_on:
      - redis    
    extra_hosts:
      - "myip:${SERVER_IP}"

Ensure curly bracers and that the environment variable exists on the host os.