Cloud and deployment · Advanced · 22 min
Deploy a new app version with zero downtime behind Nginx
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Nginx 1.30.8 · Node.js 26.13.1
You will have a deploy script that starts a new Node.js release on a spare port, waits for its health check, switches Nginx over with a reload, drains the old release and stops it, with a curl loop proving that no request failed.
On this page
A deploy that runs systemctl restart on your only app process has a gap. For a second or two nothing listens on the port, Nginx answers 502 Bad Gateway, and any request that was half-way through is cut off. On a busy site that is dozens of failed checkouts or form posts per deploy. People on mobile data, who are already paying for every retry, feel it most.
The fix on a single server is to never replace the running process in place. You start the new version beside the old one on a second port, check that it is healthy, point Nginx at it with a reload (which does not drop connections), and only then ask the old version to finish what it is doing and exit. The next deploy goes the other way. This is blue-green deployment shrunk to one machine, with two ports, 3001 and 3002, as the two colours.
In this tutorial you build each piece and then measure the result: a loop of curl requests runs through the whole deploy and counts every response that is not 200. The target is zero. The last step covers the part code alone cannot fix: database migrations, which both versions share during the switch.
This is a different problem from deploying over SSH with GitHub Actions, which unpacks a static site and switches a current symlink; there is no app process to replace, so Nginx simply serves the new files. A running app process holds a port and its in-flight requests, and that is what the two-port switch shown here handles. That workflow's forced-command script can be adapted to call the script you write here, with one sudoers rule shown under Next steps.
Step 1 · Write an app that can stop gracefully
Zero downtime starts in the app. When asked to stop, it must stop taking new connections, finish the requests it already has, and then exit. Most frameworks do not do this unless you ask. Node.js leaves SIGTERM handling to you: by default the process dies at once and takes its open requests with it.
Check your Node.js version first:
node --versionIt prints v26. followed by the minor and patch numbers.
Each release lives in its own directory under /opt/zdd-demo/releases, with a VERSION file beside the code. Create the first release:
sudo mkdir -p /opt/zdd-demo/releases/v1 /opt/zdd-demo/slots
echo v1 | sudo tee /opt/zdd-demo/releases/v1/VERSION > /dev/null
sudo tee /opt/zdd-demo/releases/v1/server.js > /dev/null <<'JS'
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const port = Number(process.env.PORT);
const version = fs.readFileSync(path.join(__dirname, 'VERSION'), 'utf8').trim();
let draining = false;
const server = http.createServer((req, res) => {
res.setHeader('X-App-Version', version);
if (req.url === '/healthz') {
res.writeHead(draining ? 503 : 200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: draining ? 'draining' : 'ok', version }));
return;
}
if (req.url === '/slow') {
setTimeout(() => res.end(`slow reply from ${version}\n`), 3000);
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`hello from ${version} on port ${port}\n`);
});
server.listen(port, '127.0.0.1', () => {
console.log(`${version} listening on ${port}`);
});
process.on('SIGTERM', () => {
draining = true;
console.log(`${version} draining`);
// Stop accepting connections, close idle keep-alive ones, wait for the rest.
server.close(() => {
console.log(`${version} stopped cleanly`);
process.exit(0);
});
// Never hang for ever: give up well before systemd's own stop timeout.
setTimeout(() => {
console.error(`${version} drain timed out`);
process.exit(1);
}, 20000).unref();
});
JSThree things in this file make the deploy work:
/healthzanswers with the version, so a deploy script can check that the right code is running, not just that something is.- On
SIGTERM,server.close()stops the listener and waits for in-flight requests. Since Node.js 19 it also closes keep-alive connections that are idle, so a browser holding a connection open does not keep the old process alive. - The 20-second timer is a backstop. A request stuck on a dead database should not block the deploy for ever.
The /slow route takes three seconds to answer. It is there so you can watch a request survive a shutdown in the next step. Leave it out of your own app.
Check it worked
node --check /opt/zdd-demo/releases/v1/server.js && echo syntax ok
cat /opt/zdd-demo/releases/v1/VERSIONThe output is syntax ok and v1.
Step 2 · Run two instances with a systemd template unit
A template unit is one unit file that systemd can start many times. The text after @ in the unit name becomes %i inside the file, so zdd-app@3001 and zdd-app@3002 are two separate services from one definition. Here %i is the port, and each port has a slot directory, a symlink to whichever release that port runs.
Create a system user for the app, so it does not run as root:
sudo useradd --system --no-create-home --shell /usr/sbin/nologin zddWrite the unit. If you installed Node.js another way, change /usr/bin/node to the output of command -v node:
sudo tee /etc/systemd/system/zdd-app@.service > /dev/null <<'UNIT'
[Unit]
Description=Zero-downtime demo app on port %i
After=network.target
[Service]
Type=simple
User=zdd
Environment=PORT=%i
WorkingDirectory=/opt/zdd-demo/slots/%i
ExecStart=/usr/bin/node server.js
KillSignal=SIGTERM
TimeoutStopSec=30
Restart=on-failure
[Install]
WantedBy=multi-user.target
UNITKillSignal=SIGTERM is the default, written out so the next person sees the contract. TimeoutStopSec=30 is how long systemd waits after SIGTERM before it sends SIGKILL. Keep it longer than the app's own 20-second backstop.
Point both slots at v1 and start port 3001:
sudo ln -sfn /opt/zdd-demo/releases/v1 /opt/zdd-demo/slots/3001
sudo ln -sfn /opt/zdd-demo/releases/v1 /opt/zdd-demo/slots/3002sudo systemctl daemon-reload
sudo systemctl enable --now zdd-app@3001Now prove the shutdown is graceful. Start a second instance on 3002, send it a slow request, and stop the instance while that request is in flight:
sudo systemctl start zdd-app@3002mkdir -p ~/zdd-check
cd ~/zdd-check
curl -s http://127.0.0.1:3002/slow > slow.txt &
sleep 1sudo systemctl stop zdd-app@3002wait
cat slow.txtsystemctl stop sends SIGTERM and waits. It returns after about two seconds, once the slow request has been answered.
Check it worked
slow.txt holds slow reply from v1: the request finished even though the process was told to stop. Read the instance's log:
sudo journalctl -u zdd-app@3002 -n 10 --no-pagerAmong systemd's own Stopping ... and Stopped ... lines you see the app's three lines: v1 listening on 3002, v1 draining and v1 stopped cleanly. If you see the process killed instead, the SIGTERM handler is missing or the code never reaches server.close(). Port 3001 is still running and answers {"status":"ok","version":"v1"} at /healthz.
Step 3 · Put Nginx in front with a one-line upstream
Nginx should send traffic to whichever port is live. Keep that choice in a file of its own that holds nothing else, so the deploy script can rewrite it without touching the rest of the config:
sudo tee /etc/nginx/conf.d/zdd-upstream.conf > /dev/null <<'CONF'
upstream zdd_app {
server 127.0.0.1:3001;
}
CONF
sudo tee /etc/nginx/conf.d/zdd.conf > /dev/null <<'CONF'
server {
listen 80;
server_name zdd.example.com;
location / {
proxy_pass http://zdd_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
CONF
sudo nginx -tReplace zdd.example.com with your own domain. The tutorial sends the name in a Host header, so it works before DNS is set up.
sudo systemctl reload nginxYou could list both ports in the upstream and mark the idle one backup, a parameter covered in the Nginx load balancing tutorial, but Nginx would then still send traffic to the backup whenever the live port fails, including to an old version you meant to retire. One server line is easier to read at a glance, and when you look at this file during an incident it tells you the live port with no thought.
Check it worked
curl -s -H 'Host: zdd.example.com' http://127.0.0.1/
curl -s -o /dev/null -w '%header{x-app-version}\n' -H 'Host: zdd.example.com' http://127.0.0.1/The first line is hello from v1 on port 3001 and the second is v1. %header{...} needs curl 7.84 or later, which Ubuntu 26.04 has.
Step 4 · Write the deploy script
The script takes a release directory and does the switch in a fixed order. Each step only happens if the one before it worked, and until Nginx is reloaded the live version has not been touched, so an early failure leaves visitors on the old release:
- Read the live port from the upstream file and pick the other one.
- Point that port's slot at the new release and start it.
- Wait until its
/healthzreports the new version. Give up after 30 seconds. - Rewrite the upstream file, test the config, and reload Nginx.
- Wait a few seconds for requests that Nginx already sent to the old port, then stop the old instance, which drains on
SIGTERM.
sudo tee /usr/local/bin/zdd-deploy > /dev/null <<'SH'
#!/usr/bin/env bash
# Usage: sudo zdd-deploy /opt/zdd-demo/releases/<version>
set -euo pipefail
RELEASE="${1:?usage: zdd-deploy <release-dir>}"
SLOTS=/opt/zdd-demo/slots
UPSTREAM=/etc/nginx/conf.d/zdd-upstream.conf
HOLD_SECONDS="${HOLD_SECONDS:-5}"
# One deploy at a time.
exec 9> /run/zdd-deploy.lock
flock -n 9 || { echo "another deploy is running" >&2; exit 1; }
[ -f "$RELEASE/server.js" ] || { echo "no server.js in $RELEASE" >&2; exit 1; }
VERSION="$(cat "$RELEASE/VERSION")"
OLD="$(grep -oE '127\.0\.0\.1:[0-9]+' "$UPSTREAM" | cut -d: -f2)"
case "$OLD" in
3001) NEW=3002 ;;
3002) NEW=3001 ;;
*) echo "cannot read the live port from $UPSTREAM" >&2; exit 1 ;;
esac
echo "deploying $VERSION to port $NEW (live now: $OLD)"
# Start the new version on the spare port.
systemctl stop "zdd-app@$NEW" 2> /dev/null || true
ln -sfn "$RELEASE" "$SLOTS/$NEW"
systemctl enable --now "zdd-app@$NEW"
# Wait for it to report the right version.
healthy=no
for i in $(seq 1 30); do
body="$(curl -fsS "http://127.0.0.1:$NEW/healthz" 2> /dev/null || true)"
case "$body" in
*"\"version\":\"$VERSION\""*) healthy=yes; break ;;
esac
sleep 1
done
if [ "$healthy" != yes ]; then
echo "$VERSION never became healthy on $NEW; traffic stays on $OLD" >&2
systemctl disable --now "zdd-app@$NEW"
exit 1
fi
# Switch Nginx, keeping the old file in case the new one fails the test.
cp "$UPSTREAM" /run/zdd-upstream.previous
printf 'upstream zdd_app {\n server 127.0.0.1:%s;\n}\n' "$NEW" > "$UPSTREAM"
if ! nginx -t -q; then
cp /run/zdd-upstream.previous "$UPSTREAM"
systemctl disable --now "zdd-app@$NEW"
echo "nginx config test failed; restored the previous upstream" >&2
exit 1
fi
systemctl reload nginx
# Let requests already sent to the old port finish, then drain and stop it.
sleep "$HOLD_SECONDS"
systemctl disable --now "zdd-app@$OLD"
echo "live: $VERSION on port $NEW"
SH
sudo chmod 755 /usr/local/bin/zdd-deploySome details worth knowing:
systemctl reload nginxstarts new worker processes with the new upstream. The old workers stop accepting connections, finish the requests they hold, and exit. Nobody gets a closed socket.restartwould stop Nginx itself and is the wrong command here.enable --nowanddisable --nowkeep the boot state in step with the live port. After a reboot, the instance Nginx points at is the one that starts.- The
flockline stops two deploys, say from two CI jobs, from picking the same spare port at once. - Starting the new version means both run at once for a few seconds, so the server needs memory for two copies. On a small 1 GB VPS, run
free -mbefore your first deploy and check there is room.
Check it worked
bash -n /usr/local/bin/zdd-deploy && echo script ok
ls -l /usr/local/bin/zdd-deployThe output is script ok and a line that starts with -rwxr-xr-x.
Step 5 · Deploy v2 while counting failed requests
Make the second release. A real release would be a fresh build or checkout; here it is a copy with a new version number:
sudo cp -r /opt/zdd-demo/releases/v1 /opt/zdd-demo/releases/v2
echo v2 | sudo tee /opt/zdd-demo/releases/v2/VERSION > /dev/nullNow start a loop that sends a request through Nginx about twenty times a second and writes the status code and version of each answer to a file. Run the deploy while it goes, then stop the loop:
cd ~/zdd-check
rm -f codes.txt stop
(
while [ ! -e stop ]; do
curl -s -o /dev/null --max-time 5 -H 'Host: zdd.example.com' \
-w '%{http_code} %header{x-app-version}\n' http://127.0.0.1/ >> codes.txt || true
sleep 0.05
done
) &
LOOP_PID=$!
sleep 2
sudo zdd-deploy /opt/zdd-demo/releases/v2
sleep 2
touch stop
wait "$LOOP_PID"The deploy prints deploying v2 to port 3002 (live now: 3001) and, about six seconds later, live: v2 on port 3002. A request that fails to connect is written as 000, and a gateway error as 502, so neither can hide.
Check it worked
Count the requests, the failures, and which version answered:
wc -l < codes.txt
awk '$1 != 200' codes.txt | wc -l
awk '{print $2}' codes.txt | uniq -cThe first number is the total, about a hundred or more. The second is 0: no request failed. The last command shows a run of v1 answers followed by a run of v2 answers, something like 45 v1 then 70 v2. Nothing listens on port 3001 any more, and curl -s -H 'Host: zdd.example.com' http://127.0.0.1/ answers hello from v2 on port 3002.
Run the same loop around a plain sudo systemctl restart of a single instance and expect 502 or 000 lines for the moment nothing listens. Removing that gap is the point of the whole setup.
Step 6 · Roll back by deploying the previous release
A rollback is a deploy of an older release. Its directory is still on disk, so it takes as long as any deploy and goes through the same health check:
sudo zdd-deploy /opt/zdd-demo/releases/v1The script moves traffic from 3002 back to 3001, because 3001 is now the spare port. Keep the last few release directories for this reason and delete older ones from a cleanup job.
The script also protects you from a bad release on its own. If a release crashes at start-up or reports the wrong version, the health loop gives up, the new instance is stopped, and Nginx never sees it.
Check it worked
curl -s -H 'Host: zdd.example.com' http://127.0.0.1/
cat /etc/nginx/conf.d/zdd-upstream.confThe app answers hello from v1 on port 3001, and the upstream file names 127.0.0.1:3001.
Step 7 · Change the database without breaking either version
For a few seconds of every deploy, the old and new versions run at the same time against the same database. After a rollback, the old code runs against whatever the new release did to the schema. So a migration that renames or drops a column the old code reads breaks the site, however clean the switch was.
The way out is to split each breaking change into steps that are each safe for the code on both sides of them. This is the expand-and-contract pattern. Take renaming users.name to users.display_name in PostgreSQL:
- Expand (release A). Add the new column, nullable, with no default that rewrites the table. Release A writes to both columns and still reads
name. - Migrate (between releases). Copy the old values into the new column, in batches on a large table.
- Switch reads (release B). Read
display_name, keep writing both. Rolling back to A is still safe, becausenameis still kept up to date. - Contract (release C, at least one deploy later). Stop writing
name, then drop it in a migration that runs after C is live everywhere.
-- Release A, before its code starts: expand
ALTER TABLE users ADD COLUMN display_name text;
-- Between A and B: copy the data
UPDATE users SET display_name = name WHERE display_name IS NULL;
-- After release C is live and no running version reads "name": contract
ALTER TABLE users DROP COLUMN name;Run the expand migration before zdd-deploy starts the new code, so the new version finds its column. Run the contract migration only when no release that reads the old column can come back, which means after you have stopped rolling back to it.
The same rule covers other changes. Adding a NOT NULL column needs a default or a backfill first. A new table is safe. A new required field in an API request needs the old clients to be gone first.
Check it worked
Take the next migration you plan to write and ask of each statement: does the code that is live now still work after it runs, and does the new code work before the next one runs? Write the release each statement belongs to (A, between, B or C) next to it in the migration file. If any statement fails the question, split it until none does.
Step 8 · Clean up
These commands stop both instances and remove everything this tutorial created: the units, the Nginx files, the script, the releases, the check files and the zdd user. They do not touch Nginx or Node.js themselves.
sudo systemctl disable --now zdd-app@3001 zdd-app@3002sudo rm -f /etc/systemd/system/zdd-app@.service
sudo rm -f /etc/nginx/conf.d/zdd.conf /etc/nginx/conf.d/zdd-upstream.conf
sudo nginx -tsudo systemctl daemon-reload
sudo systemctl reload nginxsudo rm -f /usr/local/bin/zdd-deploy /run/zdd-deploy.lock /run/zdd-upstream.previous
sudo rm -rf /opt/zdd-demo
rm -rf ~/zdd-check
sudo userdel zdd
cd ~Check it worked
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3001/ || truecurl prints 000, because nothing listens on port 3001 any more.
Next steps
- Compare this one-server switch with the other ways to release: blue-green, canary and rolling deployments.
- Trigger
zdd-deployfrom CI: adapt the forced-command script in deploy to a server over SSH with GitHub Actions to unpack an app release, then runsudo /usr/local/bin/zdd-deployon it. Thedeployuser is not root, so it needs one sudoers rule (add it withsudo visudo -f /etc/sudoers.d/zdd-deploy) that allows that command and nothing else:deploy ALL=(root) NOPASSWD: /usr/local/bin/zdd-deploy. - Grow from two ports on one server to several servers: load balance with an Nginx upstream.
Related tutorials
- How to Load Balance Traffic Across Servers with NginxYou will spread requests across three backends with an Nginx upstream block, weight them, keep a spare in reserve, and watch Nginx route around a backend that stops answering.
- How to Deploy to Your Server over SSH from GitHub ActionsYou will set up a deploy key that can only do one thing on your Ubuntu 26.04 server, store it as an encrypted GitHub environment secret, and write a workflow that uploads each release over SSH and switches to it with a single atomic step.
- Understand blue-green, canary and rolling deploymentsYou will know what rolling, blue-green and canary releases need and how each rolls back, and you will have run a canary on one server that sends 10% of users to a new version with Nginx split_clients, judged it from the logs and rolled it back.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials