Docker Swarm
Prerequisites:
- Docker should be installed on all the nodes (manager and workers).
- Nodes should be able to communicate with each other over the network.
Step 1
Initialize Docker Swarm on the Manager Node
Log in to the manager node and run the following command in the terminal:
docker swarm init
This command initializes Docker Swarm on the manager node, and it will also generate a token that you can use to join worker nodes to the cluster.
Step 2
Join Worker Nodes to the Swarm
After running the docker swarm init command on the manager node, it will output a command to join other nodes to the swarm. It will look something like this:
docker swarm join — token <SWARM_TOKEN> <MANAGER_IP>:2377
Run it on each worker node you want to add to the cluster.
Step 3
Check the Swarm Status
To check the status of your Docker Swarm and view the nodes in the cluster, run the following command on the manager node:
docker node ls
This command will display a list of nodes in the swarm along with their status and availability.
Step 4
Deploy Services on the Swarm
With Docker Swarm set up, you can now deploy services to the cluster. A service defines how a container should run in the cluster.
For example, let’s deploy a simple Nginx web server service:
docker service create — replicas 3 -p 80:80 — name webserver nginx
This command will create a service called “webserver” with three replicas (three instances) of the Nginx container, and it will publish port 80 to the host.
Step 5
Scale the Service
You can easily scale the service up or down using the docker service scale command. For example, to scale the “webserver” service to five replicas, run:
docker service scale webserver=5
Step 6
Update the Service
If you need to update the service, you can use the docker service update command. For example, to change the number of replicas to ten, run:
docker service update — replicas 10 webserver
Step 7
Remove the Service
When you no longer need the service, you can remove it with the following command:
docker service rm webserver
Step 8
Leave the Swarm
If you want to remove a node from the swarm, run the following command on the node you want to remove:
docker swarm leave
If the node is a manager, use docker swarm leave — force to force it to leave.
These are the basic steps to set up and use Docker Swarm to create a simple cluster. Docker Swarm provides many more features, such as overlay networks, secrets management, rolling updates, and more, which can be explored as you get more familiar with it.