Files
mtusi2026lab5/scripts/rolling-update.sh
T

36 lines
1.5 KiB
Bash

#!/bin/sh
set -eu
# Grade-4 rolling replacement: replace API containers one-by-one under LB.
# Usage: scripts/rolling-update.sh
cd "$(dirname "$0")/.."
REPLICAS="${API_REPLICAS:-2}"
URL="http://127.0.0.1:8080/health/ready"
ids=$(docker compose --env-file .env ps -q api | tr -d '\r')
known="$ids"
count=0
for id in $ids; do
[ -n "$id" ] || continue
count=$((count + 1))
printf '%s\n' "rolling: replacing $id"
# -t 15 = stop_grace_period: the replica drains ~3 s before it exits.
docker stop -t 15 "$id" >/dev/null
docker rm "$id" >/dev/null
# --no-recreate: the surviving replica keeps serving even if the image/config changed.
docker compose --env-file .env up -d --no-deps --no-recreate --scale "api=${REPLICAS}" api
new=$(docker compose --env-file .env ps -q api | tr -d '\r' | grep -v -F "$known" || true)
[ "$(printf '%s\n' "$new" | grep -c .)" -eq 1 ] || { printf '%s\n' "rolling: expected one new replica" >&2; exit 1; }
known="$known
$new"
host=$(docker inspect -f '{{.Config.Hostname}}' "$new" | tr -d '\r')
# Public ready is 200 while the other replica serves; wait until the LB routes to the new one.
i=0
until curl -s -D - -o /dev/null "$URL" | tr -d '\r' | grep -qi "^x-instance-id: ${host}\$"; do
i=$((i + 1))
[ "$i" -lt 180 ] || { printf '%s\n' "rolling: $host not in LB rotation" >&2; exit 1; }
sleep 0.5
done
printf '%s\n' "rolling: step $count ready ($host)"
done
printf '%s\n' "rolling update finished ($count steps, scale=${REPLICAS})"