Search code examples
dockerdocker-composereplicationdocker-swarm

Replicated service in the same node - Docker


I want a service to be replicated.

This service is replicated on the Worker role, in some cases the service is replicated in the same node twice instead one replication for each node.

I have in my docker-compose.yml

version: "3"
services:
  api-test:
    # replace username/repo:tag with your name and image details
    image: some-image
    deploy:
      replicas: 2
      placement:
        constraints:
          - node.role == worker
      restart_policy:
        condition: on-failure
    ports:
      - "4001:80"
    networks:
      - some-network
networks:
  some-network:

Solution

  • With the HA scheduling strategy introduced in 1.13 (see this PR), this behavior should not be possible from the swarm mode scheduler unless the other nodes are unavailable for scheduling. A node may not be available for scheduling if you have defined a constraint that excludes it, or you have defined resource reservations (CPU and memory) that are not available on the node. I'm not seeing either of those in the compose file you've provided.

    One potential issue is the restart policy. This defines a restart policy on individual containers, while you also have swarm mode redeploying containers after an outage. The result could be too many running replicas. Therefore I recommend removing the restart_policy section from your service and letting swarm mode handle the scheduling alone.

    Otherwise, the main reason for multiple containers on a node that I've seen is restarting nodes in the cluster. Swarm mode will reschedule services on the still running nodes (or first nodes to restart) and it will not preemptively stop a running task to schedule it on another node once other nodes reconnect. You can force a service to rebalance with the command:

    docker service update --force $service_name