In a docker swarm, I need to setup an environment variable to the value of a docker secret. I followed the answer here , but it does not work for me.
To try various options, I created a secret called testpwd and made a very simple compose file for the docker stack, as follows:
services:
server:
image: bash
deploy:
replicas: 1
entrypoint: ["sh", "-c", "cat /run/secrets/testpwd; TESTSEC=`cat /run/secrets/testpwd`; export TESTSEC; echo TESTSEC; echo $TESTSEC; ping stackoverflow.com"]
secrets:
- testpwd
secrets:
testpwd:
external: true
A log from the container launched by this stack shows:
pwd1234
TESTSEC
PING stackoverflow.com (104.18.32.7): 56 data bytes 64 bytes from 104.18.32.7: seq=0 ttl=56 time=2.548 ms
The content inside /run/secrets/testpwd is pwd1234 but TESTSPEC is neither created as an environment variable for this shell nor it is exported.
I have tried multiple variants of the entrypoint, such as:
entrypoint: ["sh", "-c", "export TESTSEC=$$(cat /run/secrets/testpwd); ping stackoverflow.com"]
entrypoint: ["sh", "-c", "export TESTSEC=$$(cat /run/secrets/testpwd) && ping stackoverflow.com"]
and others mentioned in the link at the begining.
But nothing works. When I get inside the container with "docker exec -it cont_id sh", I can see that the ping is running and see the value of the secret in /run/secrets/testpwd, but there is no TESTSEC environment variable.
Just in case, in the host machine:
$docker --version
Docker version 26.1.0, build 9714adc
$docker compose version
Docker Compose version v2.26.1
$lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 22.04.4 LTS
Release: 22.04
Codename: jammy
stack.yaml
services:
server:
image: bash
deploy:
mode: replicated-job
replicas: 1
entrypoint:
- sh
- -c
- |
export TESTSEC=$$(cat /run/secrets/testpwd)
echo $$TESTSEC
secrets:
- testpwd
secrets:
testpwd:
file: secret.txt
> docker stack deploy -c stack.yaml test
Creating network test_default
Creating secret test_testpwd
Creating service test_server
> docker service logs test_server
test_server.0.s68pzslhjbpw@docker-desktop | Secret1234
Works just fine.