How to pass environment variable to docker-compose

2019-04-04 17:49发布

问题:

I am trying to run a container. I already have the image uploaded to private Docker registry. I want to write a compose file to download and deploy the image. But I want to pass the TAG name as a variable from the docker-compose run command.My compose file looks like below. How can I pass the value for KB_DB_TAG_VERSION as part of docker-compose up command?

version: '3'
services:
   db:
    #build: k-db
    user: "1000:50"
    volumes:
      - /data/mysql:/var/lib/mysql
    container_name: k-db
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    image:  XX:$KB_DB_TAG_VERSION
    image: k-db
    ports:
      - "3307:3306"

回答1:

You have two options:

  1. Create the .env file as already suggested in another answer.
  2. Prepend KEY=VALUE pair(s) to your docker-compose command, e.g:

    KB_DB_TAG_VERSION=kb-1.3.20-v1.0.0 docker-compose up
    

    Exporting it earlier in a script should also work, e.g.:

    export KB_DB_TAG_VERSION=kb-1.3.20-v1.0.0
    docker-compose up
    


回答2:

You can create a .env file on the directory where you execute the docker-compose up command (and your docker-compose.yml file is located) with the following content:

KB_DB_TAG_VERSION=kb-1.3.20-v1.0.0

Your docker-compose.yml file should look like the following (added { and }):

version: '3'
services:
   db:
     user: "1000:50"
     volumes:
       - /data/mysql:/var/lib/mysql
     container_name: k-db
     environment:
       - MYSQL_ALLOW_EMPTY_PASSWORD=yes
     image: XX:${KB_DB_TAG_VERSION}
     image: k-db
     ports:
       - "3307:3306"


回答3:

I just answered almost the exact same question here: https://stackoverflow.com/a/52709818/229178

version: '3'
services:
  db:
    #build: k-db
    user: "1000:50"
    volumes:
      - /data/mysql:/var/lib/mysql
    container_name: k-db
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    image:  XX:${KB_DB_TAG_VERSION}
    image: k-db
      ports:
        - "3307:3306"

Then:

docker-compose -e KB_DB_TAG_VERSION kb-1.3.20-v1.0.0 up