Linux and Git commands · Lesson 23 of 23
Capstone: deploy a small app to a Linux server over SSH with Git
Put the whole module to work by shipping a tagged release to a server, checking that it is healthy, and rolling back when it is not.
On this page
This lesson ties the module together. You will take a tiny web app, push it to a server with Git, deploy a tagged release into its own folder, switch a symbolic link to make it live, check it with curl, and roll back. Nothing here is new: every step uses something from lessons 1 to 22.
Why this matters#
A deploy is the moment code meets the real world, and most outages happen right then. A good deploy is boring: the same few commands every time, a version you can name, a check that proves it works and a one-line way back. That is what we build here, using only tools that exist on every Linux server.
What was actually run#
We ran every command on a Linux machine, with these honest substitutions:
- The "server" was a local SSH server on
127.0.0.1port 2222, reached as the userdeploythrough an SSH aliasweb1. On a real server,web1would point at an address such as203.0.113.10(lesson 10). - The test machine has no systemd, so the restart step used a small stand-in script. On a real server the restart is
sudo systemctl restart capapp, which we could not run here. The unit file and the sudo rule below are written from lesson 9 and from the standard form; check them on your own server. - Output lines have been trimmed to the relevant ones. Our very first deploy ran an earlier copy of the script that also printed Git's long "detached HEAD" notice; the script shown here silences it, and the output of the
v1.0.0deploy above is what the final script prints.
The plan#
The deploy has five parts.
- The app lives in a Git repository on your laptop. Each release gets an annotated tag such as
v1.0.0(lesson 20). - The server has a bare Git repository,
/srv/cap/repo.git, to push to (lesson 17), and a folder layout like the one from lesson 2. - A deploy script on the server checks out one tag into
releases/<tag>, links the shared.env, pointscurrentat the new release, restarts the app and checks its health. - A rollback is the same script run with an older tag.
- The app runs as a service under the
deployuser, never as root (lessons 7 and 9).
The server layout:
/srv/cap/
repo.git/ bare repository that you push to
releases/
v1.0.0/ one folder per release
v1.1.0/
shared/
.env secrets and settings, mode 600, never in Git
current -> releases/v1.1.0
deploy.shStep 1: prepare the server#
Log in as deploy (lesson 10: your public key is in ~/.ssh/authorized_keys with the right permissions) and create the folders and the bare repository. We piped a short script into SSH, which is a handy way to run several commands remotely:
set -euo pipefail
mkdir -p /srv/cap/releases /srv/cap/shared
git init -q --bare /srv/cap/repo.git
echo 'PORT=5100' > /srv/cap/shared/.env
chmod 600 /srv/cap/shared/.envssh web1 'bash -s' < setup.shOn a fresh server, /srv/cap must first be created and owned by deploy, which needs sudo mkdir /srv/cap && sudo chown deploy /srv/cap. The .env has mode 600 because it holds secrets. Only the deploy user can read it.
A bare repository has no working files, only the history. It is the same kind of thing a hosting service keeps for you, and it is the right target for a push.
Step 2: the app and the first release#
The app is a dependency-free Node server with a /health endpoint that reports its version, read from a VERSION file. The point of the endpoint is that a deploy script can ask the app whether it works.
const http = require('http');
const fs = require('fs');
const port = Number(process.env.PORT || 5100);
const version = fs.readFileSync(__dirname + '/VERSION', 'utf8').trim();
http
.createServer((req, res) => {
if (req.url === '/health') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ status: 'ok', version }));
return;
}
res.statusCode = 404;
res.end('not found\n');
})
.listen(port, '127.0.0.1', () => console.log(`listening on ${port}, version ${version}`));It listens on 127.0.0.1 only (lesson 10): in production a web server such as nginx would sit in front and pass requests to it. The repository has a .gitignore containing .env, node_modules/ and *.log (lesson 14). Commit, tag, add the server as a remote called production, and push the branch and the tags:
git commit -qm "Add health endpoint and deploy script"
git tag -a v1.0.0 -m "Release 1.0.0"
git remote add production ssh://web1/srv/cap/repo.git
git push production main --tagsTo ssh://web1/srv/cap/repo.git
* [new branch] main -> main
* [new tag] v1.0.0 -> v1.0.0Remember from lesson 20 that tags are not pushed unless you ask, which is why --tags is there.
Step 3: the deploy script#
This script lives in the repository and is copied to the server with scp. Read it slowly: it uses set -euo pipefail, functions, a loop, exit codes and curl -f, all from lesson 12.
#!/usr/bin/env bash
# Deploy one tagged release. Run on the server as the deploy user: ./deploy.sh v1.0.0
set -euo pipefail
TAG="${1:?usage: deploy.sh TAG}"
BASE="${BASE:-/srv/cap}"
RESTART_CMD="${RESTART_CMD:-sudo systemctl restart capapp}"
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:5100/health}"
REL="$BASE/releases/$TAG"
log() { echo "[deploy] $*"; }
wait_healthy() {
for i in 1 2 3 4 5 6 7 8 9 10; do
if curl -sf "$HEALTH_URL" > /dev/null; then return 0; fi
sleep 1
done
return 1
}
if [[ ! -d "$REL" ]]; then
log "fetching $TAG"
git -c advice.detachedHead=false clone -q --branch "$TAG" --depth 1 "file://$BASE/repo.git" "$REL"
fi
ln -sfn "$BASE/shared/.env" "$REL/.env"
previous="$(readlink -f "$BASE/current" || true)"
ln -sfn "$REL" "$BASE/current"
log "current -> $(readlink -f "$BASE/current")"
$RESTART_CMD
if wait_healthy; then
log "healthy: $(curl -s "$HEALTH_URL")"
else
log "health check failed, rolling back" >&2
if [[ -n "$previous" && -d "$previous" ]]; then
ln -sfn "$previous" "$BASE/current"
$RESTART_CMD
fi
exit 1
fiWhat each part does:
TAG="${1:?usage...}"takes the tag from the first argument and stops with a message if it is missing.git clone --branch "$TAG"can check out a tag, and--depth 1fetches only that one commit. Afile://address makes--depthapply to a local clone. The clone is a detached HEAD at the tag (lesson 15), which is exactly right: a release folder is a fixed snapshot, never a place to commit.- If the release folder already exists, the script reuses it, which makes a rollback fast.
ln -sfnlinks the shared.envinto the release, and then switchescurrent(lesson 3). The-nstopslnfrom creating a link inside the previous release folder.- It remembers where
currentpointed before, so it can go back. wait_healthyasks the app/healthfor up to ten seconds.curl -fmakes an error response count as a failure, so a 500 page does not pass.- If the app never becomes healthy, the script restores the old link, restarts and exits with code 1, so whoever called it knows the deploy failed.
Step 4: deploy#
Copy the script over once, then run it for the tag you pushed. We set RESTART_CMD to the stand-in script:
scp deploy.sh web1:/srv/cap/deploy.sh
ssh web1 'chmod +x /srv/cap/deploy.sh'
ssh web1 '/srv/cap/deploy.sh v1.0.0'[deploy] fetching v1.0.0
[deploy] current -> /srv/cap/releases/v1.0.0
[deploy] healthy: {"status":"ok","version":"1.0.0"}Check the result with the tools from earlier lessons:
ssh web1 'ls -l /srv/cap/current; curl -s http://127.0.0.1:5100/health; ss -ltnp | grep 5100'lrwxrwxrwx 1 deploy deploy 24 Dec 3 01:17 /srv/cap/current -> /srv/cap/releases/v1.0.0
{"status":"ok","version":"1.0.0"}
LISTEN 0 511 127.0.0.1:5100 0.0.0.0:* users:(("node",pid=298,fd=21))The link points at the release, the app answers with the right version, and the only listener on port 5100 is the Node process. Next we bumped VERSION, committed, tagged v1.1.0, pushed and deployed it:
[deploy] fetching v1.1.0
[deploy] current -> /srv/cap/releases/v1.1.0
[deploy] healthy: {"status":"ok","version":"1.1.0"}Both release folders now exist side by side, and nothing was overwritten. The previous version is one ln -sfn away.
Step 5: a bad release rolls itself back#
We then tagged v1.2.0 with a deliberate bug: the app throws an error as soon as it starts. The script switched the link, restarted and waited:
[deploy] fetching v1.2.0
[deploy] current -> /srv/cap/releases/v1.2.0
[deploy] health check failed, rolling back
exit=1Afterwards, current pointed at v1.1.0 again and the old version answered {"status":"ok","version":"1.1.0"}. Users saw at most a few seconds of trouble, and the exit code said what happened. On a real server, your next step would be reading why it crashed with journalctl -u capapp -n 50 (lesson 9).
Step 6: roll back on purpose#
Sometimes a release passes the health check and is still wrong, for example a slow query or a wrong number. Rolling back is the same script with an older tag:
ssh web1 '/srv/cap/deploy.sh v1.0.0'
ssh web1 'cd /srv/cap/current && git describe --tags && cat VERSION'[deploy] current -> /srv/cap/releases/v1.0.0
[deploy] healthy: {"status":"ok","version":"1.0.0"}
v1.0.0
1.0.0Because the release folder was a clone of the tag, git describe --tags on the server tells you exactly which version is live. When someone asks "what is running?", you can answer from the server in one command. Old release folders can be cleaned up later, keeping the last few for rollbacks. List them oldest first with ls -1t /srv/cap/releases | tail -n +4 and remove them deliberately, after looking at the list (lesson 3).
What a real server adds#
These parts could not be run in our test, so treat them as a checklist for a real server:
- A systemd unit so the app starts at boot and restarts on failure, as in lesson 9. It would run
node server.jsfrom/srv/cap/current, asUser=deploy, withEnvironmentFile=/srv/cap/shared/.env. Rememberdaemon-reloadandenable --now. - A narrow sudo rule. The deploy script needs to restart one service and nothing else. Edit it with
sudo visudo -f /etc/sudoers.d/deployand allow exactly one command, in the formdeploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart capapp. Do not give the deploy user full root. - A reverse proxy and HTTPS, such as nginx, which listens on ports 80 and 443 and passes requests to
127.0.0.1:5100. - A firewall that allows only SSH and web traffic, so port 5100 is never open to the internet.
- Keys, not passwords, for SSH, with password logins turned off once keys work.
- Database migrations as a separate, deliberate step. Rolling back code does not roll back a database.
Try it#
- Create a small app (any language) with a
/healthendpoint and aVERSIONfile in a Git repository. Add a.gitignorethat excludes.env. Commit and tag itv1.0.0with an annotated tag. - Set up a practice "server": a Linux VM, a container or a second user on your machine with SSH. Create the folder layout and a bare repository. Add it as a remote and push the branch with
--tags. - Write the deploy script above from memory, adapting it to your app. Run
bash -non it, then deployv1.0.0and verify withcurl,ls -l currentandss -ltnp. - Release
v1.1.0and deploy it. Then release a version that crashes on start and confirm that the script rolls back and exits with a non-zero code. - Write a short checklist for your own team: how to deploy, how to check, how to roll back and where to read the logs. Keep it to ten lines.
Sign in to keep track of the lessons you finish.