简体   繁体   中英

Get or set env variable in docker-compose.yml file

I have got a docker-compose.yml file and there I define:

extra_hosts:
- "localhost:${MY_MACHINE_IP}"

It works if I define MY_MACHINE_IP as environment var earlier.

What I want to achieve is to perform action like:

extra_hosts:
- "localhost:<get MY_MACHINE_IP from env if it exists, if not set MY_MACHINE_IP env variable with value <docker-machine-ip>>"

In other words: I want to define it in extra_hosts section, if MY_MACHINE_IP is already specified, get it, if not - set this env. variable with value = my docker machine ip.

Is it possible?

Yes in according to docker documentation

docker-compose run SERVICE env

So i think the variables are not global as you may think. You have to pass them as parameters. Read this .

You can use the package ruamel.dcw for that ( dcw for Docker Compose Wrapper, disclaimer: I am the author of that package). It allows you to create a section with key user-data in your docker-compose.yaml file, which is stripped out before handing the file to the normal docker-compose . That section can look like:

user-data:
  author: Your Name <your-name@youremail.com>
  description: container for postfix/submission
  env-defaults:
    PORT: 587    # override during development
    NAME: submission
    DOCKER_BASE: /data0/DATA

and then you can use {PORT} , {NAME} and {DOCKER_BASE} in the rest of the file, with the option of overriding these default values with environment variables.

The utility also write out a file .dcw_env_vars.inc which you can copy into your container and source to get the appropriate values into scripts you RUN from within the Dockerfile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM