Docker Swarm结合云效DevOps搭建hyperf集群实现滚动更新

初始化集群
docker swarm init
添加attachable参数,使得单个容器也能附加到此网络
docker network create -d overlay --attachable hyperf-network
执行展示加入集群的命令
#加入到当前的 Swarm 集群中,并指定它们作为管理节点
docker swarm join-token manager
#加入作为工作节点
docker swarm join-token worker

#到其他机器执行上面生成的命令
docker swarm join --token xxxx <ip>:2377

#回到管理节点的机器查看所有节点情况
docker node ls
使用阿里云服务镜像服务
#所有机器执行登陆操作
docker login --username=xxxx registry.cn-shanghai.aliyuncs.com
制作 stack yml 文件
version: '3.7'
services:
  hyperf:
    image: registry.cn-hangzhou.aliyuncs.com/your_namespace/swarm_hyperf:latest
    #    environment:
    #      - "APP_PROJECT=hyperf"
    #      - "APP_ENV=production"
    ports:
      - "9552:9501"
    deploy:
#      replicas: 2
      mode: global #全局服务、每个节点上运行一个实例和replicas不能一起用,mode: replicated 如果是 replicated 模式,指定副本数量
      replicas: 2
      restart_policy:	#重启策略
        condition: on-failure	#容器仅在 非正常退出(退出码非 0) 时重启
        delay: 5s #在容器失败后,等待 5 秒再尝试重新启动
        max_attempts: 5 #最多尝试重启 5 次
      update_config:
        parallelism: 1 # 一次只更新一个容器
        delay: 5s # 每个容器更新之间的延迟时间
        order: start-first # 确保新容器启动并健康后,再停止旧容器
    healthcheck:
      test: [ "CMD", "curl", "-f", "http://localhost:9501" ]
      interval: 30s
      timeout: 10s
      retries: 3
    networks:
      - hyperf-network
#    volumes: #如果使用挂载,所有机器都要创建好对应的目录文件
#     - /root/hyperf-skeleton/runtime/logs/:/opt/www/runtime/logs:rw
#    - /root/hyperf-skeleton/.env:/opt/www/.env:rw
    configs:  #使用configs需要先安装 Portainer 中,创建对应的 Config hyperf_v1.0
      - source: hyperf_v1.0
        target: /opt/www/.env
configs:
  hyperf_v1.0:
    file: ./.env
networks:
  hyperf-network:
    external: true

创建portainer容器

docker service create \
    --name portainer \
    --publish 9000:9000 \
    --replicas=1 \
    --constraint 'node.role == manager' \
    --mount type=volume,src=portainer_data,dst=/data \
    --mount type=bind,src=//var/run/docker.sock,dst=/var/run/docker.sock \
    portainer/portainer
云效流水线配置:

1、配置代码源(我这里代码放在码云,需要把流水线webhook地址放到码云): 2、构建镜像并推送到阿里云(需要提前到阿里云镜像创建好仓库) (可选)打包镜像也可以到自己的机器上(需要执行 docker login 进行登录)

docker build . -t registry.cn-shanghai.aliyuncs.com/your_namespace/your_project:latest
docker push registry.cn-shanghai.aliyuncs.com/your_namespace/your_project:latest

3、启动部署服务脚本(拉取镜像、启动集群):

在所有集群机器上执行 curl 127.0.0.1:9552 查看是否能访问,能访问代表成功

每秒监听代码更新情况

sh -c 'while true;do curl 127.0.0.1:9552 && sleep 1;done;'

可以看到在服务不中断的情况下,实现代码滚动更新。

swarm常用命令
#新建服务
#docker service管理swarm集群中的服务
#该命令只能在管理节点上运行( --replicas 3表示创建三个工作节点)
docker service create --replicas 3 -p 8888:80 --name nginx nginx:1.22
#服务创建后,在任意节点,皆可访问

#查看服务
docker service ls
#查看某个服务的详情
docker service ps nginx
#查看某个服务的具体详情
docker service inspect --pretty nginx 
#查看某个服务的日志
dockr service logs nginx
#服务伸缩
docker service scale nginx=5
docker service scale nginx=2
#删除服务
docker service rm nginx

zed
请先登录后发表评论
  • latest comments
  • 总共0条评论