Overview

So far we’ve learned, what is the best approach to create a high availability cluster, initiate the docker swarm, join the nodes to the cluster, renew the token, scale up and down the containers.

In this article, I will show you some commands to set up a service in a specific network and how we can add a new network to the current service.

First, let’s see the help of the service create command.

# docker service create --help

As you can see, there are a bunch of options to create a service.

The below command will create a service named webserver with 3 replicas, binding the port 8080 to 80 in the container, with my_webserver as the hostname, and 0.25 of CPU, 64Mb the memory, pwd=123 as an environment variable, and 8.8.8.8 as the DNS.

# docker service create --name webserver --replicas 3 -p 8080:80 --hostname my_webserver --limit-cpu 0.25 --limit-memory 64M --env pwd=123 --dns 8.8.8.8 nginx
create service
# docker container ps
docker ps
# docker service inspect webserver --pretty
docker inspect

The above screenshot can show us the environment variable we set up during the creation of the service, CPU, and memory limitation.

Docker Swarm networking

Now, let’s create our network. The -d or --driver will set the driver to manage the network, theoverlay networks can be created for multiple hosts.

# docker network create -d overlay my-network
# docker network ls

Now, let’s create two new services (service01 and service02) with this new network, my-network. The option --network will set up which network this service is in.

# docker service create --name service01 -p 9090:80 --network my-network nginx
# docker service create --name service02 -p 9191:80 --network my-network nginx

If you inspect the service network01, it’ll show all settings.

# docker service inspect service01

Here, we can see the beginning of NetworkID is the same as our network created before.

Now, we’ll connect to the container in service01 and try to access the other service, service02.

It’ll show the container Id.

# docker container ls

My container id is 37d2280551ec. Replace [container_id] with your container id.

# docker container exec -ti [container_id] bash
# docker container exec -ti 37d2280551ec bash

Once connected to the container, run curl service01 and curl service02. Here we can see the nginx welcome page and we’re using the service name and not an IP address.

Obs.: If curl isn’t installed, run the below command.

# apt-get update && apt-get install curl -y 

Command to show nginx welcome page.

# curl service01
# curl service02

If you already have a service running a different network, you can add it running the command:

# docker service update --network--add my-network webserver

Now the service webserver is added to my-network.

You can connect to a container in the webserver service and runcurl service01 and curl service02 for a test.

References and documentation

--

--