Search code examples
dockerdocker-swarm

Docker swarm service environment variable is not visible within container


I am creating a docker service with an environment variable:

docker service create --env TEST=123 myservice

And I verify the environment variable was set with

$ docker service inspect myservice
...
ContainerSpec:
 Env:           TEST=123
...

But then the environment variable does not show up within the docker container. In particular, the code running inside the docker container prints os.Environ() and in the logs I see only the standard environment variable:

$ docker service logs myservice
[HOSTNAME=48bcddab9204 SHLVL=1 HOME=/root PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PWD=/app]

So the environment variable "TEST" is not set. How can I set up a service that defines this environment variable?

The output of docker version is

Client:
 Version:           20.10.12
 API version:       1.41
 Go version:        go1.17.5
 Git commit:        e91ed5707e
 Built:             Mon Dec 13 22:31:40 2021
 OS/Arch:           linux/amd64
 Context:           synology
 Experimental:      true

Server:
 Engine:
  Version:          20.10.3
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.15.13
  Git commit:       a3bc36f
  Built:            Thu Aug 19 07:11:25 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v1.4.3
  GitCommit:        ea3508454ff2268c32720eb4d2fc9816d6f75f88
 runc:
  Version:          v1.0.0-rc93
  GitCommit:        31cc25f16f5eba4d0f53e35374532873744f4b31
 docker-init:
  Version:          0.19.0
  GitCommit:        ed96d00

Solution

  • Variables should be defined in the environment when you use --env. If that's not happening, we'd need a complete example to reproduce. Here's an example showing that it works:

    $ docker service create --name env-test --env TESTVAR=123 busybox tail -f /dev/null
    nj9l6z57d9pviztyp9pglmv4r
    overall progress: 1 out of 1 tasks 
    1/1: running   [==================================================>] 
    verify: Service converged 
    
    $ docker ps -l
    CONTAINER ID   IMAGE            COMMAND               CREATED          STATUS          PORTS     NAMES
    697c1bf221b1   busybox:latest   "tail -f /dev/null"   20 seconds ago   Up 19 seconds             env-test.1.vlrepc8mqqvx7gysh2qsymja8
    
    $ docker exec -it env-test.1.vlrepc8mqqvx7gysh2qsymja8 env
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    HOSTNAME=697c1bf221b1
    TERM=xterm
    TESTVAR=123
    HOME=/root