Skip to content
shellhacks.dev
DevOps

How to Write a Zero Downtime Deploy Script in Real Scripts

Deploy a new release without dropping requests: build beside the live one, check it, switch atomically, reload gracefully and keep the old one.

6 min read
Summarize in AI
Illustration for "How to Write a Zero Downtime Deploy Script in Real Scripts": a shell script in an editor, a directory tree, environment variables.

"Zero downtime" is mostly an ordering problem. Requests fail during a deploy when the files change under a running process, when the service restarts and refuses connections, or when new code meets an old database. A script that does the steps in the right order avoids all three, and uses no tool beyond the shell. This post builds that script, and it is the main pattern behind deploy scripts that are safe to run twice. Its pieces are expanded in atomic symlink deploys and automatic rollback.

The script assumes Bash 5.2, rsync 3.4 and a service managed by systemd 257 on Debian 13.

The layout

Text
/srv/app/
  releases/
    20250314-101500/
    20250315-093000/
  shared/            logs, uploads, .env: survive every release
  current -> releases/20250315-093000

The service runs from /srv/app/current. A deploy never touches the directory that is live; it creates a new one next to it.

The script

deploy.shShell
#!/usr/bin/env bash
set -euo pipefail

app=/srv/app
src="${1:?usage: deploy.sh BUILD_DIR}"
release="$app/releases/$(date +%Y%m%d-%H%M%S)"
keep=5

exec 9>"$app/.deploy.lock"
flock -n 9 || { echo "another deploy is running" >&2; exit 1; }

echo "copying to $release"
mkdir -p "$release"
rsync -a --delete "$src"/ "$release"/

ln -sfn "$app/shared/.env" "$release/.env"
ln -sfn "$app/shared/storage" "$release/storage"

echo "checking the new release"
"$release/bin/healthcheck"

echo "switching"
ln -sfn "$release" "$app/current.tmp"
mv -T "$app/current.tmp" "$app/current"

echo "reloading"
systemctl reload app.service

echo "pruning old releases"
ls -1dt "$app"/releases/* | tail -n +"$((keep + 1))" | xargs -r rm -rf --

echo "deployed $release"

Why each step is where it is

  1. The lock. flock -n makes a second concurrent run exit immediately, so two deploys cannot interleave their symlink switches.
  2. Copy first. The new release is complete and in its own folder before anything points at it.
  3. Health check before the switch. A release that fails its own check never goes live. set -e aborts the script at that line.
  4. Atomic switch. ln -sfn to a temporary name, then mv -T over current. A rename is atomic, so a request sees the old release or the new one, never a missing link. Plain ln -sfn onto the existing link removes and recreates it, and has a brief gap.
  5. Reload, not restart. reload asks the service to re-read its code or config and hand over without dropping connections: nginx -s reload, php-fpm via systemctl reload, or Gunicorn with HUP. A restart closes the listening socket for a moment.
  6. Prune last. Old releases are deleted only after the new one is live, and the newest five are kept.

The parts a script cannot fix

  • The database. If the new release needs a schema change the old code cannot cope with, there is a window of errors whatever the script does. Use backward-compatible changes in two steps; see running migrations in a deploy script.
  • In-flight requests. A reload lets workers finish current requests. Set the service's graceful timeout longer than your slowest request.
  • Long-lived connections such as WebSockets are dropped at some point; clients must reconnect.
  • Cached paths. PHP's opcache and some language runtimes cache resolved file paths. They need a reload, which the script does, and they can serve stale code if you skip it.

Prove the switch drops nothing

The claim behind this layout is that requests keep working while the pointer moves between releases. It is cheap to test. Run a loop that reads a file through the current link as fast as it can while another loop flips the link between two releases a few thousand times. Any read that fails during a flip is a request your users would have seen as an error. On Debian 13 with coreutils 9.7, both the rename form and ln -sfn showed zero failures.

Shell
mkdir -p releases/r1 releases/r2
echo one > releases/r1/v; echo two > releases/r2/v
ln -s releases/r1 current

( i=0; end=$((SECONDS+3))
  while [ $SECONDS -lt $end ]; do
    i=$((i+1)); ln -s releases/r$((i%2+1)) current.tmp; mv -T current.tmp current
  done ) &
misses=0; n=0; end=$((SECONDS+3))
while [ $SECONDS -lt $end ]; do
  n=$((n+1)); cat current/v >/dev/null 2>&1 || misses=$((misses+1))
done
wait
echo "reads=$n misses=$misses"
Text
reads=5602 misses=0

That test covers the file system. It says nothing about the application, which may hold open files from the old release, cache absolute paths or have a worker pool that must be restarted to see the new code. A switch of the link is the cheap half of a zero-downtime deploy. Making the running process load the new files is the half that needs your attention.

Order of operations, and why

The script builds the new release beside the live one, so a failure at any point before the switch leaves the old release serving traffic, untouched. Then it runs checks against the new directory: a syntax check, a dependency install with the lock file, a migration dry run when the tool supports it. Only after every check passes does it move the pointer, and then it reloads the service and waits for a health check. The sequence is deliberately asymmetric. Everything before the switch is reversible by deleting a directory, and everything after it is reversible by moving the link back. Anything that changes shared state, such as a database migration, has to be written so that both the old and the new release can run against it, because for a few seconds both will.

Keep releases, but not all of them

Each release is a full copy, so disk use grows by one release per deploy. Keep the last five, which is enough to roll back past a bad deploy that was not noticed for a day, and delete the rest. List them by name with a sortable timestamp, skip the one the link points at, and remove the oldest. Never delete by modification time alone, because restoring a backup or touching a directory changes it. Count the number of directories before and after in the log, so a bug in the pruning shows up as a number that does not make sense.

Shell
cd /srv/app/releases
current=$(basename "$(readlink -f ../current)")
ls -1 | sort -r | tail -n +6 | grep -vx "$current" | xargs -r rm -rf --

A rehearsal on a staging copy

Before the first production use, run the whole script on a copy of the environment with the same layout, the same web server and the same service manager. Deploy twice in a row, then roll back once, and watch the logs of the web server while a loop requests the home page every 200 milliseconds. Count the failures. The goal is a number you have measured, ideally zero, and a list of anything that surprised you. Fix those surprises in the script or write them in the runbook, and repeat until a run is boring. A deploy that has never been rehearsed is a deploy that will teach you its flaws in front of your users, at a time you did not choose. Keep the rehearsal script in the repository, because you will want to run it again after every change to the deploy.

Shell
fail=0
for i in $(seq 1 100); do
  curl -fsS -o /dev/null --max-time 2 https://staging.example.test/ || fail=$((fail + 1))
  sleep 0.2
done
echo "failed requests: $fail"

Run that loop in a second terminal while the deploy happens, and the final line is your evidence.

When this is too much, or too little

For one process on one server, this is enough. With several servers behind a load balancer, add draining (take the server out of rotation, deploy, check, put it back, move to the next) and prefer an orchestrator that does it for you. Containers change the mechanics but not the order: start new, check, route traffic, stop old. See blue-green deployment with Nginx for the two-instance version. The systemd reload semantics are in systemd.service, and the rename guarantee in rename(2).

Share

Keep reading

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.