What is Docker Swarm? Give an Example

What is Docker Swarm? Give an Example

Docker Swarm helps manage groups of Docker hosts and lets you run and control containerized apps on many machines. It offers useful features like finding services, balancing loads, scaling, updating smoothly, and handling errors. Docker Swarm works well with the Docker system, so it's easy to use and fits with current Docker processes.

Example: Let's look at a basic example of creating a Docker Swarm group and running a simple web service on several nodes.

  1. Set up Docker Swarm Cluster: You need multiple Docker hosts to create a Swarm cluster. For this example, let's assume you have three hosts with Docker installed and network connectivity between them.

    Initialize the Swarm on the manager node:

     docker swarm init --advertise-addr <manager-node-ip>

    This command initializes the Swarm on the manager node and generates a token for joining worker nodes. Make a note of the join token displayed in the output.

    Join worker nodes to the Swarm using the join token:

     docker swarm join --token <worker-token> <manager-node-ip>:2377

    Replace <worker-token> with the join token generated during initialization and <manager-node-ip> with the IP address of the manager node.

  2. Deploy a Service: Once the Swarm cluster is set up, you can deploy services across the cluster. Let's deploy a simple web service using the nginx Docker image.

    Create a Docker Compose file named docker-compose.yml:

     version: '3.8'
         image: nginx:latest
           - "80:80"

    This Compose file defines a single service (nginx) using the nginx:latest Docker image, which listens on port 80 and forwards requests to port 80 inside the container.

    Deploy the service to the Swarm cluster:

     docker stack deploy -c docker-compose.yml mywebapp

    This command deploys the service defined in the docker-compose.yml file as a stack named mywebapp in the Swarm cluster.

  3. Scale the Service: Docker Swarm allows you to scale services horizontally by increasing the number of replicas. Let's scale the nginx service to have three replicas:

     docker service scale mywebapp_nginx=3

    This command scales the nginx service to have three replicas running across the Swarm cluster.

  4. Access the Service: Now that the service is deployed and scaled, you can access it through any of the Swarm nodes. Use the IP address of any node in the Swarm cluster to access the web service.

    Open a web browser and navigate to http://<node-ip> to access the web service deployed by the nginx service.

This example shows how to set up and deploy a Docker Swarm cluster and a simple web service across the cluster. Docker Swarm offers more advanced features for managing and organizing containerized apps in production environments.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!