Selected topic

Docker Swarm

Container Orchestration

Prefer practical output? Use related tools below while reading.

Docker Swarm is a container orchestration tool provided by Docker that allows you to deploy and manage multiple containers across a cluster of machines. It's designed to scale your applications easily, efficiently, and reliably.

Key Features:


  1. Cluster Management: Create and manage clusters of Docker hosts.
  2. Service Definition: Define services as a collection of containers with specific configurations.
  3. Scaling: Scale services up or down based on demand.
  4. Load Balancing: Automatically distribute traffic across multiple containers.
  5. Self-healing: If a container fails, the service will automatically restart it.

Example: Deploying a simple web application


Let's consider a simple example of deploying a web application using Docker Swarm.

Step 1: Create a Dockerfile for the web application


dockerfile
FROM nginx:latest

COPY index.html /usr/share/nginx/html/

EXPOSE 80


This Dockerfile builds an Nginx image with our index.html file inside.

Step 2: Build and push the Docker image to a registry (e.g., Docker Hub)


bash
docker build -t my-web-app .
docker tag my-web-app:latest <username>/my-web-app:latest
docker push <username>/my-web-app:latest

Step 3: Create a docker-compose.yml file for the service definition


yml
version: '3'
services:
web:
image: <username>/my-web-app:latest
ports:
- "80:80"

This docker-compose.yml file defines a single service called web that uses our custom Docker image.

Step 4: Initialize the Swarm cluster and join nodes to it


Create a new directory for your swarm cluster, navigate into it, and run:
bash
docker swarm init
docker swarm join --token <join-token> <manager-node-ip>

This initializes the Swarm cluster and joins the node to it.

Step 5: Deploy the service to the Swarm cluster


bash
docker stack deploy -c docker-compose.yml my-web-app-stack

This deploys our web service to the Swarm cluster. You can verify that the containers are running by checking the Swarm logs:
bash
docker ps -a --format "table {{.Names}}"

Step 6: Scale and manage the service


To scale the service, use:
bash
docker service scale my-web-app-stack_web=3

This will deploy three replicas of our web service.

That's a basic overview of deploying an application with Docker Swarm!