Docker Swarm 是 Docker 原生的集群管理工具,可以轻松地将多个 Docker 主机组成一个集群,实现服务的高可用性和负载均衡。以下是详细的部署步骤:
# 设置主机名
hostnamectl set-hostname node1 # 在第一台执行
hostnamectl set-hostname node2 # 在第二台执行
hostnamectl set-hostname node3 # 在第三台执行
# 编辑/etc/hosts添加解析
echo "
192.168.1.101 node1
192.168.1.102 node2
192.168.1.103 node3
" >> /etc/hosts
docker swarm init --advertise-addr <node1-IP>
输出示例:
Swarm initialized: current node (xyz) is now a manager.
To add a worker to this swarm, run the following command:
docker swarm join --token SWMTKN-1-xxx 192.168.1.101:2377
To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
在其他节点上运行上面输出的加入命令:
docker swarm join --token <worker-token> <node1-IP>:2377
# 在主节点获取管理令牌
docker swarm join-token manager
# 在其他管理节点运行输出的命令
docker node ls
输出示例:
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
x3y * node1 Ready Active Leader 20.10.7
z4w node2 Ready Active Reachable 20.10.7
a5b node3 Ready Active 20.10.7
docker info | grep -i swarm
docker network create --driver overlay --attachable my-overlay
docker service create \
--name nginx \
--replicas 3 \
--publish published=8080,target=80 \
--network my-overlay \
nginx:latest
docker service ls
docker service ps nginx
docker service update \
--restart-condition any \
--restart-delay 5s \
--restart-max-attempts 3 \
nginx
docker service update \
--update-parallelism 2 \
--update-delay 10s \
--image nginx:1.21 \
nginx
docker service update \
--health-cmd "curl -f http://localhost || exit 1" \
--health-interval 5s \
--health-retries 3 \
--health-timeout 2s \
nginx
# 将节点设置为维护模式
docker node update --availability drain node2
# 恢复节点
docker node update --availability active node2
# 备份 Raft 日志(在管理节点执行)
docker swarm ca --rotate # 先轮换证书
tar -czvf swarm-backup.tar.gz /var/lib/docker/swarm/
# 在新节点恢复管理角色
docker swarm init --force-new-cluster --advertise-addr <new-ip>
# 创建监控网络
docker network create --driver overlay monitor
# 部署 Prometheus
docker service create --name prometheus \
--network monitor \
--publish published=9090,target=9090 \
prom/prometheus
# 部署 Grafana
docker service create --name grafana \
--network monitor \
--publish published=3000,target=3000 \
grafana/grafana
docker service create --name logspout \
--mode global \
--mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock \
--network my-overlay \
gliderlabs/logspout syslog+tls://your-log-server:514
# 初始化 Swarm 时启用 TLS
docker swarm init --advertise-addr <ip> --default-addr-pool 10.10.0.0/16 --data-path-port 4789 --force-new-cluster --listen-addr <ip>:2377 --cert-expiry 2160h
docker swarm ca --rotate
iptables -A INPUT -p tcp --dport 2377 -s <trusted-ip> -j ACCEPT
iptables -A INPUT -p tcp --dport 2377 -j DROP
节点无法加入集群
服务无法启动
docker service inspect --pretty
docker service logs
网络连接问题
docker network inspect
通过以上步骤,您已经成功部署了一个高可用的 Docker Swarm 集群。这种架构可以自动处理节点故障、服务扩展和负载均衡,适合生产环境使用。