Skip to content

Instantly share code, notes, and snippets.

@yuswitayudi
Last active June 30, 2022 03:08
Show Gist options
  • Save yuswitayudi/7a8299f21b1f9f73e0d1a67936e9c6ee to your computer and use it in GitHub Desktop.
Save yuswitayudi/7a8299f21b1f9f73e0d1a67936e9c6ee to your computer and use it in GitHub Desktop.
Zero downtime docker, with docker-compose and nginx
--> script pull or build image
reload_nginx() {
docker exec nginx-lb /usr/sbin/nginx -s reload
}
zero_downtime_deploy() {
service_name=name_of_service_docker_compose
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)
echo $new_container_ip
sleep 5
## Curl new container if the response is 200 so deploy new container
if [[ $(curl -o /dev/null -s -w "%{http_code}\n" --max-time 3 http://$new_container_ip:5000) = 200 ]];
then
# 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
else
docker-compose up -d --no-deps --scale $service_name=1 --no-recreate $service_name
echo "Gagal deploy, CHECK RUNNING CONTAINER"
fi
}
zero_downtime_deploy
version: '3.8'
services:
backend:
image: nginx-test
build: .
restart: always
reverse-proxy:
container_name: nginx-lb
image: nginx
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
ports:
- 80:80
FROM nginx:alpine
COPY index.html /usr/share/nginx/html
Test zero downtime
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment