TExcelTAD
Home › Docker Swarm › Stack Variables & docker stack config

Stack Variables & docker stack config

One stack file usually serves several environments: staging and production differ in image tags, replica counts, hostnames and resource limits. Instead of copying the file, you put variables in it: ${TAG}, ${REPLICAS:-2}. docker stack deploy replaces them with values from the shell environment on the machine that runs the command, then sends the finished file to the swarm. This lesson covers the syntax, the traps (some of them different from docker compose), and how to check the result with docker stack config.

The syntax

Form Value when VAR is unset when set but empty when set to x
${VAR} or $VAR empty string, no warning empty x
${VAR:-default} default default x
${VAR-default} default empty x
${VAR:?message} error, deploy stops error x
${VAR?message} error empty x
$ a literal $ (not interpolated)

The examples on this page run with an empty environment, so every variable is unset. Here is what that does to a typical file:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:${TAG}
    environment:
      LOG_LEVEL: ${LOG_LEVEL:-info}
      REGION: ${REGION-eu-west-1}
      GREETING: "costs $5"
    deploy:
      replicas: ${API_REPLICAS:-2}
version: "3.13"
services:
  api:
    deploy:
      replicas: 2
    environment:
      GREETING: costs $5
      LOG_LEVEL: info
      REGION: eu-west-1
    image: 'ghcr.io/acme/shop-api:'

Look at the image: ghcr.io/acme/shop-api: with an empty tag, and not a single warning. docker compose would at least print The "TAG" variable is not set; the stack loader stays silent. replicas: ${API_REPLICAS:-2} became the number 2, because the value is substituted before the schema check. $5 came out as $5.

Required variables

For values that must never default, use :?. The deploy stops before anything is sent to the cluster:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:${TAG:?set TAG to the release to deploy}
    deploy:
      replicas: 3
invalid interpolation format for services.api.image: "required variable TAG is missing a value: set TAG to the release to deploy"; you may need to escape any $ with another $

Make every variable that has no safe default required. An empty image tag or an empty hostname is much harder to debug after the deploy than an error before it.

.env files are NOT read

docker compose automatically loads a .env file next to the Compose file. docker stack deploy does not. The same folder, two commands:

compose · try it yourself
# $ docker compose config
# $ docker stack config -c compose.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:${TAG:-latest}
# --- .env
TAG=2.4.1
$ docker compose config
name: demo
services:
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    networks:
      default: null
networks:
  default:
    name: demo_default
$ docker stack config -c compose.yaml
version: "3.13"
services:
  api:
    image: ghcr.io/acme/shop-api:latest

Compose used TAG=2.4.1 from .env; the stack fell back to latest. To deploy with values from a file, export them into the shell first:

bash
$ set -a; . ./prod.env; set +a       # export every variable the file defines
$ docker stack config -c stack.yaml | grep image:
    image: ghcr.io/acme/shop-api:2.4.1
$ docker stack deploy -c stack.yaml shop

(sample output.) In CI, the pipeline's own environment variables play this role: TAG=$CI_COMMIT_SHA docker stack deploy ….

env_file: is different: it is not interpolation, it is a list of variables put into the containers. The stack loader reads the file at deploy time and merges it into environment (keys in environment: win):

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    env_file: ./api.env
    environment:
      LOG_LEVEL: warn
# --- api.env
LOG_LEVEL=debug
CACHE_TTL=300
version: "3.13"
services:
  api:
    environment:
      CACHE_TTL: "300"
      LOG_LEVEL: warn
    env_file:
      - ./api.env
    image: ghcr.io/acme/shop-api:2.4.1

No nested defaults

docker compose accepts a default that is itself a variable, ${A:-${B:-x}}. The stack loader uses an older interpolation engine that doesn't, and produces a surprising result instead of an error:

compose · try it yourself
# $ docker compose config --no-normalize
# $ docker stack config -c compose.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    environment:
      DB_HOST: ${DB_HOST:-${DEFAULT_DB_HOST:-db}}
$ docker compose config --no-normalize
name: demo
services:
  api:
    environment:
      DB_HOST: db
    image: ghcr.io/acme/shop-api:2.4.1
$ docker stack config -c compose.yaml
version: "3.13"
services:
  api:
    environment:
      DB_HOST: ${DEFAULT_DB_HOST:-db}
    image: ghcr.io/acme/shop-api:2.4.1

Compose resolved the inner default to db. The stack loader stopped at the first } and kept the rest as text, so the container would receive a literal ${DEFAULT_DB_HOST:-db} as its database host. Keep stack defaults flat.

Swarm templates are not variables

Some values contain {{ … }} placeholders that Swarm itself fills in per task, long after interpolation: {{.Node.Hostname}}, {{.Service.Name}}, {{.Task.Slot}}. They are allowed in hostname, environment and mount sources. Interpolation leaves them untouched, and so does --skip-interpolation, which prints the file with every ${…} left as written:

compose · try it yourself
# $ docker stack config -c stack.yaml --skip-interpolation
# --- stack.yaml
services:
  worker:
    image: ghcr.io/acme/shop-worker:${TAG:?required}
    hostname: "{{.Service.Name}}-{{.Task.Slot}}"
    environment:
      NODE_NAME: "{{.Node.Hostname}}"
      QUEUE: ${QUEUE:-orders}
version: "3.13"
services:
  worker:
    environment:
      NODE_NAME: '{{.Node.Hostname}}'
      QUEUE: ${QUEUE:-orders}
    hostname: '{{.Service.Name}}-{{.Task.Slot}}'
    image: ghcr.io/acme/shop-worker:${TAG:?required}

With --skip-interpolation, even the ${TAG:?required} error doesn't fire, which makes the flag handy for checking a file's structure in CI before the variables are known.

A model of the interpolation rules

This small Python function implements the table above (flat forms only), useful to reason about edge cases:

python · try it yourself
import re

PATTERN = re.compile(r"\$\$|\$\{(\w+)(?:(:?[-?])([^}]*))?\}|\$(\w+)")

def interpolate(text, env):
    def repl(m):
        if m.group(0) == "$":
            return "
quot; name = m.group(1) or m.group(4) op, arg = m.group(2), m.group(3) value = env.get(name) unset_or_empty = value is None or (op and op.startswith(":") and value == "") if op in (":-", "-") and unset_or_empty: return arg if op in (":?", "?") and unset_or_empty: raise ValueError(f"required variable {name} is missing a value: {arg}") return value or "" return PATTERN.sub(repl, text) env = {"TAG": "2.4.1", "EMPTY": ""} for text in ["api:${TAG}", "api:${MISSING}", "${EMPTY:-fallback}", "${EMPTY-fallback}", "costs $5", "${MISSING:?set it}"]: try: print(f"{text:<20} -> {interpolate(text, env)!r}") except ValueError as e: print(f"{text:<20} -> error: {e}")
api:${TAG}           -> 'api:2.4.1'
api:${MISSING}       -> 'api:'
${EMPTY:-fallback}   -> 'fallback'
${EMPTY-fallback}    -> ''
costs $5            -> 'costs $5'
${MISSING:?set it}   -> error: required variable MISSING is missing a value: set it

A checklist for CI

  1. docker stack config -c stack.yaml --skip-interpolation > /dev/null: is the file valid at all?
  2. Export the environment's variables, then docker stack config -c stack.yaml -c prod.yaml: are they all set, and does the result look right? Save the output as a build artifact: it is exactly what will be deployed.
  3. grep -E ':$|: ""
    #39;
    over that output to catch values that became empty.
  4. Only then docker stack deploy.

Learn more: Compose interpolation · Stack Files & deploy · Updating Stacks

Test yourself

A stack file uses image: shop/api:${TAG} and TAG is not set. What does docker stack deploy do?

  1. Fails with an error
  2. Uses shop/api:latest and warns
  3. Uses shop/api: with an empty tag, without a warning
  4. Asks for the value

Your folder contains stack.yaml and .env with TAG=2.4.1. What does docker stack deploy -c stack.yaml shop use for ${TAG:-latest}?

  1. 2.4.1
  2. latest
  3. an empty string
  4. an error

What does docker stack config --skip-interpolation print for {{.Task.Slot}} and ${QUEUE:-orders}?

  1. 1 and orders
  2. Both unchanged
  3. {{.Task.Slot}} unchanged and orders
  4. An error