skip to Main Content

I’d like to pass the result of bash-command (or cmd) or OS variable as an env to docker-compose.yml, is it possible or not?

For example:

hostname gives me the current machine name: ubuntu-machine-01

and I’d like to pass it as env for docker-compose file:

version: '3.8'
services:
  service:
    image: docker-container:latest
    environment:
      - WORKSPACE=${{hostname}}

P.S. Unfortunately I can’t bypass arg during Docker image build phase & unable to call it inside container, so the question is about passing OS env to docker-compose via syntax of the file.

2

Answers


  1. As of today, no. Unfortunately Docker Compose interpolation only supports a limited set of features.

    Other extended shell-style features […] are not supported by Compose.

    Alternatively you can create a .env file which will be used by Docker Compose to interpolate variable, for example:

    echo "HOSTNAME=$(hostname)" > .env
    

    And with docker-compose.yml

    version: '3.8'
    services:
      service:
        image: docker-container:latest
        environment:
          - WORKSPACE=$HOSTNAME
    
    Login or Signup to reply.
  2. With regards to hostname specifically it is worth mentioning Docker Swarm supports service template parameters.

    So to follow the example on a swarm, if you needed WORKSPACE to reflect the hostname of the node the service is running on (rather than deployed from), the following syntax would apply:

    version: '3.9'
    services:
      service:
        image: docker-container:latest
        environment:
          WORKSPACE: "{{.Node.Hostname}}"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search