docker swarm - 如何平衡 swarm 集群中已经 运行 的容器?

docker swarm - how to balance already running containers in a swarm cluster?

我在 AWS 上有 docker 个带有 2 个节点的 swarm 集群。我停止了这两个实例,最初启动了 swarm manager,然后启动了 worker。在停止实例之前,我有一个服务 运行 4 个副本分布在经理和工人之间。
当我首先启动 swarm 管理节点时,所有副本容器都在管理器本身上启动,根本没有移动到工作节点。
请告诉我如何做负载平衡?
swarm manager在worker启动的时候不负责吗?

在docker-compose.yml中,可以定义:

version: "3"

services:

  app:
    image: repository/user/app:latest
    networks:
      - net
    ports:
      - 80
    deploy:
      restart_policy:
        condition: any
      mode: replicated
      replicas: 5
      placement:
        constraints: [node.role == worker]
      update_config:
        delay: 2s

备注:约束是node.role == worker

使用标志“ — replicas”意味着我们不关心它们放在哪个节点上,如果我们想要每个节点一个服务,我们可以使用“ — mode=global”代替。

在 Docker 1.13 及更高版本中,您可以将 --force 或 -f 标志与 docker 服务更新命令一起使用,以强制服务在可用工作节点之间重新分配其任务。

Swarm 在创建容器后不会执行 auto-balancing。您可以在所有工作人员启动后扩展 up/down,它将根据您的配置 requirements/roles/etc.

分配容器

参见:https://github.com/moby/moby/issues/24103

There are problems with new nodes getting "mugged" as they are added. We also avoid pre-emption of healthy tasks. Rebalancing is done over time, rather than killing working processes. Pre-emption is being considered for the future.

As a workaround, scaling a service up and down should rebalance the tasks. You can also trigger a rolling update, as that will reschedule new tasks.

Swarm 当前 (18.03) 在启动新节点时不会移动或替换容器,如果服务处于默认状态 "replicated mode"。这是设计使然。如果我要添加一个新节点,我不一定要停止一堆其他容器,并在我的新节点上创建新容器。 Swarm 仅在必须时(在复制模式下)将容器停止到 "move" 个副本。

docker service update --force <servicename> 将在满足其要求和约束的所有节点之间重新平衡服务。

进一步的建议:与其他容器编排器一样,您需要在节点上提供容量,以便处理在中断期间移动的任何服务副本的工作负载。您的备用容量应该与您计划支持的冗余级别相匹配。例如,如果您想处理同时发生故障的 2 个节点的容量,您需要所有节点上的资源达到最低百分比才能将这些工作负载转移到其他节点。

这是我用来重新平衡的 bash 脚本:

#!/usr/bin/env bash

set -e

EXCLUDE_LIST="(_db|portainer|broker|traefik|prune|logspout|NAME)"

for service in $(docker service ls | egrep -v $EXCLUDE_LIST | 
                 awk '{print }'); do
  docker service update --force $service
done