Deploying a Replicated Service

A replicated service is a Docker Swarm service that has a specified number of replicas running. These replicas consist of multiple instances of the specified Docker container. 

To create our new service, we'll use the docker command along with the service create options. The following command will create a service with 4 replicas -

root@master:~# docker service create -d --replicas 4 alpine ping

To check all the containers replicas deployed by the service using the below command -

docker service ps serviceID


root@master:~# docker service ls
ID             NAME             MODE         REPLICAS   IMAGE           PORTS
w4iv8lq3q5ag   crazy_einstein   replicated   4/4        alpine:latest
root@master:~# docker service ps w4
ID             NAME               IMAGE           NODE       DESIRED STATE   CURRENT STATE           ERROR     PORTS
j6ab2gd7dq92   crazy_einstein.1   alpine:latest   worker01   Running         Running 2 minutes ago
4be0tnamctta   crazy_einstein.2   alpine:latest   worker02   Running         Running 2 minutes ago
gdssk5jzht4o   crazy_einstein.3   alpine:latest   master     Running         Running 2 minutes ago
iwinbsa43f2q   crazy_einstein.4   alpine:latest   worker01   Running         Running 2 minutes ago

In the output you can see, two containers are running on worker01, one on master, and 1 one on worker02.

Now, go to worker01 and remove the underlying containers.

root@worker01:~# docker container ls
CONTAINER ID   IMAGE           COMMAND                CREATED         STATUS         PORTS     NAMES
e02cfc5348e4   alpine:latest   "ping"   3 minutes ago   Up 3 minutes             crazy_einstein.1.j6ab2gd7dq92llot347x9y80w
60339b79e95f   alpine:latest   "ping"   3 minutes ago   Up 3 minutes             crazy_einstein.4.iwinbsa43f2qgg722pb6edci8
root@worker01:~# docker container rm -f e0 60

And as a result of this, the docker service on the manager node will again start 2 more containers as the replicas are set as 4.

root@master:~# docker service ps w4
ID       NAME          IMAGE      NODE    DESIRED STATE  CURRENT STATE      ERROR             PORTS
w1ofqtlfv5ah  crazy_einstein.1    alpine:latest  worker01  Ready      Ready 4 seconds ago
j6ab2gd7dq92  \_ crazy_einstein.1  alpine:latest  worker01  Shutdown    Failed 4 seconds ago  "task: non-zero exit (137)"
4be0tnamctta  crazy_einstein.2    alpine:latest  worker02  Running     Running 3 minutes ago
gdssk5jzht4o  crazy_einstein.3    alpine:latest  master   Running     Running 3 minutes ago
g3m2takbws4d  crazy_einstein.4    alpine:latest  worker01  Ready      Ready 4 seconds ago
iwinbsa43f2q  \_ crazy_einstein.4  alpine:latest  worker01  Shutdown    Failed 4 seconds ago  "task: non-zero exit (137)"

In this way, the docker swarm manager makes sure that the cluster is always running in the desired state.