Stacks
Creating services one by one with docker service create is fine for experiments, but a real application is a set of services plus their networks, volumes, configs and secrets, and that set should live in a file under version control. A stack is exactly that: a group of Swarm objects described in one Compose-format file and deployed, updated and removed together with docker stack commands.
If you know Docker Compose, you already know 90% of the file format. The difference is who acts on it: Compose talks to one Docker engine and starts containers; docker stack deploy sends the file to a swarm manager, which creates services that the orchestrator schedules across the cluster.
The stack commands
| Command | What it does |
|---|---|
docker stack deploy -c stack.yaml shop |
create or update the stack shop from the file |
docker stack ls |
list stacks and how many services each has |
docker stack services shop |
the stack's services with replica counts |
docker stack ps shop |
every task of the stack, with node and state |
docker stack config -c stack.yaml |
print the final file after merging and interpolation, without deploying |
docker stack rm shop |
remove the services, networks, configs and secrets of the stack |
All of them (except config) must run against a manager.
A first stack
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
web:
image: ghcr.io/acme/shop-web:3.2.0
ports:
- "80:8000"
environment:
API_URL: http://api:9000
deploy:
replicas: 3
api:
image: ghcr.io/acme/shop-api:2.4.1
deploy:
replicas: 2
redis:
image: redis:8-alpineversion: "3.13"
services:
api:
deploy:
replicas: 2
image: ghcr.io/acme/shop-api:2.4.1
redis:
image: redis:8-alpine
web:
deploy:
replicas: 3
environment:
API_URL: http://api:9000
image: ghcr.io/acme/shop-web:3.2.0
ports:
- mode: ingress
target: 8000
published: 80
protocol: tcp
docker stack config is your safety net: it parses the file exactly as deploy will (same schema, same interpolation, same merging of multiple -c files) and prints the result, or the error, without touching any cluster. Use it in CI on every change. Note the version: "3.13" line it adds: stacks still use the legacy Compose file format 3.x schema, which is older and stricter than the Compose Specification that docker compose follows. The next lesson covers what that means.
Deploying it:
$ docker stack deploy -c stack.yaml shop
Creating network shop_default
Creating service shop_web
Creating service shop_api
Creating service shop_redis
$ docker stack services shop
ID NAME MODE REPLICAS IMAGE PORTS
u2v7x9k1m4pq shop_api replicated 2/2 ghcr.io/acme/shop-api:2.4.1
d8r3t6y0w5ez shop_redis replicated 1/1 redis:8-alpine
j4h1g7f2s9al shop_web replicated 3/3 ghcr.io/acme/shop-web:3.2.0 *:80->8000/tcp
$ docker stack ps shop --format 'table {{.Name}}\t{{.Node}}\t{{.CurrentState}}'
NAME NODE CURRENT STATE
shop_api.1 node-2 Running 40 seconds ago
shop_api.2 node-3 Running 40 seconds ago
shop_redis.1 node-1 Running 41 seconds ago
shop_web.1 node-1 Running 38 seconds ago
shop_web.2 node-2 Running 38 seconds ago
shop_web.3 node-3 Running 38 seconds ago(sample output.)
Namespacing: everything gets the stack prefix
Every object a stack creates is named <stack>_<key> and labelled com.docker.stack.namespace=<stack>. That's how two stacks can both have a service called api and a network called default, and how docker stack rm knows what to delete. Inside the stack, services still find each other by the short name (http://api:9000 above), because the stack adds the short names as DNS aliases on its networks.
stack_file = {
"services": ["web", "api", "redis"],
"networks": ["default", "back"],
"configs": ["nginx_conf"],
"secrets": ["db_password"],
"volumes": ["pgdata"],
}
external = {"secrets": {"db_password"}} # created outside the stack: not prefixed, not owned
def objects(stack):
for kind, keys in stack_file.items():
for key in keys:
if key in external.get(kind, set()):
yield kind, key, "external (used, never created or removed)"
else:
yield kind, f"{stack}_{key}", f"label com.docker.stack.namespace={stack}"
for stack in ("shop", "shop-staging"):
print(f"docker stack deploy -c stack.yaml {stack}")
for kind, name, note in objects(stack):
print(f" {kind:<9} {name:<26} {note}")docker stack deploy -c stack.yaml shop
services shop_web label com.docker.stack.namespace=shop
services shop_api label com.docker.stack.namespace=shop
services shop_redis label com.docker.stack.namespace=shop
networks shop_default label com.docker.stack.namespace=shop
networks shop_back label com.docker.stack.namespace=shop
configs shop_nginx_conf label com.docker.stack.namespace=shop
secrets db_password external (used, never created or removed)
volumes shop_pgdata label com.docker.stack.namespace=shop
docker stack deploy -c stack.yaml shop-staging
services shop-staging_web label com.docker.stack.namespace=shop-staging
services shop-staging_api label com.docker.stack.namespace=shop-staging
services shop-staging_redis label com.docker.stack.namespace=shop-staging
networks shop-staging_default label com.docker.stack.namespace=shop-staging
networks shop-staging_back label com.docker.stack.namespace=shop-staging
configs shop-staging_nginx_conf label com.docker.stack.namespace=shop-staging
secrets db_password external (used, never created or removed)
volumes shop-staging_pgdata label com.docker.stack.namespace=shop-staging
The same file deployed twice under different names gives two independent copies, a cheap way to run a staging environment on the same cluster (as long as published ports differ).
Removing a stack
$ docker stack rm shop
Removing service shop_api
Removing service shop_redis
Removing service shop_web
Removing network shop_default(sample output.) Named volumes are not removed (data is precious), and neither are external networks, configs or secrets. The command returns before the containers have actually stopped: if you redeploy immediately, the old network may still be "in use" for a few seconds.
Stacks vs Compose vs Kubernetes
docker compose up |
docker stack deploy |
kubectl apply / Helm |
|
|---|---|---|---|
| Target | one Docker engine | a swarm | a Kubernetes cluster |
| File | Compose Specification | Compose file format 3.x (deploy: honoured) |
Kubernetes manifests / charts |
| Builds images | yes (build:) |
no, images must be in a registry | no |
| Unit of deployment | containers | services and tasks | Deployments, Pods, Services… |
| Grouping | project name | stack name prefix | namespaces, labels, Helm releases |
So the usual workflow is: build and push images in CI, then deploy the stack file that references them by tag (or digest). Moving from Compose to a stack is covered in Compose to Swarm; from a stack to Kubernetes in From Compose & Swarm.
Learn more: Stack Files & deploy · Stack Variables & docker stack config · Updating Stacks
Test yourself
In stack shop, what is the real name of the service declared as api?
apishop-apishop_apiapi.shop
What does docker stack config -c stack.yaml do?
- Deploys the stack in dry-run mode on the managers
- Prints the final, interpolated file (or the validation error) without contacting a swarm
- Shows the configs of a running stack
- Converts the file to Kubernetes YAML
What survives docker stack rm shop?
- Nothing
- The stack's named volumes and any external networks, configs and secrets
- Only the services
- Only the overlay networks