Host environment variables with docker stack deploy

It works if you run the docker command through env.

env JMX_HOSTNAME="${JMX_HOSTNAME}" docker stack deploy -c docker-compose.yml mystack

Credit to GitHub issue that pointed me in the right direction.


Yes, this works when you combine two concepts:

  1. Swarm node labels, of which Hostname is one of the built-in ones.
  2. Swarm service go templates, which also work in stack files.

This would pull in the hostname to the ENV value of DUDE for each container to be the host that it's running on:

version: '3.4'

services:
  nginx:
    image: nginx
    environment:
      DUDE: "{{.Node.Hostname}}"
    deploy:
      replicas: 3

I found another way for when you have many environment variables. The same method also works with docker-compose up

sudo -E docker stack deploy -c docker-compose.yml mystack

instead of

env foo="${foo}" bar="${bar}" docker stack deploy -c docker-compose.yml mystack

sudo -E man description;

   -E, --preserve-env
               Indicates to the security policy that the user wishes to
               preserve their existing environment variables.  The
               security policy may return an error if the user does not
               have permission to preserve the environment.