What is Docker Swarm ?

ยท

2 min read

Docker Swarm is a native clustering and orchestration solution for Docker. It turns a pool of Docker hosts into a single, virtual Docker host, allowing you to deploy and manage applications across multiple machines with ease.

Key Concepts

Before diving into examples, let's familiarize ourselves with some key concepts:

  1. Node: A machine in the Swarm cluster (can be a manager or worker)

  2. Manager Node: Responsible for cluster management and orchestration

  3. Worker Node: Executes containers

  4. Service: The definition of tasks to execute on nodes

  5. Task: A Docker container and the commands to run inside it

Setting Up a Docker Swarm

Let's start by creating a simple Swarm cluster:

# Initialize a swarm on the manager node
docker swarm init --advertise-addr <MANAGER-IP>

# This command will output a token to add worker nodes
# On each worker node, run:
docker swarm join --token <TOKEN> <MANAGER-IP>:2377

# To view nodes in the swarm (run on manager)
docker node ls

Deploying a Service

Now that we have our Swarm set up, let's deploy a simple web service:

# Create a service with 3 replicas
docker service create --name my-web-app --replicas 3 -p 80:80 nginx

# List services
docker service ls

# Inspect the service
docker service ps my-web-app

Scaling a Service

One of the key benefits of Docker Swarm is easy scaling:

# Scale the service to 5 replicas
docker service scale my-web-app=5

# Verify the scaling
docker service ps my-web-app

Rolling Updates

Docker Swarm makes it easy to perform rolling updates:

# Update the image of our service
docker service update --image nginx:alpine my-web-app

# Watch the rolling update in action
docker service ps my-web-app

Creating a Multi-Service Stack

For more complex applications, we can use Docker Compose with Swarm mode:

version: '3'
services:
  web:
    image: nginx
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
      restart_policy:
        condition: on-failure
    ports:
      - "80:80"
  visualizer:
    image: dockersamples/visualizer
    ports:
      - "8080:8080"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
    deploy:
      placement:
        constraints: [node.role == manager]

Save this as docker-compose.yml and deploy with:

docker stack deploy -c docker-compose.yml my-stack

Conclusion

Docker Swarm provides a robust and user-friendly solution for container orchestration. With its built-in load balancing, service discovery, and rolling updates, it's an excellent choice for teams looking to scale their containerized applications.

ย