Skip to content

Zero-Downtime Deployments for Node Apps With Docker Compose · Part 2 of 11 in the series

Part 2: Health Checks and Graceful Shutdown

Teach the guestbook the two things every deploy will ask of it: to say honestly whether it is ready for visitors, and to finish its open requests before it leaves.

Quest objectives

  • Know the two questions a deploy asks an app
  • Add a health check that includes the database
  • Keep the app alive when the database goes away for a moment
  • Understand the signals SIGTERM and SIGINT
  • Shut the app down so that no open request is cut off

Swapping one version of an app for another without a gap is teamwork. The server does the swapping, but it has to ask the app two things, and the app has to be able to answer:

  • "Are you ready for visitors?" The new version is asked this before anyone is sent to it. The answer is a health check. Without it, visitors would be sent to a version that has not finished starting, or that cannot work at all.

  • "Please finish what you are doing and leave." The old version is told this once the new one has taken over. Leaving properly is called a graceful shutdown. Without it, the old version would drop the requests it is in the middle of answering.

Neither needs Docker or a server. Both are a few lines in the app, and you can try them on your own computer.

A health check

A health check is an address that a program can ask. First, give the app a way to find out whether the database is there. Add this to the end of src/db.js:

src/db.js
/** The cheapest possible question: is the database there and answering? */
export async function ping() {
  await pool.query('select 1');
}

In src/app.js, import the new function by changing the second line:

src/app.js
import { addEntry, listEntries, ping } from './db.js';

And add the address itself to the end of the same file:

src/app.js
app.get('/health', async (c) => {
  try {
    await ping();
    return c.json({ status: 'ok', version });
  } catch {
    return c.json({ status: 'error', version }, 503);
  }
});

Why does it ask the database? Because "the program runs" and "the app works" are not the same thing. A guestbook that cannot reach its entries answers every visitor with an error. Such a version must not be given the visitors, so the health check asks for the one thing the app cannot do without.

The answer comes in two forms. People read the text, ok or error. Programs read the status code, the number every answer on the web starts with: 200 means all is well, and 503 means "not available right now". Start the app with npm run dev, if it is not running, and ask it:

~/projects/guestbook
$ curl --include http://localhost:3000/healthHTTP/1.1 200 OKContent-Type: application/jsonDate: Tue, 17 Nov 2026 09:08:01 GMTConnection: keep-aliveKeep-Alive: timeout=5Content-Length: 31{"status":"ok","version":"dev"}

The first line holds the status code, and the last one the text, with the version you know from the footer of the page.

When the database goes away

Now find out what the health check says when the database is gone. Leave the app running. In a second terminal, ask the health check once more and stop the database right after it, both in one line:

~/projects/guestbook
$ curl http://localhost:3000/health && docker compose stop db{"status":"ok","version":"dev"}

The request in front matters: it leaves a connection to the database waiting in the pool, and the pool closes connections that have had nothing to do for ten seconds. Look at the terminal with the app:

~/projects/guestbook
node:events:505    throw er; // Unhandled 'error' event    ^error: terminating connection due to administrator command    at parseErrorMessage (/home/robin/projects/guestbook/node_modules/pg-protocol/dist/parser.js:306:11)    at Parser.handlePacket (/home/robin/projects/guestbook/node_modules/pg-protocol/dist/parser.js:143:27)

That is not an honest "not healthy". The whole app has crashed, although only the database was stopped. The reason is the pool from part 1. It keeps a few connections to the database open, waiting for the next query. When the database shuts down, a waiting connection breaks, and it reports that as an error. Nobody listens for that error, and in Node.js an error that nobody listens for ends the program.

A database that restarts is nothing unusual, so the app has to survive it. Listen for the error: add these two lines to src/db.js, right below the line that creates the pool:

src/db.js
// A connection that breaks while it waits in the pool must not take the whole app down.
pool.on('error', (error) => console.error(`Lost a database connection: ${error.message}`));

The pool throws a broken connection away by itself and opens a new one for the next query. All that was missing was somebody who takes note. Now try again. Start the database:

~/projects/guestbook
$ docker compose start db

Start the app again with npm run dev (press Ctrl+C first if its terminal is still busy), run the line from before once more, the one that asks and then stops the database, and ask the health check again:

~/projects/guestbook
$ curl http://localhost:3000/health{"status":"error","version":"dev"}$ docker compose start db$ curl http://localhost:3000/health{"status":"ok","version":"dev"}

This time the app stayed up. Without its database it says error, with the status code 503, and a few seconds after the database is back it says ok again, without anyone restarting it. Its terminal shows what happened:

~/projects/guestbook
Guestbook listening on port 3000Lost a database connection: terminating connection due to administrator command

A graceful shutdown

The second question is about leaving. A program is asked to stop with a signal, a short message from the operating system. Two of them matter here:

  • SIGTERM means "please terminate". It is what Docker sends to a container when it stops it.

  • SIGINT means "interrupt". It is what your terminal sends when you press Ctrl+C.

A Node.js program that does not handle these signals ends on the spot. A visitor whose entry is being saved at that moment gets no answer, only a broken connection. During a deploy, the old version is stopped while visitors are on the site, so that would happen with every update.

Replace src/server.js with this:

src/server.js
import { serve } from '@hono/node-server';
import { app } from './app.js';
import { pool } from './db.js';

const port = Number(process.env.PORT ?? 3000);

const server = serve({ fetch: app.fetch, port }, () => {
  console.log(`Guestbook listening on port ${port}`);
});

/**
 * Docker stops a container with SIGTERM, and Ctrl+C in a terminal sends SIGINT. Either way:
 * take no new requests, let the open ones finish, close the database, then leave.
 */
function shutdown(signal) {
  console.log(`${signal} received, finishing open requests`);
  server.close(async () => {
    await pool.end();
    console.log('All done, bye');
    process.exit(0);
  });
  // A request that hangs must not keep the old version alive forever.
  setTimeout(() => process.exit(1), 10_000).unref();
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

The first half is what you had, except that the pool is imported and the server is now kept in a variable. The function shutdown is new, and the last two lines run it when one of the signals arrives. It does three things:

  • server.close stops the server from taking new requests. The ones that are open get answered as usual. Only when the last of them is done does the function inside run.

  • pool.end() closes the connections to the database, and then the program ends with process.exit(0). The zero means "everything went fine".

  • The setTimeout is a safety net. If a request hangs and never finishes, the program ends after ten seconds anyway, with a one for "something went wrong". unref() tells Node.js not to wait for this timer, so it does not keep the program alive by itself.

Ten seconds is not a random number. After Docker has sent SIGTERM, it waits ten seconds for the container to leave. Then it loses patience and kills it. An app that finishes within that time decides for itself how it ends.

Try it. Stop the app and start it without the restart-on-save mode, which has its own way of dealing with Ctrl+C. Then press Ctrl+C:

~/projects/guestbook
$ node --env-file=.env src/server.jsGuestbook listening on port 3000^CSIGINT received, finishing open requestsAll done, bye

The app noticed the signal, finished, and said goodbye. On your computer there was no open request to wait for, so it went quickly. On a busy server, those two lines are the difference between a visitor who gets their answer and one who gets an error.

Commit

Save the state:

~/projects/guestbook
$ git add .$ git commit --message "Health check and graceful shutdown"$ git push

What you have now

An app that can answer both questions of a deploy. It says whether it is ready, and it tells the truth about its database. And when it is asked to leave, it finishes its work first. In the next part you pack it into an image, and Docker starts asking those questions.

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.