Restarting A pm2 App Behind Nginx With No 502s
Jake MarshIn this post
A plain pm2 delete and pm2 start leaves the app’s port closed for a second or two while the new process boots. Any request nginx proxies during that window gets a 502. My deploy script now closes that gap with a trick I like a lot: it starts a temporary copy of the new build on a second port, quietly points nginx’s connections at it with one iptables rule, restarts the real app, and takes the rule away again. Nothing in the nginx config changes.
I tested it by sending requests through nginx in a loop during a deploy. 5,473 requests, every one a 200.
The Sequence#
The app runs on port 3000 as pm2 app myapp. The handoff copy always gets the app’s port plus 20,000, so it never needs configuring:
HANDOFF_PORT=$((APP_PORT + 20000))
HANDOFF_NAME="$APP_NAME-handoff"
HANDOFF_TAG="gw-handoff-$APP_NAME"By this point the new build is already on disk next to the running app. The deploy starts it a second time as myapp-handoff on port 23000, with autorestart: false so pm2 won’t try to keep it alive past its job:
module.exports = { apps: [{
name: "myapp-handoff",
script: "./scripts/start-with-port-clear.sh",
exec_mode: "fork",
autorestart: false,
env: { NODE_ENV: "production", PORT: "23000" },
}] };Then it waits until the copy answers. Any HTTP status counts, since all I need to know is that something is listening and talking HTTP:
for i in $(seq 1 60); do
c=$(curl -s -o /dev/null -m 5 -w '%{http_code}' http://127.0.0.1:23000/ || true)
[ "$c" != 000 ] && break
sleep 1
doneOnce it answers, this is the whole trick, once for IPv4 and once for IPv6:
sudo iptables -t nat -I OUTPUT -d 127.0.0.1/32 -p tcp --dport 3000 \
-m owner --uid-owner www-data \
-m comment --comment gw-handoff-myapp \
-j REDIRECT --to-ports 23000
sudo ip6tables -t nat -I OUTPUT -d ::1/128 -p tcp --dport 3000 \
-m owner --uid-owner www-data \
-m comment --comment gw-handoff-myapp \
-j REDIRECT --to-ports 23000From here on, every new connection nginx opens to port 3000 lands on port 23000. The script sleeps 2 seconds so requests already on the old process can finish, then does the restart it always did: pm2 delete myapp, pm2 start ecosystem.config.cjs, pm2 save. It waits up to 90 seconds for port 3000 to answer, deletes the rule, sleeps 5 more seconds so requests already on the handoff can finish, and deletes myapp-handoff.
What A Deploy Looks Like#
Here’s that part of a real deploy log, trimmed, with the app renamed to match:
Starting handoff copy of the new build on :23000...
nginx -> :3000 now goes to the handoff; restarting the app.
[PM2] Applying action deleteProcessId on app [myapp](ids: [ 4 ])
[PM2] [myapp](4) ✓
│ 5 │ myapp-handoff │ fork │ 2551525 │ 7s │ online │ 136.9mb │
[PM2][WARN] Applications myapp not running, starting...
[PM2] App [myapp] launched (1 instances)
│ 6 │ myapp │ fork │ 2551779 │ 0s │ online │ 3.3mb │
│ 5 │ myapp-handoff │ fork │ 2551525 │ 7s │ online │ 136.9mb │
[PM2] Saving current process list...
App answering on :3000 again; draining the handoff.The two pm2 tables tell the story. When the real app is deleted, the handoff has been up for 7 seconds and is already holding 136.9 MB, so it’s fully booted and serving. The new myapp shows up at 3.3 MB, which is the bash wrapper before Next has even loaded. Without the handoff, that’s the moment nginx would be getting connection refused.
The Start Wrapper#
Both copies start through the same small script, start-with-port-clear.sh, which is why the handoff only needs a different PORT:
#!/usr/bin/env bash
set -e
PORT="${PORT:-3000}"
HOLDER=$(ss -tlnp 2>/dev/null | awk -v p=":$PORT" "\$0 ~ p" | grep -oE "pid=[0-9]+" | cut -d= -f2 | head -1)
if [ -n "$HOLDER" ] && [ "$HOLDER" != "$$" ]; then
echo "[start] killing orphan holder pid $HOLDER on port $PORT"
kill -9 "$HOLDER" 2>/dev/null || true
sleep 1
fi
exec node node_modules/next/dist/bin/next start -p "$PORT"next start runs the server in a child process. If pm2 kills the parent and the child survives, the child keeps the port, and the next start fails to bind. The wrapper clears whoever holds its own port first, and the pm2 config sets treekill: true so stops take the whole process tree with them. The handoff runs the same wrapper on 23000, so it can never touch the real app’s port.
Why OUTPUT And Not PREROUTING#
Most iptables port-forwarding examples put REDIRECT in PREROUTING, which handles packets as they arrive on an interface. nginx and the app are on the same machine, so nginx’s connection to 127.0.0.1:3000 is a locally generated packet that never comes in from anywhere. The iptables man page describes the nat table’s OUTPUT chain as being “for altering locally-generated packets before routing,” and that’s the only place these packets pass.
The REDIRECT target is allowed in exactly those two chains, and for OUTPUT it maps the destination to “127.0.0.1 for IPv4 and ::1 for IPv6,” which is where the handoff is listening anyway.
Why Only www-data#
The owner match is what makes this safe to leave running for a minute. --uid-owner www-data only matches packets from sockets owned by nginx’s worker user, and the man page notes the match is “only valid in the OUTPUT and POSTROUTING chains,” which works out since we’re already in OUTPUT.
So nginx gets the handoff, and everyone else still reaches the real port. That includes the deploy’s own health check. When the script curls 127.0.0.1:3000 to see whether the restarted app is up, that curl runs as my deploy user, skips the rule, and hits the real app. Without the owner match, the check would get a happy answer from the handoff and the script would tear it down while the real app was still booting.
The comment match does nothing to the traffic. It tags the rule so the script can find and delete it later without tracking rule numbers.
Why Open Connections Don’t Move#
The nat table, per the man page, “is consulted when a packet that creates a new connection is encountered.” Conntrack remembers the decision for the rest of the connection. That’s what makes both switches clean:
- When the rule goes in, connections already open to the old process stay on the old process.
- When the rule comes out, connections already open to the handoff stay on the handoff until they’re done.
The 2-second and 5-second sleeps are there for exactly those leftover connections.
Why A localhost Upstream Makes The Gap Worse#
On vhosts that use proxy_pass http://localhost:3000, a plain restart cost about 8 seconds of 502s instead of 1 or 2. The proxy_pass docs explain why: “If a domain name resolves to several addresses, all of them will be used in a round-robin fashion.” On my server localhost resolves to both ::1 and 127.0.0.1, so nginx quietly builds a group of two servers.
The upstream module docs say a server is marked unavailable after max_fails failed attempts within fail_timeout, and stays that way for fail_timeout. The defaults are 1 failure and 10 seconds. During a restart, one failed connection to each address marks both of them down, and nginx keeps answering 502 after the app is back, until the timer runs out.
A plain 127.0.0.1 upstream doesn’t have this problem, because “If there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable.” The handoff fixes both cases the same way, since no connection ever fails, so nothing gets marked down. If you don’t want to bother with any of this, switching localhost to 127.0.0.1 in your vhost still gets you back from 8 seconds to 1 or 2.
Cleaning Up After A Bad Deploy#
A deploy can die halfway through, and a leftover REDIRECT rule would keep sending nginx’s connections to port 23000 after nothing listens there anymore. So the script never trusts that it cleaned up last time. It sets trap handoff_cleanup EXIT while the handoff is live, and the first thing every deploy does is delete any rule carrying this app’s tag:
for t in iptables ip6tables; do
sudo $t -t nat -S OUTPUT \
| grep -- '--comment gw-handoff-myapp ' \
| sed 's/^-A/-D/' \
| while read -r r; do eval sudo $t -t nat $r; done
done-S prints each rule in the same syntax you’d use to add it, so swapping -A for -D turns the listing into delete commands. It also deletes any leftover myapp-handoff from pm2. If port 23000 is already taken, or the handoff never answers within 60 seconds, the script skips the trick and does the plain restart it always did.
When Not To Use It#
For about ten seconds, two copies of the app are running. That’s fine for a web app that only answers requests. It’s wrong for an app that runs a scheduler in its own process, because both copies would run the same jobs. Those apps get a .deploy-no-handoff file in their project root and keep the plain restart. The handoff also starts with GW_DEPLOY_HANDOFF=1 in its environment, so an app could check for it and skip its scheduler. For now the apps with in-process jobs opt out instead, which is simpler to trust.
A Cache That Outlives The Restart#
One more thing bit me on Next.js 16.4, and it’s about the window before the restart. Next keeps ISR and notFound results in .next/server/route-cache, keyed by route, with no build id in the key. The old process keeps serving while the new build syncs and installs. If someone requests a page that only the new build has, the old process caches a 404 for it, and the new process happily serves that cached 404 until the next deploy.
So the restart step empties the folder after deleting the old process and before starting the new one:
pm2 delete myapp
find .next/server/route-cache -mindepth 1 -delete 2>/dev/null || true
pm2 start ecosystem.config.cjsBuilds never ship a route-cache, so there’s nothing in there worth keeping.
Testing It#
To see a gap, you need requests going through nginx the whole time the deploy runs. I use a loop like this from my Mac against the public URL, started before the deploy and stopped with Ctrl-C after it:
#!/usr/bin/env bash
# Request a URL in a loop until Ctrl-C, then count the status codes.
url="${1:?usage: hammer.sh https://example.com/}"
out=$(mktemp)
trap 'sort "$out" | uniq -c; exit' INT
while true; do
curl -s -o /dev/null -m 10 -w '%{http_code}\n' "$url" >> "$out"
doneA plain restart shows up as a handful of 502 lines. With the handoff, the only line should be the 200s. 000 means curl gave up, which points at the network rather than nginx.
While the rule is live, the packet counters show it working:
sudo iptables -t nat -L OUTPUT -n -vSince the nat table only sees the first packet of each connection, the pkts column on the REDIRECT rule is the number of connections nginx sent to the handoff. And after a deploy, this should print nothing:
sudo iptables -t nat -S OUTPUT | grep gw-handoffOther Ways To Do This#
There are more standard tools for this, and I looked at each one:
- pm2 cluster mode does have
pm2 reload, which the pm2 docs say “achieves a 0-second-downtime reload.” Cluster mode only works for JavaScript run by Node or Bun, though, and my apps start through a small bash wrapper that pm2 runs in fork mode. - systemd socket activation lets systemd hold the listening socket while the service restarts, but the app has to accept the socket from systemd (systemd.socket,
sd_listen_fds), and these apps are run by pm2. - An nginx
backupserver in an upstream block is “passed requests when the primary servers are unavailable.” That needs an upstream block in every vhost and a second copy of every app listening on the backup port all the time. - SO_REUSEPORT lets two processes bind the same port (socket(7)), but it “must be set on each socket (including the first socket) prior to calling bind(2),” which means changing how every app opens its port.
The handoff fit because it needs nothing from the app or the vhost. Any app that reads its port from PORT gets it for free, and the only moving part is a rule that exists for a few seconds per deploy.