Create a Docker Swarm service
In this step, we will learn how to create a Docker Swarm service. A Docker Swarm service is a set of tasks that run on a Swarm cluster. Each task is an instance of a container. Services are the central concept of Docker Swarm, allowing you to define how many replicas of a container image should be running and how they should be updated.
Before creating a service, we need to initialize a Docker Swarm. Since we are running on a single VM, we will initialize a single-node Swarm.
First, let's initialize the Swarm:
docker swarm init --advertise-addr 127.0.0.1
You should see output indicating that the Swarm has been initialized and that the current node is now a manager.
Now, let's create a service using the nginx
image. We will name the service my-nginx
and specify that we want 3 replicas of the nginx
container running.
First, pull the nginx
image to ensure it's available locally:
docker pull nginx:latest
Now, create the service:
docker service create --name my-nginx --replicas 3 nginx:latest
This command creates a new service named my-nginx
with 3 replicas using the nginx:latest
image. Docker Swarm will automatically distribute these replicas across the nodes in the Swarm (in this case, just our single node).
To verify that the service has been created and the replicas are running, you can list the services:
docker service ls
You should see my-nginx
listed with 3/3 replicas running.
You can also inspect the tasks associated with the service:
docker service ps my-nginx
This command will show you the individual tasks (containers) that make up the my-nginx
service, their current state, and the node they are running on. You should see 3 tasks in the Running
state.