Search code examples
docker-composedocker-secrets

docker stack: setting environment variable from secrets


I was trying to set the password from secrets but it wasn't picking it up. Docker Server verions is 17.06.2-ce. I used the below command to set the secret:

echo "abcd" | docker secret create password -

My docker compose yml file looks like this

version: '3.1'
...
 build:
  context: ./test
  dockerfile: Dockerfile
environment:
  user_name: admin
  eureka_password: /run/secrets/password
secrets:
  - password

I also have root secrets tag:

secrets:
  password:
     external: true

When I hardcode the password in environment it works but when I try via the secrets it doesn't pick up. I tried to change the compose version to 3.2 but with no luck. Any pointers are highly appreciated!


Solution

  • You need modify docker compose to read the secret env file from /run/secrets. If you want to set environment variables via bash, you can overwrite your docker-compose.yaml file as displayed below.

    You can save the following code as entrypoint_overwrited.sh:

    # get your envs files and export envars
    export $(egrep  -v '^#'  /run/secrets/* | xargs) 
    # if you need some specific file, where password is the secret name 
    # export $(egrep  -v '^#'  /run/secrets/password| xargs) 
    # call the dockerfile's entrypoint
    source /docker-entrypoint.sh
    

    In your docker-compose.yaml overwrite the dockerfile and entrypoint keys:

    version: '3.1'
    #...
    build:
      context: ./test
      dockerfile: Dockerfile
    entrypoint: source /data/entrypoint_overwrited.sh
    tmpfs:
      - /run/secrets
    volumes:
      - /path/your/data/where/is/the/script/:/data/
    environment:  
      user_name: admin
      eureka_password: /run/secrets/password
    secrets:
      - password
    

    Using the snippets above, the environment variables user_name or eureka_password will be overwritten. If your secret env file defines the same env vars, the same will happen if you define in your service some env_file.