{"title":"Restarting A pm2 App Behind Nginx With No 502s","html_url":"https://deallocatedobjects.com/posts/restarting-a-pm2-app-behind-nginx-with-no-502s","source_url":"","markdown_content":"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.\n\nI tested it by sending requests through nginx in a loop during a deploy. 5,473 requests, every one a 200.\n\n### The Sequence\n\nThe 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:\n\n```bash title=\"deploy-app.sh\"\nHANDOFF_PORT=$((APP_PORT + 20000))\nHANDOFF_NAME=\"$APP_NAME-handoff\"\nHANDOFF_TAG=\"gw-handoff-$APP_NAME\"\n```\n\nBy 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:\n\n```js title=\"handoff.config.cjs\"\nmodule.exports = { apps: [{\n  name: \"myapp-handoff\",\n  script: \"./scripts/start-with-port-clear.sh\",\n  exec_mode: \"fork\",\n  autorestart: false,\n  env: { NODE_ENV: \"production\", PORT: \"23000\" },\n}] };\n```\n\nThen it waits until the copy answers. Any HTTP status counts, since all I need to know is that something is listening and talking HTTP:\n\n```bash\nfor i in $(seq 1 60); do\n  c=$(curl -s -o /dev/null -m 5 -w '%{http_code}' http://127.0.0.1:23000/ || true)\n  [ \"$c\" != 000 ] && break\n  sleep 1\ndone\n```\n\nOnce it answers, this is the whole trick, once for IPv4 and once for IPv6:\n\n```bash\nsudo iptables -t nat -I OUTPUT -d 127.0.0.1/32 -p tcp --dport 3000 \\\n  -m owner --uid-owner www-data \\\n  -m comment --comment gw-handoff-myapp \\\n  -j REDIRECT --to-ports 23000\nsudo ip6tables -t nat -I OUTPUT -d ::1/128 -p tcp --dport 3000 \\\n  -m owner --uid-owner www-data \\\n  -m comment --comment gw-handoff-myapp \\\n  -j REDIRECT --to-ports 23000\n```\n\nFrom 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`.\n\n### What A Deploy Looks Like\n\nHere's that part of a real deploy log, trimmed, with the app renamed to match:\n\n```text\n    Starting handoff copy of the new build on :23000...\n    nginx -> :3000 now goes to the handoff; restarting the app.\n[PM2] Applying action deleteProcessId on app [myapp](ids: [ 4 ])\n[PM2] [myapp](4) ✓\n│ 5  │ myapp-handoff    │ fork │ 2551525 │ 7s  │ online │ 136.9mb │\n[PM2][WARN] Applications myapp not running, starting...\n[PM2] App [myapp] launched (1 instances)\n│ 6  │ myapp            │ fork │ 2551779 │ 0s  │ online │ 3.3mb   │\n│ 5  │ myapp-handoff    │ fork │ 2551525 │ 7s  │ online │ 136.9mb │\n[PM2] Saving current process list...\n    App answering on :3000 again; draining the handoff.\n```\n\nThe 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.\n\n### The Start Wrapper\n\nBoth copies start through the same small script, `start-with-port-clear.sh`, which is why the handoff only needs a different `PORT`:\n\n```bash title=\"scripts/start-with-port-clear.sh\"\n#!/usr/bin/env bash\nset -e\nPORT=\"${PORT:-3000}\"\nHOLDER=$(ss -tlnp 2>/dev/null | awk -v p=\":$PORT\" \"\\$0 ~ p\" | grep -oE \"pid=[0-9]+\" | cut -d= -f2 | head -1)\nif [ -n \"$HOLDER\" ] && [ \"$HOLDER\" != \"$$\" ]; then\n  echo \"[start] killing orphan holder pid $HOLDER on port $PORT\"\n  kill -9 \"$HOLDER\" 2>/dev/null || true\n  sleep 1\nfi\nexec node node_modules/next/dist/bin/next start -p \"$PORT\"\n```\n\n`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.\n\n### Why OUTPUT And Not PREROUTING\n\nMost 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](https://ipset.netfilter.org/iptables.man.html) 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.\n\nThe [REDIRECT target](https://ipset.netfilter.org/iptables-extensions.man.html) 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.\n\n### Why Only www-data\n\nThe `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`.\n\nSo 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.\n\nThe `comment` match does nothing to the traffic. It tags the rule so the script can find and delete it later without tracking rule numbers.\n\n### Why Open Connections Don't Move\n\nThe `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:\n\n- When the rule goes in, connections already open to the old process stay on the old process.\n- When the rule comes out, connections already open to the handoff stay on the handoff until they're done.\n\nThe 2-second and 5-second sleeps are there for exactly those leftover connections.\n\n### Why A localhost Upstream Makes The Gap Worse\n\nOn 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](https://nginx.org/en/docs/http/ngx_http_proxy_module.html) 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.\n\nThe [upstream module docs](https://nginx.org/en/docs/http/ngx_http_upstream_module.html) 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.\n\nA 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.\n\n### Cleaning Up After A Bad Deploy\n\nA 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:\n\n```bash\nfor t in iptables ip6tables; do\n  sudo $t -t nat -S OUTPUT \\\n    | grep -- '--comment gw-handoff-myapp ' \\\n    | sed 's/^-A/-D/' \\\n    | while read -r r; do eval sudo $t -t nat $r; done\ndone\n```\n\n`-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.\n\n### When Not To Use It\n\nFor 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.\n\n### A Cache That Outlives The Restart\n\nOne 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.\n\nSo the restart step empties the folder after deleting the old process and before starting the new one:\n\n```bash\npm2 delete myapp\nfind .next/server/route-cache -mindepth 1 -delete 2>/dev/null || true\npm2 start ecosystem.config.cjs\n```\n\nBuilds never ship a `route-cache`, so there's nothing in there worth keeping.\n\n### Testing It\n\nTo 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:\n\n```bash title=\"hammer.sh\"\n#!/usr/bin/env bash\n# Request a URL in a loop until Ctrl-C, then count the status codes.\nurl=\"${1:?usage: hammer.sh https://example.com/}\"\nout=$(mktemp)\ntrap 'sort \"$out\" | uniq -c; exit' INT\nwhile true; do\n  curl -s -o /dev/null -m 10 -w '%{http_code}\\n' \"$url\" >> \"$out\"\ndone\n```\n\nA plain restart shows up as a handful of `502` lines. With the handoff, the only line should be the `200`s. `000` means curl gave up, which points at the network rather than nginx.\n\nWhile the rule is live, the packet counters show it working:\n\n```bash\nsudo iptables -t nat -L OUTPUT -n -v\n```\n\nSince 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:\n\n```bash\nsudo iptables -t nat -S OUTPUT | grep gw-handoff\n```\n\n### Other Ways To Do This\n\nThere are more standard tools for this, and I looked at each one:\n\n- **pm2 cluster mode** does have `pm2 reload`, which the [pm2 docs](https://pm2.keymetrics.io/docs/usage/cluster-mode/) 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.\n- **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](https://www.freedesktop.org/software/systemd/man/latest/systemd.socket.html), `sd_listen_fds`), and these apps are run by pm2.\n- **An nginx `backup` server** 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.\n- **SO_REUSEPORT** lets two processes bind the same port ([socket(7)](https://man7.org/linux/man-pages/man7/socket.7.html)), 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.\n\nThe 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.","html_content":"<p>A plain <code>pm2 delete</code> and <code>pm2 start</code> 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.</p>\n<p>I tested it by sending requests through nginx in a loop during a deploy. 5,473 requests, every one a 200.</p>\n<h2 id=\"the-sequence\" data-level=\"3\">The Sequence</h2>\n<p>The app runs on port 3000 as pm2 app <code>myapp</code>. The handoff copy always gets the app’s port plus 20,000, so it never needs configuring:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"file\">deploy-app.sh</span><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">HANDOFF_PORT</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$((</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">APP_PORT</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> +</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 20000</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">))</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">HANDOFF_NAME</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$APP_NAME</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">-handoff\"</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">HANDOFF_TAG</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"gw-handoff-</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$APP_NAME</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span></span></code></pre></figure><p>By this point the new build is already on disk next to the running app. The deploy starts it a second time as <code>myapp-handoff</code> on port 23000, with <code>autorestart: false</code> so pm2 won’t try to keep it alive past its job:</p>\n<figure class=\"code\" data-lang=\"javascript\"><figcaption><span class=\"file\">handoff.config.cjs</span><span class=\"lang\">JavaScript</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">module</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">.</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">exports</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> =</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> { apps: [{</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">  name: </span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"myapp-handoff\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">  script: </span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"./scripts/start-with-port-clear.sh\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">  exec_mode: </span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"fork\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">  autorestart: </span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">false</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">,</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">  env: { NODE_ENV: </span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"production\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">, PORT: </span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"23000\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> },</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">}] };</span></span></code></pre></figure><p>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:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">for</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> i </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">in</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> $(</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">seq</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 1</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 60</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">); </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">do</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">  c</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$(</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">curl</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -s</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -o</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> /dev/null</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -m</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 5</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -w</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> '%{http_code}'</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> http://127.0.0.1:23000/</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> ||</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> true</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">)</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">  [ </span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$c</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> !=</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 000</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> ] &#x26;&#x26; </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">break</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">  sleep</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 1</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">done</span></span></code></pre></figure><p>Once it answers, this is the whole trick, once for IPv4 and once for IPv6:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">sudo</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> iptables</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -t</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> nat</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -I</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> OUTPUT</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -d</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> 127.0.0.1/32</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -p</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> tcp</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --dport</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 3000</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  -m</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> owner</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --uid-owner</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> www-data</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  -m</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> comment</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --comment</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> gw-handoff-myapp</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  -j</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> REDIRECT</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --to-ports</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 23000</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">sudo</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> ip6tables</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -t</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> nat</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -I</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> OUTPUT</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -d</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> ::1/128</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -p</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> tcp</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --dport</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 3000</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  -m</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> owner</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --uid-owner</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> www-data</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  -m</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> comment</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --comment</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> gw-handoff-myapp</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  -j</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> REDIRECT</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --to-ports</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 23000</span></span></code></pre></figure><p>From 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: <code>pm2 delete myapp</code>, <code>pm2 start ecosystem.config.cjs</code>, <code>pm2 save</code>. 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 <code>myapp-handoff</code>.</p>\n<h2 id=\"what-a-deploy-looks-like\" data-level=\"3\">What A Deploy Looks Like</h2>\n<p>Here’s that part of a real deploy log, trimmed, with the app renamed to match:</p>\n<figure class=\"code\" data-lang=\"text\"><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span>    Starting handoff copy of the new build on :23000...</span></span>\n<span class=\"line\"><span>    nginx -> :3000 now goes to the handoff; restarting the app.</span></span>\n<span class=\"line\"><span>[PM2] Applying action deleteProcessId on app [myapp](ids: [ 4 ])</span></span>\n<span class=\"line\"><span>[PM2] [myapp](4) ✓</span></span>\n<span class=\"line\"><span>│ 5  │ myapp-handoff    │ fork │ 2551525 │ 7s  │ online │ 136.9mb │</span></span>\n<span class=\"line\"><span>[PM2][WARN] Applications myapp not running, starting...</span></span>\n<span class=\"line\"><span>[PM2] App [myapp] launched (1 instances)</span></span>\n<span class=\"line\"><span>│ 6  │ myapp            │ fork │ 2551779 │ 0s  │ online │ 3.3mb   │</span></span>\n<span class=\"line\"><span>│ 5  │ myapp-handoff    │ fork │ 2551525 │ 7s  │ online │ 136.9mb │</span></span>\n<span class=\"line\"><span>[PM2] Saving current process list...</span></span>\n<span class=\"line\"><span>    App answering on :3000 again; draining the handoff.</span></span></code></pre></figure><p>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 <code>myapp</code> 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.</p>\n<h2 id=\"the-start-wrapper\" data-level=\"3\">The Start Wrapper</h2>\n<p>Both copies start through the same small script, <code>start-with-port-clear.sh</code>, which is why the handoff only needs a different <code>PORT</code>:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"file\">scripts/start-with-port-clear.sh</span><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#6A737D;--shiki-dark:#6A737D\">#!/usr/bin/env bash</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">set</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -e</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">PORT</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"${</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">PORT</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">:-</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">3000</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">}\"</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">HOLDER</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$(</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">ss</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -tlnp</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> 2></span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">/dev/null</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> |</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\"> awk</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -v</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> p=\":</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$PORT</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">\\$</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">0 ~ p\"</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> |</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\"> grep</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -oE</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"pid=[0-9]+\"</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> |</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\"> cut</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -d=</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -f2</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> |</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\"> head</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -1</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">)</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">if</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> [ </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">-n</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$HOLDER</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> ] &#x26;&#x26; [ </span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$HOLDER</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> !=</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">$$</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> ]; </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">then</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  echo</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"[start] killing orphan holder pid </span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$HOLDER</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> on port </span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$PORT</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">  kill</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -9</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$HOLDER</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> 2></span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">/dev/null</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> ||</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> true</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">  sleep</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 1</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">fi</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">exec</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> node</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> node_modules/next/dist/bin/next</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> start</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -p</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$PORT</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span></span></code></pre></figure><p><code>next start</code> 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 <code>treekill: true</code> 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.</p>\n<h2 id=\"why-output-and-not-prerouting\" data-level=\"3\">Why OUTPUT And Not PREROUTING</h2>\n<p>Most iptables port-forwarding examples put REDIRECT in <code>PREROUTING</code>, which handles packets as they arrive on an interface. nginx and the app are on the same machine, so nginx’s connection to <code>127.0.0.1:3000</code> is a locally generated packet that never comes in from anywhere. The <a href=\"https://ipset.netfilter.org/iptables.man.html\">iptables man page</a> describes the <code>nat</code> table’s <code>OUTPUT</code> chain as being “for altering locally-generated packets before routing,” and that’s the only place these packets pass.</p>\n<p>The <a href=\"https://ipset.netfilter.org/iptables-extensions.man.html\">REDIRECT target</a> is allowed in exactly those two chains, and for <code>OUTPUT</code> it maps the destination to “127.0.0.1 for IPv4 and ::1 for IPv6,” which is where the handoff is listening anyway.</p>\n<h2 id=\"why-only-www-data\" data-level=\"3\">Why Only www-data</h2>\n<p>The <code>owner</code> match is what makes this safe to leave running for a minute. <code>--uid-owner www-data</code> 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 <code>OUTPUT</code>.</p>\n<p>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 <code>127.0.0.1:3000</code> 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.</p>\n<p>The <code>comment</code> match does nothing to the traffic. It tags the rule so the script can find and delete it later without tracking rule numbers.</p>\n<h2 id=\"why-open-connections-dont-move\" data-level=\"3\">Why Open Connections Don’t Move</h2>\n<p>The <code>nat</code> 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:</p>\n<ul>\n<li>When the rule goes in, connections already open to the old process stay on the old process.</li>\n<li>When the rule comes out, connections already open to the handoff stay on the handoff until they’re done.</li>\n</ul>\n<p>The 2-second and 5-second sleeps are there for exactly those leftover connections.</p>\n<h2 id=\"why-a-localhost-upstream-makes-the-gap-worse\" data-level=\"3\">Why A localhost Upstream Makes The Gap Worse</h2>\n<p>On vhosts that use <code>proxy_pass http://localhost:3000</code>, a plain restart cost about 8 seconds of 502s instead of 1 or 2. The <a href=\"https://nginx.org/en/docs/http/ngx_http_proxy_module.html\">proxy_pass docs</a> explain why: “If a domain name resolves to several addresses, all of them will be used in a round-robin fashion.” On my server <code>localhost</code> resolves to both <code>::1</code> and <code>127.0.0.1</code>, so nginx quietly builds a group of two servers.</p>\n<p>The <a href=\"https://nginx.org/en/docs/http/ngx_http_upstream_module.html\">upstream module docs</a> say a server is marked unavailable after <code>max_fails</code> failed attempts within <code>fail_timeout</code>, and stays that way for <code>fail_timeout</code>. 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.</p>\n<p>A plain <code>127.0.0.1</code> 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 <code>localhost</code> to <code>127.0.0.1</code> in your vhost still gets you back from 8 seconds to 1 or 2.</p>\n<h2 id=\"cleaning-up-after-a-bad-deploy\" data-level=\"3\">Cleaning Up After A Bad Deploy</h2>\n<p>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 <code>trap handoff_cleanup EXIT</code> while the handoff is live, and the first thing every deploy does is delete any rule carrying this app’s tag:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">for</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> t </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">in</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> iptables</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> ip6tables</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">; </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">do</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">  sudo</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> $t </span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">-t</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> nat</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -S</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> OUTPUT</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">    |</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\"> grep</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> --</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> '--comment gw-handoff-myapp '</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">    |</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\"> sed</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> 's/^-A/-D/'</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> \\</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">    |</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> while</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> read</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -r</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> r</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">; </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">do</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> eval</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> sudo</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> $t </span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">-t</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> nat</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> $r; </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">done</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">done</span></span></code></pre></figure><p><code>-S</code> prints each rule in the same syntax you’d use to add it, so swapping <code>-A</code> for <code>-D</code> turns the listing into delete commands. It also deletes any leftover <code>myapp-handoff</code> 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.</p>\n<h2 id=\"when-not-to-use-it\" data-level=\"3\">When Not To Use It</h2>\n<p>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 <code>.deploy-no-handoff</code> file in their project root and keep the plain restart. The handoff also starts with <code>GW_DEPLOY_HANDOFF=1</code> 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.</p>\n<h2 id=\"a-cache-that-outlives-the-restart\" data-level=\"3\">A Cache That Outlives The Restart</h2>\n<p>One more thing bit me on Next.js 16.4, and it’s about the window before the restart. Next keeps ISR and <code>notFound</code> results in <code>.next/server/route-cache</code>, 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.</p>\n<p>So the restart step empties the folder after deleting the old process and before starting the new one:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">pm2</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> delete</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> myapp</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">find</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> .next/server/route-cache</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -mindepth</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 1</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -delete</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> 2></span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">/dev/null</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> ||</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> true</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">pm2</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> start</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> ecosystem.config.cjs</span></span></code></pre></figure><p>Builds never ship a <code>route-cache</code>, so there’s nothing in there worth keeping.</p>\n<h2 id=\"testing-it\" data-level=\"3\">Testing It</h2>\n<p>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:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"file\">hammer.sh</span><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#6A737D;--shiki-dark:#6A737D\">#!/usr/bin/env bash</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6A737D;--shiki-dark:#6A737D\"># Request a URL in a loop until Ctrl-C, then count the status codes.</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">url</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">${1</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">:?</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">usage</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">:</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> hammer</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">.</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">sh</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\"> https</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">://</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">example</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">.</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">com</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">/</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">}</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">out</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">=</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$(</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">mktemp</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">)</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\">trap</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> 'sort \"$out\" | uniq -c; exit'</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> INT</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">while</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> true</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">; </span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">do</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">  curl</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -s</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -o</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> /dev/null</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -m</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> 10</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -w</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> '%{http_code}\\n'</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$url</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> >></span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> \"</span><span style=\"--shiki-light:#24292E;--shiki-dark:#E1E4E8\">$out</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\">\"</span></span>\n<span class=\"line\"><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\">done</span></span></code></pre></figure><p>A plain restart shows up as a handful of <code>502</code> lines. With the handoff, the only line should be the <code>200</code>s. <code>000</code> means curl gave up, which points at the network rather than nginx.</p>\n<p>While the rule is live, the packet counters show it working:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">sudo</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> iptables</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -t</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> nat</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -L</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> OUTPUT</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -n</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -v</span></span></code></pre></figure><p>Since the <code>nat</code> table only sees the first packet of each connection, the <code>pkts</code> column on the REDIRECT rule is the number of connections nginx sent to the handoff. And after a deploy, this should print nothing:</p>\n<figure class=\"code\" data-lang=\"bash\"><figcaption><span class=\"lang\">Shell</span></figcaption><pre class=\"shiki shiki-themes github-light github-dark\" style=\"--shiki-light:#24292e;--shiki-dark:#e1e4e8;--shiki-light-bg:#fff;--shiki-dark-bg:#24292e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\">sudo</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> iptables</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -t</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> nat</span><span style=\"--shiki-light:#005CC5;--shiki-dark:#79B8FF\"> -S</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> OUTPUT</span><span style=\"--shiki-light:#D73A49;--shiki-dark:#F97583\"> |</span><span style=\"--shiki-light:#6F42C1;--shiki-dark:#B392F0\"> grep</span><span style=\"--shiki-light:#032F62;--shiki-dark:#9ECBFF\"> gw-handoff</span></span></code></pre></figure><h2 id=\"other-ways-to-do-this\" data-level=\"3\">Other Ways To Do This</h2>\n<p>There are more standard tools for this, and I looked at each one:</p>\n<ul>\n<li><strong>pm2 cluster mode</strong> does have <code>pm2 reload</code>, which the <a href=\"https://pm2.keymetrics.io/docs/usage/cluster-mode/\">pm2 docs</a> 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.</li>\n<li><strong>systemd socket activation</strong> lets systemd hold the listening socket while the service restarts, but the app has to accept the socket from systemd (<a href=\"https://www.freedesktop.org/software/systemd/man/latest/systemd.socket.html\">systemd.socket</a>, <code>sd_listen_fds</code>), and these apps are run by pm2.</li>\n<li><strong>An nginx <code>backup</code> server</strong> 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.</li>\n<li><strong>SO_REUSEPORT</strong> lets two processes bind the same port (<a href=\"https://man7.org/linux/man-pages/man7/socket.7.html\">socket(7)</a>), 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.</li>\n</ul>\n<p>The handoff fit because it needs nothing from the app or the vhost. Any app that reads its port from <code>PORT</code> gets it for free, and the only moving part is a rule that exists for a few seconds per deploy.</p>","created_at":"2026-11-30T14:00:00.000Z","updated_at":"2026-11-30T14:00:00.000Z"}