Module 12 Lesson 3: Services and Stacks
·DevOps

Module 12 Lesson 3: Services and Stacks

Master the administrative units of Swarm. Learn how to define 'Services' for individual apps and 'Stacks' for entire multi-container architectures.

Module 12 Lesson 3: Services and Stacks

In a Swarm cluster, we don't use the word "Container." We use Services and Stacks.

1. What is a Service?

A Service is the definition of a Task. It includes:

  • The Image to use.
  • The number of Replicas (copies).
  • The Port mappings.
  • The Update Strategy (e.g., "Replace one per minute").
docker service create --name web --replicas 5 -p 80:80 nginx

Docker will ensure that 5 instances are running somewhere in the cluster at all times.


2. What is a Stack?

A Stack is a collection of Services that work together (e.g., your Web + DB + Redis).

  • The Best Part: Stacks use the same docker-compose.yml file format we learned in Module 5!
docker stack deploy -c docker-compose.yml my-awesome-app
  • -c: Considers the Compose file.
  • my-awesome-app: The namespace (Stack Name).

Visualizing the Process

graph TD
    Start[Input] --> Process[Processing]
    Process --> Decision{Check}
    Decision -->|Success| End[Complete]
    Decision -->|Retry| Process

3. Rolling Updates (Zero Downtime)

When you want to update your web app from v1 to v2:

  • In a single container, the site goes down while the new one starts.
  • In Swarm, you run: docker service update --image my-app:v2 web.
  • Swarm stops one v1 container, starts one v2, verifies it's healthy, and then moves to the next. The site stays up 100% of the time.

4. The Routing Mesh

This is Swarm’s "Secret Sauce."

  • If you publish port 80 on your cluster, every node in the cluster will listen on port 80, even if the Nginx container isn't running on that specific node.
  • If a user hits "Server B," but the container is on "Server A," Docker automatically forwards the request internally. This is the Routing Mesh.

Exercise: Scaling Up and Down

  1. Run docker swarm init (if you haven't already).
  2. Launch a service with 2 replicas: docker service create --name scale-test --replicas 2 alpine sleep 1000.
  3. Check the status: docker service ls.
  4. Scale it to 10: docker service scale scale-test=10.
  5. Watch the containers start: docker service ps scale-test.
  6. Force a "Failure": docker rm -f <one_of_the_tasks_ids>.
  7. Check docker service ps again. Did Swarm automatically start a replacement? How long did it take?

Summary

Services and Stacks allow you to treat your entire application as a single entity. By defining your "Desired State" in a Compose file and deploying it as a Stack, you gain the production-grade benefits of self-healing and zero-downtime updates with almost no extra work.

Next Lesson: The world standard: Introduction to Kubernetes (K8s) basics.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn