Deploy your First Service

A service is an abstraction that represents multiple containers of the same image deployed across a distributed cluster. In our example, we have initialized three-node Swarm cluster, now we will deploy some containers. We need to create a service in order to run containers on a Docker Swarm. We will do it using NGINX. Initially, we will create a service with one running container and later will scale up.

1. Deploy a service  (using NGINX)
[copy and paste the following command on manager node (node1)]
   $ docker service create --detach=true --name nginx1 --publish 80:80  --mount source=/etc/hostname,target=/usr/share/nginx/html/index.html,type=bind,ro nginx:1.12
(this should be written as single statement)
 --mount flag            -print out the hostname of the node it's running on.
This will be useful when we do load balancing between multiple containers of NGINX that are distributed across different nodes in the cluster and we want to see which node in the swarm is serving the request.
--publish command uses the swarm's built-in routing mesh.
In this case, port 80 is exposed on every node in the swarm. The routing mesh will route a request coming in on port 80 to one of the nodes running the container.

Note: – Docker Swarm will try to maintain the state which is useful when nodes go down. In such case containers are automatically rescheduled on other nodes.

2. Inspect the service.
            $ docker service ls 
3. Check the running container of the service.
      $ docker service ps nginx1
This provides a deeper look at the running tasks. A task is another abstraction in Docker Swarm that represents the running instances of a service. We can also use the following command  to see the container running on that specific node.  
                $ docker container ls
4. Test the service (Try this command on each node)
                $ curl localhost:80
Because of the routing mesh, you can send a request to any node of the swarm on port 80. This request will be automatically routed to the one node that is running the NGINX container. Curling will output the hostname where the container is running. In our example, it is running on node1.