Search code examples
dockerdocker-composedocker-swarm

How to run multiple docker containers for each docker swarm node


I have a docker swarm consisting of multiple swarm nodes (physical servers). How can I run 2 instances of a container in each node?

  • I know that the global option allows me to run a container in each node but I need 2 containers per swarm node and not one.
  • I know that replicas option allows me tu run multiple containers but I need 2 containers per swarm node and not 2 containers for the entire swarm.

Solution

  • If the swarm had 3 nodes then the following should work:

    services:
      some-service:
        deploy:
          replicas: 6
          placement:
            max_replicas_per_node: 2
    

    If the number of nodes is variable, then you could set replicas to (max_nodes*2), and ignore the tasks that can't be scheduled. It does feel a bit ikky giving the swarm resolver a target state it can never reach, but it will ensure swarm is always running at least, and at most, 2 replicas per node.