
A lot of small projects deploy like this: SSH into the server, cd into the live directory, git pull, install dependencies, restart. It works until it doesn't:
For the minute the pull and build take, the live directory is a mix of old and new files.
If the build fails halfway, the site is broken and you're debugging in production.
"Rolling back" means
git reset, reinstalling dependencies and hoping you remember what the last good commit was.
You don't need Kubernetes or a deployment platform to fix this. You need one directory per deploy and a symlink.
flowchart TD
A["Clone into releases/TIMESTAMP"] --> B["Build in place"]
B --> C["Link shared files: .env and data"]
C --> D["Atomically repoint the current symlink"]
D --> E["Restart the service"]
E --> F{"Health check passes?"}
F -->|"Yes"| G["Prune old releases"]
F -->|"No"| H["Repoint current at the previous release and restart"]The layout
/srv/myapp/
├── releases/
│ ├── 20261130-101500/ # one directory per deploy, never edited afterwards
│ └── 20261130-143000/
├── shared/ # state that survives deploys
│ ├── .env
│ └── data/
└── current -> releases/20261130-143000Everything that points at the app (the systemd unit, the nginx root, cron jobs) uses /srv/myapp/current. A deploy builds a complete new release next to the live one and only then changes where current points. Nothing the running app uses is touched until that moment.
The deploy script
#!/usr/bin/env bash
# deploy.sh <branch-or-tag>
set -euo pipefail
APP="${APP:-/srv/myapp}"
REPO="${REPO:[email protected]:you/myapp.git}"
SERVICE="${SERVICE:-myapp}"
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:8000/health}"
KEEP="${KEEP:-5}"
REF="${1:-main}" # a branch or tag name
release="$APP/releases/$(date +%Y%m%d-%H%M%S)"
previous="$(readlink -f "$APP/current" 2>/dev/null || true)"
switch_to() { # atomically repoint "current" at a release directory
ln -sfn "$1" "$APP/current.tmp"
mv -Tf "$APP/current.tmp" "$APP/current"
}
mkdir -p "$APP/releases" "$APP/shared"
# If anything fails before the switch, clean up and leave the live release untouched
trap 'echo "deploy failed before switching; removing $release" >&2; rm -rf "$release"' ERR
git -c advice.detachedHead=false clone --quiet --depth 1 --branch "$REF" "$REPO" "$release"
# Link state that must survive between releases (keep these paths out of the repo)
ln -s "$APP/shared/.env" "$release/.env"
ln -s "$APP/shared/data" "$release/data"
# Build in the final location: venvs and node_modules often hardcode their paths
if [ -x "$release/build.sh" ]; then
(cd "$release" && ./build.sh)
fi
switch_to "$release"
trap - ERR
if sudo systemctl restart "$SERVICE" \
&& curl -fsS -m 5 --retry 5 --retry-delay 1 --retry-connrefused "$HEALTH_URL" > /dev/null; then
echo "deployed $release"
else
echo "health check failed" >&2
if [ -n "$previous" ]; then
switch_to "$previous"
sudo systemctl restart "$SERVICE"
echo "rolled back to $previous" >&2
fi
exit 1
fi
# Keep the newest $KEEP releases, never delete the one in use
current="$(readlink -f "$APP/current")"
mapfile -t all < <(printf '%s\n' "$APP"/releases/* | sort -r)
for old in "${all[@]:$KEEP}"; do
[ "$(readlink -f "$old")" = "$current" ] || rm -rf -- "$old"
doneWhat it does, in order:
Clones into a new, timestamped directory. The names sort chronologically, which the rollback script relies on.
REFmust be a branch or tag name, so tag the commit if you want to deploy a specific one.Links the shared files (
.env, uploads, your SQLite database) into the release, so they're the same across every release.Builds in place by running a
build.shfrom your repo: install dependencies, compile assets, whatever the app needs. Building in the final directory matters because virtualenvs andnode_modulesoften hardcode absolute paths.Switches
current, restarts and checks health. If the health check fails, the script pointscurrentback at the previous release, restarts, and exits with an error.Prunes old releases, keeping the newest five and never deleting the live one.
If the clone or build fails, the ERR trap deletes the half-built release and the live site is never touched. A release that built fine but failed its health check stays on disk so you can inspect it, until pruning removes it.
Rollback in one command
#!/usr/bin/env bash
# rollback.sh: point "current" back at the previous release
set -euo pipefail
APP="${APP:-/srv/myapp}"
SERVICE="${SERVICE:-myapp}"
current="$(readlink -f "$APP/current")"
previous=""
found=0
for r in "$APP"/releases/*; do
if [ "$(readlink -f "$r")" = "$current" ]; then found=1; break; fi
previous="$r"
done
if [ "$found" != 1 ] || [ -z "$previous" ]; then
echo "no earlier release to roll back to" >&2
exit 1
fi
ln -sfn "$previous" "$APP/current.tmp"
mv -Tf "$APP/current.tmp" "$APP/current"
sudo systemctl restart "$SERVICE"
echo "rolled back: $current -> $previous"It finds the release just before the live one, repoints current and restarts. There's no rebuild, no reinstall and no git commands, because the previous release is still sitting on disk exactly as it was. Run it again to step back one more release.
Wiring up the service
The service runs from current, and the deploy user is allowed to restart only that one service:
[Unit]
Description=myapp
After=network.target
[Service]
User=deploy
WorkingDirectory=/srv/myapp/current
ExecStart=/srv/myapp/current/.venv/bin/gunicorn myapp:app --bind 127.0.0.1:8000
Restart=on-failure
[Install]
WantedBy=multi-user.target# /etc/sudoers.d/deploy (edit with: sudo visudo -f /etc/sudoers.d/deploy)
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myappA restart is still needed. A running process keeps using the release directory it started in, and systemctl reload won't change that, so the script restarts the service. That means a blip of about a second for an app server. For a static site served directly by nginx (root /srv/site/current/public;), the symlink switch alone makes the new version live instantly, with no restart. For a truly zero-downtime app server, you'd run two instances behind a proxy and switch between them, which is a topic for another post.
About "atomic"
The switch is atomic because it's a rename, and rename(2) replaces its target in one step: any reader sees either the old current or the new one, never a missing link or a half-written one. The script builds the new link under a temporary name and renames it over current with GNU mv -T, which is what makes the switch atomic on Linux.
You'll often see ln -sfn new current suggested on its own. On recent GNU coreutils that's atomic too: when I traced ln -sfn over an existing link on coreutils 9.4, it created a temporary link and renamed it into place. Older versions and other systems may remove the old link first and then create the new one, which leaves a brief moment with no current. Using an explicit temporary link plus mv -T doesn't depend on which ln you have.
Gotchas
Rollback restores code, not your database. If a release ran a migration, the previous release has to work with the new schema. Make migrations backward compatible: add columns first, and only drop old ones in a later deploy once nothing uses them.
Keep shared paths out of the repo. If
data/is also tracked in git,ln -swill drop the link inside that directory instead of replacing it. Add.envanddata/to.gitignore.Cron jobs and timers that use
current/...run whichever release is live at the moment they start.Disk space. Each release is a full copy, including dependencies. Tune
KEEPto your disk size.Same-second deploys collide, because release names have one-second resolution. In practice, a deploy takes longer than that.
Get told when it fails. The script exits non-zero when a deploy is rolled back, so you can append
|| curl -d "deploy failed" ntfy.sh/your-topicto the command in your CI job or shell alias.
Wrap-up
Per-deploy directories and a current symlink cost you a few lines of shell and some disk space. In return, a failed build never touches the live site, the new version appears in a single step, and the way back is one command. Try it on a small project first, and deliberately deploy a broken release once to watch the automatic rollback work.
Comments0
Log in to join the discussion.
No comments yet.