How does docker swarm run the specified container on the specified node

  • 2020-12-09 01:09:53
  • OfStack

Describe the problem

For example, we have worker1, worker2, worker33 docker host plus one manager1 (which is the master of swarm) to manage them.

If docker service create is directly on manager1, such as nginx, then master will decide which node to select as the host for the nginx container to run on.

What if I want the nginx container to run only on worker1?

The solution

Simply put, label each node.


docker node update --label-add func=nginx worker1

master has labeled docker of worker1 as nginx. func and nginx are key-value pairs that you can set yourself.

The constraint parameter is then specified when docker service create is run


docker service create --name my_nginx --constraint 'node.labels.func == nginx' nginx

This will enable the container for nginx to start on worker1 and not on other node.

supplement

My curiosity got me a bad turn. After I labeled worker1 with func=nginx, I deliberately wrote node.labels.func == nginx111 on the constraint parameter of docker service create.

At this time, docker service ls and docker service ps nginx can be seen that service has been registered, but its CURRENT STATE shows Pending, and there is no allocation to node.

Instead of stopping this service, I simply labeled worker2 as nginx111 and miraculously started the nginx container on worker2 itself. The master is pretty smart.


Related articles: