Getting Started with Docker Services

Let’s start with the smallest component of Docker swarm which is Docker services.

Initializing the swarm node

If you are using the Docker Desktop for Windows or for Mac, the Docker swarm comes prebuilt. You can check that using docker swarm. To initialize the swarm mode, type docker swarm init.

$ docker swarm init
Swarm initialized: current node (ayxwwpio1sksk5hi2bdqxanf4) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-19vn56bmfcc2l20jmts9gg9b152vkn47ruu6vtfwgsl3646ha2-8lcseq2vaegpjqytnnw1xgksn

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

The node you started will be a manager node. We can add other machines or hosts to this swarm network using the command above with the provided token. But for now, we will see all the operations on a single worker-manager node only.

Creating services

Like we have created containers using docker run command, a service does the same thing for a swarm cluster.

docker service create <service name> allows us to create a service on swarm with a defined number of containers in it.

Our aim is to create a load-balanced Flask app service and attach a database to it.

Swarm cluster only works with prebuilt images. Hence, you need to first have the image of the app in order to create the services.

For this lesson, we will use the prebuilt image of our app. So, pull the image using the docker pull venky8283/flask_app:3.0 command.

Now, let’s create the first service, which is our Flask login app.

Flask app

Type docker service create --name web_app -p 5000:5000 venky8283/flask_app:3.0. This will create a service with one container in it, which is also called a task.

$ docker service create --name web_app -p 5000:5000  venky8283/flask_app:3.0
image flask_app:3.0 could not be accessed on a registry to record
its digest. Each node will access flask_app:3.0 independently,
possibly leading to different nodes running different
versions of the image.

overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

If the image is not pulled from the Docker Hub, it will warn us saying other swarm nodes may not have the same image, which is fine for now.

Get hands-on with 1200+ tech skills courses.