Deploying a Web Application with a Bash Script
Deploying a web application means getting a new version of its code onto a server, preparing it, and making it the version that answers requests, without breaking the site if something goes wrong. Many teams start by deploying by hand: log in, git pull, run the build, restart the service. That works until the build fails halfway through and the site serves a mixture of old and new files, or until the new version turns out to be broken and nobody remembers exactly how the old one was set up.
This lesson builds a deployment script that avoids these problems with a technique used by many deployment tools: every version is built in its own directory, a symbolic link marks the live one, and switching versions, forward or back, is a single atomic operation. The script checks the application's health after each switch and automatically returns to the previous version when the new one is not healthy.
The Release Directory Layout
The script organizes the application's directory like this:
/srv/shop/
├── current -> releases/20261201-043921-cacc984
├── releases/
│ ├── 20261201-043910-6517a65/
│ └── 20261201-043921-cacc984/
└── shared/
├── .env
└── uploads/
releases/holds one directory per deployed version, a release. Its name combines the deployment time and the abbreviated Git commit, so it sorts chronologically and shows exactly what code it contains. A release is built once and then never modified.currentis a symbolic link to the live release. The web server or service manager is configured to run the application from/srv/shop/current, so whatevercurrentpoints to is what users see.shared/holds everything that must survive from one release to the next: the configuration file with secrets (lesson 178), files uploaded by users, and similar data. Each release gets symbolic links to these files.
This layout gives three guarantees that in-place deployment cannot:
- The live site is never half-updated. The new release is prepared in a separate directory while the old one keeps serving requests. A failed build leaves the live release untouched.
- Switching is instant and atomic. Changing which release is live means changing one symbolic link.
- Rollback is just another switch. Previous releases are still on disk, complete and already built, so returning to one takes a second and needs no rebuild.
Atomic Switching
The obvious command for repointing a link, ln -sfn releases/NEW current, is not atomic: ln first deletes the old link and then creates the new one. Between the two system calls, current does not exist, and a request arriving at that moment fails. The window is short, but on a busy site it is hit sooner or later.
The atomic method creates the new link under a temporary name and then renames it over the old one:
ln -s "releases/$id" /srv/shop/current.new
mv -T /srv/shop/current.new /srv/shop/current
A rename within one file system is a single operation in the kernel (the rename system call): at every moment, current exists and points either to the old release or to the new one. The -T option tells mv to treat current as a plain name to replace. Without it, because current is a link to a directory, mv would move current.new into that directory instead. The link target is relative (releases/ID), so the whole tree can be moved or restored from backup without breaking it.
Restarting and Checking Health
A new release is live only once the application has been restarted from it, because a running process keeps using the files it loaded at startup. How to restart depends on the setup: systemctl restart shop for a systemd service, systemctl reload for servers that can reload gracefully, or a command of the application server. The script receives the command as a setting.
After restarting, the script asks the application whether it works, through a health endpoint: a URL that returns success only when the application can serve requests (lesson 176 explains health checks in detail). It polls the endpoint for up to 15 seconds, because applications need a moment to start:
restart_and_check() { # restart the app, then poll the health URL for up to 15s
local i body
$RESTART_CMD 9>&- || return 1 # the app must not inherit the lock
for (( i = 0; i < 15; i++ )); do
if body=$(curl -fsS --max-time 2 "$HEALTH_URL" 2> /dev/null); then
log "health check passed: $body"
return 0
fi
sleep 1
done
log "health check failed: $(curl -sS -o /dev/null -w 'HTTP %{http_code}' --max-time 2 "$HEALTH_URL" 2>&1)"
return 1
}
curl -f makes HTTP error statuses count as failures (lesson 168), -sS hides the progress meter but keeps error messages, and --max-time 2 keeps a hanging application from blocking the loop. When all attempts fail, a final request with -w 'HTTP %{http_code}' records which status the application returned.
$RESTART_CMD is deliberately unquoted, so that a setting such as sudo systemctl restart shop is split into a command and its arguments. That is acceptable for a value set by the administrator, never for user input. The redirection 9>&- closes file descriptor 9, the deployment lock, for the restart command; the reason is shown in the section about testing below.
A Complete Example: Deploying from Git with Automatic Rollback
deploy-app.sh deploys the "shop" application from a Git repository on the server. It has three commands: deploy REF builds a tag, branch or commit and makes it live; rollback returns to the previous release; list shows the releases. The application's own build steps are in a script build.sh in its repository, so the deployment script works for any application that provides one.
#!/usr/bin/env bash
#
# deploy-app.sh - deploy the shop web application from Git, with instant rollback
#
# Usage: deploy-app.sh deploy REF build REF (tag, branch or commit) and switch to it
# deploy-app.sh rollback switch back to the previous release
# deploy-app.sh list show the releases on this server
#
# Layout under APP_ROOT:
# releases/ID/ one directory per release, never changed after it is built
# shared/ files that survive releases: .env, uploads/
# current symbolic link to the live release
#
# Exit status: 0 success, 1 deployment failed (the previous release is live),
# 2 usage error or another deployment running
set -euo pipefail
APP_ROOT=${APP_ROOT:-/srv/shop}
REPO=${REPO:-/srv/git/shop.git}
KEEP=${KEEP:-5} # releases kept on disk
RESTART_CMD=${RESTART_CMD:-"sudo systemctl restart shop"}
HEALTH_URL=${HEALTH_URL:-http://127.0.0.1:8080/health.txt}
SHARED=(.env uploads) # linked into every release
releases=$APP_ROOT/releases
log() { printf '%(%H:%M:%S)T %s\n' -1 "$*"; }
die() { log "ERROR: $*" >&2; exit 1; }
usage() { sed -n '5,7s/^# \{0,1\}//p' "$0" >&2; exit 2; }
current_release() { # prints the ID of the live release, or nothing
[[ -L $APP_ROOT/current ]] && basename "$(readlink "$APP_ROOT/current")"
}
# switch_to ID: point "current" at a release, atomically
switch_to() {
rm -f -- "$APP_ROOT/current.new" # left over from an interrupted run
ln -s "releases/$1" "$APP_ROOT/current.new"
mv -T "$APP_ROOT/current.new" "$APP_ROOT/current"
}
restart_and_check() { # restart the app, then poll the health URL for up to 15s
local i body
$RESTART_CMD 9>&- || return 1 # the app must not inherit the lock
for (( i = 0; i < 15; i++ )); do
if body=$(curl -fsS --max-time 2 "$HEALTH_URL" 2> /dev/null); then
log "health check passed: $body"
return 0
fi
sleep 1
done
log "health check failed: $(curl -sS -o /dev/null -w 'HTTP %{http_code}' --max-time 2 "$HEALTH_URL" 2>&1)"
return 1
}
cmd_deploy() {
local ref=$1 sha id dir previous name
sha=$(git -C "$REPO" rev-parse --verify --quiet "$ref^{commit}") || die "unknown ref: $ref"
id=$(date +%Y%m%d-%H%M%S)-${sha:0:7}
dir=$releases/$id
previous=$(current_release) || true
log "deploying $ref ($id)"
mkdir -p "$dir"
trap 'rm -rf -- "$dir"; log "build failed; removed incomplete release $id"' ERR
# 1. code: export the commit, without the .git directory
git -C "$REPO" archive --format=tar "$sha" | tar -x -C "$dir"
# 2. shared files: link them into the release
for name in "${SHARED[@]}"; do
rm -rf -- "${dir:?}/$name"
ln -s "../../shared/$name" "$dir/$name"
done
# 3. build, inside the new release only; the live release is not touched
( cd "$dir" && ./build.sh ) 2>&1 | sed 's/^/ | /'
trap - ERR
# 4. go live, check, and roll back if the new release is not healthy
switch_to "$id"
log "current -> releases/$id"
if ! restart_and_check; then
if [[ -n $previous ]]; then
log "rolling back to $previous"
switch_to "$previous"
restart_and_check || log "WARNING: the previous release is not healthy either"
fi
rm -rf -- "$dir"
die "deployment of $ref failed; $( [[ -n $previous ]] && echo "$previous is live again" || echo "no previous release")"
fi
# 5. keep the newest KEEP releases (the live one is always among them)
ls -1 "$releases" | sort -r | tail -n +$(( KEEP + 1 )) | while read -r name; do
[[ $name == "$id" ]] || { rm -rf -- "${releases:?}/$name"; log "removed old release $name"; }
done
log "deployed $ref"
}
cmd_rollback() {
local current previous
current=$(current_release) || die "no current release"
previous=$(ls -1 "$releases" | sort | grep -B1 -x -- "$current" | head -n 1)
[[ -n $previous && $previous != "$current" ]] || die "no release older than $current"
log "rolling back from $current to $previous"
switch_to "$previous"
restart_and_check || die "$previous is not healthy"
log "rolled back; $current is still on disk"
}
cmd_list() {
local current name
current=$(current_release) || true
for name in $(ls -1 "$releases" | sort); do
printf '%s %s\n' "$([[ $name == "$current" ]] && echo '*' || echo ' ')" "$name"
done
}
(( $# >= 1 )) || usage
exec 9> "$APP_ROOT/.deploy.lock"
flock -n 9 || { echo "${0##*/}: another deployment is running" >&2; exit 2; }
case $1 in
deploy) (( $# == 2 )) || usage; cmd_deploy "$2" ;;
rollback) (( $# == 1 )) || usage; cmd_rollback ;;
list) (( $# == 1 )) || usage; cmd_list ;;
*) usage ;;
esac
How It Works
- Settings with defaults. Each setting can be overridden through the environment (lesson 178), so the same script serves several applications or servers.
SHAREDlists the files and directories that every release links to. - Resolving the reference first.
git rev-parse --verify --quiet "$ref^{commit}"turns a tag, branch or abbreviated hash into the full commit hash, and fails for anything that is not a commit. The deployment then works with that exact commit: if someone pushes to the branch during the deployment, it does not change what is deployed. git archivewrites the files of a commit as a tar stream, whichtar -xunpacks into the release directory. The release contains exactly the committed files: no.gitdirectory, no uncommitted changes, no leftovers from earlier builds.- Shared files are links. For each name in
SHARED, a file of that name from the repository is removed and replaced by a link toshared/. The relative link../../shared/.envworks fromreleases/ID/. Removing first matters for directories:ln -sonto an existing directory would create the link inside it instead. - Building with cleanup on failure. The
ERRtrap removes the incomplete release if any command fails while the release is being prepared, including the build: withpipefail, the pipeline( cd "$dir" && ./build.sh ) | sedfails whenbuild.shfails, even thoughsedsucceeds. The build's output is indented withsedso that it stands out in the log. After the build,trap - ERRremoves the trap, because from then on failures are handled explicitly. - Switch, check, roll back. After
switch_to, the new release is live. If the health check fails, the script switches back to the release that was live before, restarts and checks it, deletes the failed release, and exits with status 1, so a CI pipeline or person running it sees the failure (lesson 177). - Cleanup. Release names sort chronologically, so
sort -r | tail -n +$(( KEEP + 1 ))lists everything except the newestKEEPreleases. The new release is newest, so it is never removed.${releases:?}makes therm -rffail if the variable were ever empty, instead of turning intorm -rf /name(lesson 160). - Rollback finds the release before the current one in sorted order:
grep -B1 -x -- "$current"prints the line matching the current release exactly and the line before it. If the current release is the oldest, both are the same, and the script refuses. The newer release stays on disk, so the nextdeployor a manual switch can return to it. - One deployment at a time.
flockon file descriptor 9 (lesson 171) prevents two deployments, or a deployment and a rollback, from running at once.
Testing the Script
The script was tested with a small demo application in a local Git repository. Its build.sh renders a page and a health file containing the version:
#!/usr/bin/env bash
# build.sh - build step of the demo shop: renders the pages in public/ with the version
set -euo pipefail
version=$(< VERSION)
mkdir -p public
sed "s/@VERSION@/$version/g" templates/index.html > public/index.html
printf 'ok %s\n' "$version" > public/health.txt
echo "built shop $version"
The repository contains five tagged versions. v1.0.0 and v1.1.0 are correct; v1.2.0 renamed the health file to healthz.txt, so its health check fails, a stand-in for a release that builds but does not work; v1.3.0 has a typo (VERSON) that breaks the build; v1.3.1 fixes it. As the restart command, a small script stops the previous process and starts Python's built-in web server from current/public on port 18180. The settings for the test:
export APP_ROOT=/srv/shop REPO=/srv/git/shop.git KEEP=3 \
RESTART_CMD=/usr/local/bin/appctl.sh HEALTH_URL=http://127.0.0.1:18180/health.txt
The first version of the script did not have 9>&- in restart_and_check. Its first deployment worked, but every command after it failed:
$ deploy-app.sh deploy v1.1.0
deploy-app.sh: another deployment is running
[status 2]
The lock is held as long as any process has file descriptor 9 open. The restart command started the web server in the background, and the server inherited the descriptor from the script, so the lock stayed held for as long as the server ran. With systemd, the service would be started by systemd itself and the problem would not appear, but any restart command that starts the application directly has the same effect. Closing the descriptor for the restart command fixed it. Background processes inherit all open file descriptors, a detail worth remembering whenever a script holds locks or open files.
Running the Complete Example
The first deployment builds v1.0.0 and makes it live:
$ deploy-app.sh deploy v1.0.0
04:39:10 deploying v1.0.0 (20261201-043910-6517a65)
| built shop 1.0.0
04:39:10 current -> releases/20261201-043910-6517a65
04:39:11 health check passed: ok 1.0.0
04:39:11 deployed v1.0.0
[status 0]
$ curl -s http://127.0.0.1:18180/
<h1>Shop 1.0.0</h1>
The release contains the committed files, the built public/ directory, and the links to the shared files:
$ ls -A releases/20261201-043910-6517a65
.env .gitignore VERSION build.sh public templates uploads
$ ls -l releases/20261201-043910-6517a65/.env releases/20261201-043910-6517a65/uploads
... .env -> ../../shared/.env
... uploads -> ../../shared/uploads
Then v1.1.0, which works, v1.2.0, which builds but fails its health check, and v1.3.0, whose build fails:
$ deploy-app.sh deploy v1.1.0
04:39:21 deploying v1.1.0 (20261201-043921-cacc984)
| built shop 1.1.0
04:39:21 current -> releases/20261201-043921-cacc984
04:39:22 health check passed: ok 1.1.0
04:39:22 deployed v1.1.0
[status 0]
$ deploy-app.sh deploy v1.2.0
04:39:23 deploying v1.2.0 (20261201-043923-ad31172)
| built shop 1.2.0
04:39:23 current -> releases/20261201-043923-ad31172
04:39:39 health check failed: HTTP 404
04:39:39 rolling back to 20261201-043921-cacc984
04:39:40 health check passed: ok 1.1.0
04:39:40 ERROR: deployment of v1.2.0 failed; 20261201-043921-cacc984 is live again
[status 1]
$ deploy-app.sh deploy v1.3.0
04:39:41 deploying v1.3.0 (20261201-043941-03e2a12)
| ./build.sh: line 4: VERSON: No such file or directory
04:39:41 build failed; removed incomplete release 20261201-043941-03e2a12
[status 1]
$ curl -s http://127.0.0.1:18180/
<h1>Shop 1.1.0 - now with search</h1>
$ deploy-app.sh list
20261201-043910-6517a65
* 20261201-043921-cacc984
The two failures are handled at different stages. v1.2.0 was live for about 16 seconds while the health check kept retrying, and then the script returned to v1.1.0 on its own. A shorter polling period would shorten that window, at the risk of rejecting releases that simply start slowly. v1.3.0 never went live: its build failed in its own directory while v1.1.0 kept serving. In both cases, no trace of the failed release is left. The fixed version v1.3.1 deploys normally, and two rollbacks walk back through the releases, each in about a second, because nothing is rebuilt:
$ deploy-app.sh deploy v1.3.1
04:39:49 deploying v1.3.1 (20261201-043949-0d46255)
| built shop 1.3.1
04:39:49 current -> releases/20261201-043949-0d46255
04:39:51 health check passed: ok 1.3.1
04:39:51 deployed v1.3.1
[status 0]
$ deploy-app.sh rollback
04:39:51 rolling back from 20261201-043949-0d46255 to 20261201-043921-cacc984
04:39:52 health check passed: ok 1.1.0
04:39:52 rolled back; 20261201-043949-0d46255 is still on disk
[status 0]
$ deploy-app.sh rollback
04:39:52 rolling back from 20261201-043921-cacc984 to 20261201-043910-6517a65
04:39:53 health check passed: ok 1.0.0
04:39:53 rolled back; 20261201-043921-cacc984 is still on disk
[status 0]
$ deploy-app.sh rollback
04:39:53 ERROR: no release older than 20261201-043910-6517a65
[status 1]
$ deploy-app.sh list
* 20261201-043910-6517a65
20261201-043921-cacc984
20261201-043949-0d46255
Deploying again creates a fourth release. With KEEP=3, the oldest one is removed:
$ deploy-app.sh deploy v1.3.1
04:39:54 deploying v1.3.1 (20261201-043954-0d46255)
| built shop 1.3.1
04:39:54 current -> releases/20261201-043954-0d46255
04:39:56 health check passed: ok 1.3.1
04:39:56 removed old release 20261201-043910-6517a65
04:39:56 deployed v1.3.1
[status 0]
$ deploy-app.sh list
20261201-043921-cacc984
20261201-043949-0d46255
* 20261201-043954-0d46255
$ ls -l current
lrwxrwxrwx 1 root root 32 Dec 1 04:39 current -> releases/20261201-043954-0d46255
Finally, an unknown reference is rejected before anything is created, a missing argument prints the usage, and a deployment started while another one is running is refused:
$ deploy-app.sh deploy v9.9
04:39:56 ERROR: unknown ref: v9.9
[status 1]
$ deploy-app.sh deploy
Usage: deploy-app.sh deploy REF build REF (tag, branch or commit) and switch to it
deploy-app.sh rollback switch back to the previous release
deploy-app.sh list show the releases on this server
[status 2]
$ deploy-app.sh deploy v1.1.0 & sleep 0.3; deploy-app.sh deploy v1.0.0
deploy-app.sh: another deployment is running
[status 2]
Beyond a Single Server
The script handles the parts of a deployment that are common to most applications. Real applications add steps that fit into the same structure:
- Dependencies such as
npm ci,pip installorcomposer installbelong inbuild.sh, so they run inside the new release. A shared cache directory inshared/avoids downloading everything for every release. - Database migrations change data that all releases share, so they are the one step a symbolic link cannot undo. They usually run after the build and before the switch. To keep rollback possible, migrations are written so that the previous release still works with the migrated database, for example by adding a column in one release and removing the old one in a later release.
- Several servers are handled by running the same script on each of them over SSH (lesson 179), typically one server or one group at a time behind a load balancer, so that some servers always run a healthy release.
- Zero downtime. The restart in this script causes a brief interruption. Application servers that support graceful reloads (
systemctl reload) start new worker processes from the new release while the old ones finish their current requests, which removes even that gap.
Lesson 203 combines these ideas into a larger deployment automation project.