skip to Main Content

Environment variables defined in docker-compose.yml are not set.

services:
  service1:
    image: alpine
    environment:
      - VAR1:H
      - VAR2:HI
    command:
      - /bin/sh
      - -c
      - |
        echo $VAR1
        echo $VAR2

This outputs:

$ docker compose up
WARN[0000] The "VAR1" variable is not set. Defaulting to a blank string.
WARN[0000] The "VAR2" variable is not set. Defaulting to a blank string.
[+] Running 1/0
 ⠿ Container compose-service1-1  Recreated                                                                                                                                                                              0.1s
Attaching to compose-service1-1
compose-service1-1  |
compose-service1-1  |
compose-service1-1 exited with code 0

Docker Compose version v2.12.0

2

Answers


  1. Envrionment variables can be either passed with map syntax or array syntax, see:

    # Array syntax
    services:
      service1:
        image: alpine
        environment:
          - VAR1=H
          - VAR2=HI
        command:
          - /bin/sh
          - -c
          - |
            echo $$VAR1
            echo $$VAR2
    

    Or,

    # Map syntax
    services:
      service1:
        image: alpine
        environment:
          VAR1: "H"
          VAR2: "HI"
        command:
          - /bin/sh
          - -c
          - |
            echo $$VAR1
            echo $$VAR2
    

    Then, you have to use $$. As using echo $VAR1 makes docker-compose look for the variables from your host’s environment.

    See:

    Login or Signup to reply.
  2. Can you try this?

     services:
      service1:
        image: alpine
        environment:
         VAR1: "H"
         VAR2: "HI"
        command:
          - /bin/sh
          - -c
          - |
            echo "$${VAR1}"
            echo "$${VAR2}"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search