# Docker Swarm

[Docker](https://www.dataquest.io/blog/install-and-configure-docker-swarm-on-ubuntu/) [Swarm](https://docs.docker.com/engine/swarm/) is [Docker's](https://docs.ansible.com/ansible/2.9/modules/docker_swarm_info_module.html) built-in container orchestration tool that helps manage containerized applications in a production environment. It allows you to create and manage a cluster of [Docker](https://thalesdocs.com/dpod/services/integrations/docker/swarm/index.html) nodes, known as a [Swarm](https://docs.docker.com/engine/reference/commandline/swarm/), and deploy containerized services across these nodes

### Components of [Docker](https://aws.plainenglish.io/using-aws-to-create-a-docker-swarm-b48731c850c) [Swarm](https://docs.docker.com/engine/swarm/swarm-tutorial/)

* [**Swarm**](https://docs.docker.com/engine/swarm/key-concepts/) **Manager**
    
* **Worker Nodes**
    

## [Swarm](https://docs.docker.com/engine/reference/commandline/swarm/) Manager

The cluster is orchestrated and managed by the [Swarm](https://www.simplilearn.com/tutorials/docker-tutorial/docker-swarm) Manager. There is usually only one management node, however, many managers can be configured for high availability. It manages failover, schedules services, and saves the cluster state.

### Key responsibilities and characteristics of the [Swarm](https://www.sumologic.com/glossary/docker-swarm/) Manager

* **Cluster Creation and Management**
    
* **Node Membership**
    
* **Service Scheduling**
    
* **Cluster State and Consistency**
    
* **Load Balancing**
    
* **Health Monitoring**
    
* **Rolling Updates**
    
* **Secrets Management**
    
* **Interactions with Workers**
    
* [**Swarm**](https://www.techtarget.com/searchitoperations/definition/Docker-Swarm) **API**
    
* [**Swarm**](https://www.geeksforgeeks.org/introduction-to-docker-swarm-mode/) **Dashboard**
    
* **Cluster Creation and Management:** When setting up a [Docker](https://www.googleadservices.com/pagead/aclk?sa=L&ai=DChcSEwiw55n0ttyBAxW4qGYCHc4MBX0YABAAGgJzbQ&gclid=Cj0KCQjwmvSoBhDOARIsAK6aV7jyFOabOKUFvPq9zUem1KZFnw70-6AqYhTbHYGSMCX28x940j78HqMaAmN9EALw_wcB&ohost=www.google.com&cid=CAESVeD2nNJkfx7s82ZK-YZVW2YRGw0nQXW6gFN8Lj22ejHOfJvdiyH1hVZLW1lpGVyd5JZ2C8w0VnqLaQkXfrnlQdGZLQdo0z8s8Zt2CXDnV_qLnyBcsKw&sig=AOD64_32DoHmgMy3f--b0mRvEWp5tynJtA&q&adurl&ved=2ahUKEwjU-pP0ttyBAxXO3jgGHaopAOA4PBDRDHoECAAQAQ) [Swarm](https://circleci.com/blog/docker-swarm-vs-kubernetes/) cluster, the [Swarm](https://www.digitalocean.com/community/tutorials/how-to-create-a-cluster-of-docker-containers-with-docker-swarm-and-digitalocean-on-ubuntu-16-04) Manager is critical in building and controlling the cluster. You may start a [Swarm](https://semaphoreci.com/community/tutorials/running-applications-on-a-docker-swarm-mode-cluster) by issuing the following command to a node.
    

```dockerfile
docker swarm init
```

* **Node Membership:** The [Swarm](https://www.javatpoint.com/docker-swarm) Manager coordinates the addition of a worker node to the [Swarm](https://www.vultr.com/docs/install-and-configure-docker-swarm-on-ubuntu-20-04-lts/?utm_source=performance-max-apac&utm_medium=paidmedia&obility_id=16876059738&utm_adgroup=&utm_campaign=&utm_term=&utm_content=&gclid=Cj0KCQjwmvSoBhDOARIsAK6aV7g17qa7CT9dnWo6HfGvrzaRCmhINmUQCsE7WOJPXgMXeOtlLsIjPh8aAtMVEALw_wcB) cluster.
    

```dockerfile
docker swarm join --token <worker-token> <manager-ip>:<manager-port>
```

* **Service Scheduling:** When you deploy a service to a [Swarm](https://www.aquasec.com/cloud-native-academy/docker-container/docker-swarm/) cluster, the [Swarm](https://www.section.io/engineering-education/introduction-to-docker-swarm-in-container-orchestration/) Manager decides which worker nodes should perform the service activities based on limitations and resource availability.
    
* **Cluster State and Consistency:** The [Swarm](https://dockerswarm.rocks/) Manager keeps a distributed database of information about services, tasks, and nodes. It guarantees data consistency and dependability throughout the cluster.
    
* **Load Balancing:** The [Swarm](https://www.mirantis.com/cloud-native-concepts/understanding-docker-swarm/what-is-docker-swarm/) Manager configures services for automated load balancing. For example, if you run a web application in many containers, incoming requests are distributed evenly among the containers.
    
* **High Availability:** You can configure multiple [Swarm](https://www.toptal.com/devops/software-deployment-docker-swarm-tutorial) Managers for high availability. If one manager node fails, another can take over.
    
* **Health Monitoring:** The [Swarm](https://vsupalov.com/what-is-docker-swarm/) Manager constantly checks the status of containers and worker nodes. When a node or container gets ill, it might reassign work to healthy nodes.
    
* **Rolling Updates:** The [Swarm](https://www.atatus.com/glossary/docker-swarm/) Manager allows you to execute rolling upgrades on services. It guarantees that new versions of containers are gradually deployed while service availability is maintained.
    
* **Secrets Management:** The [Swarm](https://sysdig.com/learn-cloud-native/container-security/what-is-docker-swarm/) Manager handles secrets such as API keys, passwords, and certificates in a safe manner and makes them available to services without exposing them in plaintext.
    
* **Interactions with Workers:** To launch, halt, and manage containers, the [Swarm](https://www.educative.io/courses/docker-for-web-developers/docker-swarm?utm_campaign=brand_educative&utm_source=google&utm_medium=ppc&utm_content=performance_max_india&eid=5082902844932096&utm_term=&utm_campaign=%5BNew%5D+Performance+Max&utm_source=adwords&utm_medium=ppc&hsa_acc=5451446008&hsa_cam=18931439518&hsa_grp=&hsa_ad=&hsa_src=x&hsa_tgt=&hsa_kw=&hsa_mt=&hsa_net=adwords&hsa_ver=3&gclid=Cj0KCQjwmvSoBhDOARIsAK6aV7iFQlh5Nzc8jY8UZxbLcOrYcnC3IBRl34jr25h0U895GTN4RaKxhOQaAu70EALw_wcB) Manager talks with worker nodes. Based on service settings, it provides instructions to worker nodes.
    
* [**Swarm**](https://k21academy.com/docker-kubernetes/docker-swarm/) **API:** The [Swarm](https://www.amazon.in/s?k=docker+swarm&adgrpid=58679720853&ext_vrnc=hi&hvadid=590226604977&hvdev=c&hvlocphy=9299829&hvnetw=g&hvqmt=e&hvrand=14381894984130664637&hvtargid=kwd-100040026646&hydadcr=18656_2248887&tag=googinhydr1-21&ref=pd_sl_9l73exb4vl_e) Manager provides a RESTful API that allows developers to connect with and operate the [Swarm](https://www.educative.io/answers/what-is-docker-swarm) cluster programmatically.
    
* [**Swarm**](https://www.udemy.com/course/docker-swarm-mastery/) **Dashboard:** The [Swarm](https://gabrieltanner.org/blog/docker-swarm/) Manager provides a web-based GUI dubbed the "[**<mark>Swarm</mark>**](https://data-flair.training/blogs/docker-swarm/) **<mark> Dashboard</mark>**" for convenient cluster administration and monitoring. It shows the cluster's status, services, and nodes in graphical form.
    

## Worker Nodes

These are the worker computers that deploy and operate containers. Worker nodes undertake duties like as executing containers and scaling services based on instructions from the [Swarm](https://www.ibm.com/docs/kk/SSD29G_2.0.0/com.ibm.swg.ba.cognos.tm1_inst.2.0.0.doc/paw_distributed_creating_docker_swarm.html) Manager.

* **Container Execution**
    
* **Scalability**
    
* **Health Checks**
    
* **Resource Managemen**
    
* **Load Balancing**
    
* **Container Network Connectivity**
    
* [**Swarm**](https://dockerlabs.collabnix.com/intermediate/workshop/getting-started-with-swarm.html) **Joins**
    
* **Resource Isolation**
    
* **Scaling Services**
    
* **Service Updates**
    
* **Logging and Monitoring**
    
* [**Swarm**](https://www.redswitches.com/blog/docker-swarm/) **Exit and Rejoin**
    
* **Container Execution:** Worker nodes are in charge of operating containers. For example, if you deploy a web server as a [Docker](https://dev.to/afif_ahmed/everything-you-need-to-know-about-docker-swarm-3dck) service, the containerized instances of the web server are executed and managed by the worker nodes.
    
* **Scalability:** When the demand for a service increases, worker nodes may automatically scale the number of container replicas to accommodate the load. This assures the application's responsiveness.
    

```bash
docker service scale <service-name>=<desired-replica-count>
```

* **Health Checks:** Worker nodes execute health checks on running containers regularly. If a container fails its health check, the worker node can swap it out with a healthy one, ensuring that only functioning containers serve traffic.
    
* **Resource Management:** Worker nodes handle CPU, memory, and other container resources. They allocate resources depending on the restrictions and constraints provided in service setups.
    
* **Load Balancing:** Worker nodes help with load balancing by spreading incoming requests across several service replicas. This prevents any single container from becoming overcrowded.
    
* **Container Network Connectivity:** Worker nodes guarantee that containers inside the [Swarm](https://geekflare.com/docker-swarm/) network may interact with one another. They are in charge of containerized apps' network routing and connection.
    
* [**Swarm**](https://www.chakray.com/key-differences-between-docker-and-docker-swarm-in-container-management-and-orchestration/) **Joins:** Worker nodes join the Docker Swarm cluster by connecting to the [Swarm](https://betterstack.com/community/guides/scaling-docker/ha-docker-swarm/) manager(s) and using the manager's join token. This enables them to join the cluster and participate in service orchestration.
    
* **Resource Isolation:** Worker nodes keep containers' resources isolated. Containers on the same node do not compete for resources, maintaining constant performance.
    
* **Scaling Services:** Worker nodes can scale up or down services based on demand. For example, if the traffic to a web application increases, extra container replicas can be launched on available worker nodes.
    
* **Service Updates:** During service upgrades, worker nodes replace old container instances with new ones, ensuring that service downtime is kept to a minimum. This is accomplished by rolling updates, which are coordinated by worker nodes.
    
* **Logging and Monitoring:** Worker nodes are responsible for generating logs and metrics for containers and services. These logs and data may be gathered and examined to monitor the [Swarm](https://techblog.geekyants.com/an-introduction-to-docker-swarm) cluster's health and performance.
    
* [**Swarm**](https://techblog.geekyants.com/an-introduction-to-docker-swarm) **Exit and Rejoin:** Worker nodes can gracefully leave the [Swarm](https://bluexp.netapp.com/blog/cvo-blg-docker-vs-openshift-or-docker-swarm-vs-openshift) cluster and, if needed, rejoin it. This feature allows for flexibility and adaptability in case nodes need to be temporarily taken offline for maintenance or other reasons.
    

### Step-by-step guide for deployment of a simple web application to handle increased traffic

[Docker](https://blog.tericcabrel.com/manage-docker-container-with-swarm/) [Swarm](https://toolsqa.com/docker/docker-swarm/) distributes the load across a cluster, deploying five web service instances for fault tolerance and scalability, enabling the deployment of a simple web application to handle increased traffic.

**Step 1: Prepare Your Web Application**

```bash
mywebapp/
   ├── app.py
   ├── requirements.txt
   └── Dockerfile
```

The [`app.py`](http://app.py) contains your web application code, and the `requirements.txt` lists the Python dependencies. Your `Dockerfile` contains instructions for building a [Docker](https://www.linkedin.com/pulse/docker-swarm-mesut-oezdil/) image for your application.

**Step 2: Initialize** [**Docker**](https://www.pluralsight.com/cloud-guru/labs/aws/building-a-docker-swarm?utm_source=google&utm_medium=paid-search&utm_campaign=upskilling-and-reskilling&utm_term=ssi-apac-in-dynamic&utm_content=free-trial&gclid=Cj0KCQjwmvSoBhDOARIsAK6aV7ij0UZxribG9kPfSsx7xhB4fhCBLg5CM3RcAxjabwPaJw8IeO53MCUaAsk9EALw_wcB) [**Swarm**](https://cloudacademy.com/course/container-orchestration-with-docker-swarm-mode/course-introduction-11/?utm_feeditemid=&utm_device=c&utm_term=&utm_campaign=%5BSearch%5D+DSA+-+All+Website+-+India&utm_source=google&utm_medium=ppc&hsa_acc=5890858304&hsa_cam=13996404894&hsa_grp=128133670034&hsa_ad=651406237901&hsa_src=g&hsa_tgt=dsa-19959388920&hsa_kw=&hsa_mt=&hsa_net=adwords&hsa_ver=3&gclid=Cj0KCQjwmvSoBhDOARIsAK6aV7j0X8KjrMVLJPtFSCs9Hm-8Tgp9fMo7mprW-e1p1DIcFevfZo8mUVwaApMAEALw_wcB) **(if not already done):**

A Docker [Swarm](https://github.com/dockersamples/docker-swarm-visualizer) cluster requires at least two machines, one for the manager node and multiple for worker nodes, which can be virtual, cloud, or physical.

```bash
docker swarm init
```

This command starts [Docker](https://betterprogramming.pub/hands-on-guide-containers-orchestration-with-docker-swarm-27b3d64826c9) [Swarm](https://github.com/dockersamples/docker-swarm-visualizer) on the management node and gives you a token that you can use to add worker nodes to the [swarm](https://bluexp.netapp.com/blog/cvo-blg-docker-vs-openshift-or-docker-swarm-vs-openshift).

**Step 3: Join Worker Nodes**

Run the command supplied by the '[**docker**](https://gdevillele.github.io/swarm/plan-for-production/) [**swarm**](https://prometheus.io/docs/guides/dockerswarm/) **init**' output on the management node on each machine you want to add as a worker node.

```bash
docker swarm join --token <token> <manager-node-ip>:<port>
```

**Step 4: Define the** [**Docker**](https://gdevillele.github.io/swarm/swarm-api/) **Compose File (e.g., '<mark>web-app.yml</mark>'):**

[Docker](https://fotc.com/blog/what-is-docker-swarm/) [Compose](https://www.javainuse.com/devOps/docker/docker-swarm1) is utilized to install a Nginx web server in a [Docker](https://www.scaler.com/topics/docker/docker-swarm/) [Swarm](https://dccn-docker-swarm.readthedocs.io/en/latest/tutorial/swarm.html) cluster, enabling the creation and management of multi-container applications.

```yaml
version: '3'
services:
  web:
    image: mywebapp:latest
    ports:
      - "80:80"
    deploy:
      replicas: 3  # Scale to 3 replicas
```

**Create the service using the** [**Docker**](https://www.cherryservers.com/blog/docker-swarm-tutorial-container-orchestration) **Compose file**

```bash
docker stack deploy -c docker-compose.yml myapp
```

This setup instructs [Docker](https://www.javacodegeeks.com/2023/05/a-comprehensive-guide-to-docker-swarm.html) [Swarm](https://www.infoworld.com/article/3259872/docker-tutorial-get-started-with-docker-swarm-mode.html) to deploy three copies of the "**web**" service and map port 80 on the host to port 80 on the container.

**Step 5: Deploy the Application Stack**

Use the following command to deploy your application stack to the [Docker](https://docs.portainer.io/start/install/server/swarm) [Swarm](https://www.freecodecamp.org/news/kubernetes-vs-docker-swarm-what-is-the-difference/) cluster:

```bash
docker stack deploy -c docker-compose.yml mywebappstack
```

This command installs your application stack named '**mywebappstack**' by the parameters in the '[docker](https://signoz.io/docs/install/docker-swarm/)\-compose.yml' file. [Docker](https://www.googleadservices.com/pagead/aclk?sa=L&ai=DChcSEwi5irflrtyBAxXGdCsKHb2DAoQYABAAGgJzZg&gclid=Cj0KCQjwmvSoBhDOARIsAK6aV7jrfVUhvEfyZfpcIYPPnIyi2GV2rYxnZ-Fa3uyfOZJGUtiViRNBS6oaAosMEALw_wcB&ohost=www.google.com&cid=CAESVeD29b8YlOlKPcyvBwxJnYqnaq0FfTFBtZI3TLAgphrpwhmsulsH70jpiJv9sI-z-g7-q9KB8iau-GtaKiHp8bzS4XSWJQ_nm2_RWbgAwxLjE3lKwo4&sig=AOD64_3iIIr4xvAfMX4sb2qoAdlXe1djFA&q&adurl&ved=2ahUKEwj5_6_lrtyBAxUTZ2wGHXRxByE4MhDRDHoECAAQAQ) [Swarm](https://www.cloudbees.com/blog/running-services-within-docker-swarm) will generate and distribute the number of containers requested across the worker nodes.

**Step 6: Monitor and Scale**

Monitor the status of your services and replicas with the following command

```bash
docker service ls
```

Use the '[docker](https://www.whizlabs.com/blog/docker-swarm/) service scale' command to scale the "web" service. To scale it up to 5 replicates, for example:

```bash
docker service scale mywebappstack_web=5
```

[Docker](https://www.tutorialspoint.com/working-with-docker-swarm) [Swarm](https://www.howtogeek.com/devops/what-is-docker-swarm-mode-and-when-should-you-use-it/) will automatically manage the distribution of containers across the worker nodes to achieve the desired scale.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">With <a target="_blank" rel="noopener noreferrer nofollow" href="https://thenewstack.io/kubernetes-vs-docker-swarm-whats-the-difference/" style="pointer-events: none">Docker</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://upcloud.com/resources/tutorials/docker-swarm-orchestration" style="pointer-events: none">Swarm</a>, you have now scaled your web application to handle increased traffic by distributing multiple container replicas across a cluster of nodes. This approach provides load balancing and fault tolerance, ensuring your application can meet the demands of increased traffic.</div>
</div>

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent">In summary, containerization with <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.tutorialspoint.com/working-with-docker-swarm" style="pointer-events: none">Docker</a> allows you to package applications with their dependencies, <a target="_blank" rel="noopener noreferrer nofollow" href="https://logz.io/blog/docker-swarm-monitoring-logging-using-elk-stack/" style="pointer-events: none">Docker</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.edureka.co/blog/docker-swarm-cluster-of-docker-engines-for-high-availability" style="pointer-events: none">Compose </a>simplifies the management of multi-container applications during development and testing, and <a target="_blank" rel="noopener noreferrer nofollow" href="https://codefresh.io/docs/docs/example-catalog/cd-examples/docker-swarm/" style="pointer-events: none">Docker Swarm </a>provides a native orchestration solution for deploying and scaling containerized applications across a cluster of machines. These technologies offer a powerful ecosystem for modern application deployment and management.</div></details>

Stay tuned for the upcoming articles in the series, where we'll discuss more interesting topics related to [Docker](https://docs.appsmith.com/getting-started/setup/installation-guides/docker). Subscribe to our channel to ensure you don't miss any part of this enlightening journey!

Thank you for reading our blog. Our top priority is your success and satisfaction. We are ready to assist with any questions or additional help.

Warm regards,

[**Kamilla Preeti Samuel,**](https://www.linkedin.com/in/preeti-samuel-kamilla-5a247962/)

**Content Editor**

[**ByteScrum Technologies Private Limited!**](https://www.bytescrum.com/) 🙏
