Back
3/4

Stacks & Secrets

+20 XP on completion

#Stacks & Secrets

After this lesson you'll know:

  • how to use Compose files in Swarm
  • what docker stack deploy is
  • how to manage secrets securely

#From compose to stack

Your docker-compose.yml works almost 1:1 in Swarm. The command is just different:

# Instead of:
docker compose up -d

# In Swarm:
docker stack deploy -c docker-compose.yml my-stack

#Compose for Swarm

# stack.yml
services:
  web:
    image: nginx
    ports:
      - "80:80"
    deploy:
      replicas: 3
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: any

  api:
    image: my-api:latest
    secrets:
      - db_password
    deploy:
      replicas: 2
      placement:
        constraints:
          - node.role == worker

secrets:
  db_password:
    file: ./db_password.txt
docker stack deploy -c stack.yml production-stack
docker stack ls
docker stack services production-stack
docker stack ps production-stack
docker stack rm production-stack

#Docker Secrets — safe and simple

Secrets are encrypted, only distributed to nodes that need them, and never baked into the image:

# Create a secret
echo "super-secure-password" | docker secret create db_password -

# Use the secret in a service
docker service create   --name api   --secret db_password   --replicas 3   my-api

# Inside the container, the secret is at /run/secrets/db_password
# cat /run/secrets/db_password

#Docker Configs (for non-secret data)

# For configuration files (e.g. nginx.conf)
docker config create nginx.conf ./nginx.conf

docker service create   --name web   --config src=nginx.conf,target=/etc/nginx/nginx.conf   nginx

Configs are like Secrets — but for non-sensitive configuration.


#✋ Try it out

  • Create a stack.yml with an nginx service (3 replicas) and deploy with docker stack deploy -c stack.yml my-test. Check with docker stack ls
  • Add a secret: echo "my-password" | docker secret create test_pw -. Use it in a service with --secret test_pw and read it inside the container with cat /run/secrets/test_pw
  • Remove the stack with docker stack rm my-test

#📌 Summary

  • docker stack deploy uses Compose files in Swarm
  • Secrets live under /run/secrets/ and are never baked into the image
  • Configs = Secrets without encryption — for configuration files
← → to navigate