大网数据广告活动
服务器运维问答

Recreate containers with no downtime in docker-compose

· 52CE 我爱测

I am using docker-compose for deploying several containers on the same host. My images are built in Google Cloud Build and stored on gcr.io; I am not using docker-compose to build my images . When I run docker-compose pull follow…

问题原文

原帖链接 · sffc · CC BY-SA 4.0

I am using docker-compose for deploying several containers on the same host. My images are built in Google Cloud Build and stored on gcr.io; I am not using docker-compose to build my images.

When I run docker-compose pull followed by docker-compose up -d, new containers are created for my images. However, if I run docker ps in another tab, I observe that my containers go offline for a few seconds while the new ones are being created.

Is there a way to tell docker-compose to recreate and then restart the containers without any downtime?

社区高分解答

原帖链接 · Stephen O'Brien · CC BY-SA 4.0

Here’s a really simple solution we found for zero downtime, blue–green style deploys with just docker-compose and nginx: https://engineering.tines.com/blog/simple-zero-downtime-deploys.

Turns out, a well-placed bash script is all you need here! This method saved us adding other dependencies to our stack. Here's the central piece:

reload_nginx() {  
  docker exec nginx /usr/sbin/nginx -s reload  
}

zero_downtime_deploy() {  
  service_name=tines-app  
  old_container_id=$(docker ps -f name=$service_name -q | tail -n1)

  # bring a new container online, running new code  
  # (nginx continues routing to the old container only)  
  docker-compose up -d --no-deps --scale $service_name=2 --no-recreate $service_name

  # wait for new container to be available  
  new_container_id=$(docker ps -f name=$service_name -q | head -n1)
  new_container_ip=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $new_container_id)
  curl --silent --include --retry-connrefused --retry 30 --retry-delay 1 --fail http://$new_container_ip:3000/ || exit 1

  # start routing requests to the new container (as well as the old)  
  reload_nginx

  # take the old container offline  
  docker stop $old_container_id
  docker rm $old_container_id

  docker-compose up -d --no-deps --scale $service_name=1 --no-recreate $service_name

  # stop routing requests to the old container  
  reload_nginx  
}

Hope this can help others.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-02-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。