Docker stack deploy with context and env variables?

I have a docker-compose stack that I have been successfully deploying with

docker --context remote_name stack deploy -c compose-file.yaml stack_name

This works fine and env variables I include via “env_file: .env.web” are correctly used in the deployment. However, I’d like to make use of docker-compose variable substitution to change a couple of items in the yaml based on an “.env” file contents. The .env file is in the directory I run the above command from (that also contains the yaml file).

I expected to be able to use ${VAR_NAME} in the compose file, just as I can when using “docker-compose up”, however when using a stack deploy variable substitution does not appear to take place.

Is this supposed to work when using a stack deploy with a --context?

1 Like

Ignore above question. Found a mention buried in the docs that .env isn’t used by stack deploy. Further search then turned up a thread about this issue and in particular this comment https://github.com/moby/moby/issues/29133#issuecomment-442912378 that suggests a workaround.

2 Likes

Even though you found your solution, I find this approach interesting.

Is “remote_name” the name of the Docker swarm manager? And, if so, does the deployment honour swarm-specific compose values like replicas and and placement? I went from swarm back to normal docker compose for this reason i.e. couldn’t get variables working (before also realising they aren’t officially supported).

1 Like

I’d like to share a simple solution that work in most cases.

  • Create a .sh file (eg install.sh)
    The file content should be:

export $(cat .env) > /dev/null 2>&1; docker stack deploy -c swarm-docker-compose.yml my_stack

Note: Replace your regular stack command with the one you use and it should be good. Remember that .env variables in this case have to be VAR1=VALUE1 (No commas or quotes)