Production deployment
Eighteenth and final chapter of the "Fastify with TypeScript" series. Let's close the loop: graceful shutdown, health checks for your orchestrator, a production-ready Dockerfile, and a look back at the principles the whole series has been following.
Graceful shutdown
When Kubernetes (or docker stop, or a Ctrl-C) sends SIGTERM, you want to stop accepting new connections, let the requests in flight finish, close the database pool, and only then exit. close-with-grace wires the signals to app.close(), and forcibly exits if that takes too long:
npm install close-with-grace
Replace src/server.ts with:
// src/server.ts
import closeWithGrace from 'close-with-grace';
import { buildApp } from './app.ts';
const app = buildApp();
closeWithGrace({ delay: 10_000 }, async ({ signal, err }) => {
if (err) {
app.log.error({ err }, 'Shutting down due to an error');
} else {
app.log.info({ signal }, 'Shutting down gracefully');
}
await app.close();
});
try {
await app.listen({ port: app.config.PORT, host: '0.0.0.0' });
} catch (err) {
app.log.error(err);
process.exit(1);
}
app.close() runs every onClose hook, including the one @fastify/postgres registered to drain the pool (chapter 9). The same handler also runs on uncaughtException and unhandledRejection, with the error in err: after an error nobody caught, the state of the process can't be trusted, so we log it, close cleanly and let the orchestrator start a fresh instance.
Start the server with npm start and stop it with Ctrl-C. The last line of the log is:
{"level":30,"time":1795538924827,"pid":3195,"hostname":"vm","signal":"SIGINT","msg":"Shutting down gracefully"}
Liveness vs readiness
Orchestrators ask two different questions. Is the process alive? If not, restart it. Can it serve traffic right now? If not, stop sending it requests, but leave it running. /health has answered the first question since chapter 4. Add the second one in src/app.ts, between /health and /health/metrics:
// Readiness: can this instance serve traffic right now? Not if it can't reach the database
// (and not when it is under pressure: this route is not exempt, so it answers 503 then)
app.get('/health/ready', { schema: { hide: true } }, async (request, reply) => {
try {
await app.pg.query('SELECT 1');
return { status: 'ok' };
} catch {
reply.code(503);
return { status: 'degraded' };
}
});
Try the scenario it exists for. With the server running, stop the database (docker stop fastify-pg):
curl -w ' %{http_code}\n' localhost:3000/health/ready
# {"status":"degraded"} 503
curl -w ' %{http_code}\n' localhost:3000/health
# {"status":"ok"} 200
The process is alive but not ready, and the two routes say exactly that. Start the database again (docker start fastify-pg) and /health/ready goes back to 200 on its own: the pool reconnects, nobody had to restart anything. That recovery is the pool.on('error') listener from chapter 13 at work; without it, the process would have died the moment the database went away.
Keep /health free of dependencies. If it checked the database too, an outage of the database would make the orchestrator restart every instance of the API in a loop, which fixes nothing and adds a cold start to the recovery.
Add the readiness check to test/health.test.ts:
it('is ready when the database answers', { skip: !process.env.DATABASE_URL }, async (t) => {
const response = await app.inject({ url: '/health/ready' });
t.assert.equal(response.statusCode, 200);
t.assert.deepEqual(response.json(), { status: 'ok' });
});
The Dockerfile
Two stages: the first has the devDependencies and runs tsc; the second copies only the compiled output and the production dependencies. Create Dockerfile:
# ---- build stage ----
FROM node:24-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY tsconfig*.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev
# ---- runtime stage ----
FROM node:24-alpine
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=builder --chown=nodejs:nodejs /app/package.json ./
USER nodejs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s CMD wget -qO- http://127.0.0.1:3000/health || exit 1
CMD ["node", "dist/server.js"]
and .dockerignore, so that local files never end up in the image:
node_modules
dist
.env
test
Why it's structured this way:
-
node:24is an LTS line.node:26is one too, and this Dockerfile was built and run with both: to use it, change the twoFROMlines. Use only LTS versions of Node in production: they receive fixes and security patches for about three years from their release. Put the end-of-life date of the version you run in your calendar and plan the upgrade before it arrives. -
ENV NODE_ENV=productionis set for the libraries that read it. Our own code never branches on it: every difference between environments is an explicit variable such asLOG_LEVELorDATABASE_URL, so staging and production run exactly the same code paths. -
npm ciinstalls everything, becausetypescriptis a devDependency and the build needs it.npm prune --omit=devthen strips the devDependencies before the runtime stage copiesnode_modules. - The runtime image has no TypeScript, no source, no compiler: just
dist/and production dependencies. Type stripping is a development convenience; in production you ship plain JavaScript with source maps. - Running as a non-root user and a
HEALTHCHECKagainst the liveness endpoint are cheap and worth having on every image. -
CMD ["node", ...](exec form, no shell) makes Node PID 1, so it receivesSIGTERMdirectly andclose-with-gracecan do its job.
docker build -t my-fastify-app .
docker run -p 3000:3000 -e DATABASE_URL=... -e JWT_SECRET=... my-fastify-app
In Kubernetes, point the liveness probe at /health and the readiness probe at /health/ready.
Behind a proxy
If a load balancer or ingress terminates TLS in front of the app, set trustProxy: true in the Fastify options: request.ip, request.protocol and the rate limiter will then use the X-Forwarded-* headers instead of the proxy's address.
Keeping dependencies healthy
The image you ship contains your code plus everything in node_modules, and most of the lines in it were written by someone else. Three habits keep that under control:
-
Add little. This project runs TypeScript, watches files, loads
.env, runs tests and measures coverage with Node alone: nots-node,nodemon,dotenvorjest. Before adding a package, check whether Node or something you already depend on does the job. -
Check continuously.
npm auditruns in CI on every push (chapter 15), andnpm ciinstalls only what the lockfile says. - Update regularly. A tool like Dependabot or Renovate opens a pull request when a dependency has a new version; your test suite tells you whether it is safe to merge. Small, frequent updates are far easier than one large jump after two years.
The Nine Node Pillars
The choices made along this series follow the Nine Node Pillars, a set of principles for running Node.js in production that the Node.js Reference Architecture also maps to. Here is where each one shows up:
| Pillar | In this series |
|---|---|
| 1. Do not block the event loop | Native Argon2 hashing off the main thread, streaming, worker threads for CPU work (chapters 12, 17) |
| 2. Monitor Node-specific metrics and act on them | Event loop utilization and delay with @fastify/under-pressure, /health/metrics, liveness and readiness (chapters 17, 18) |
| 3. Use Node LTS versions in production |
node:24 image, engines in package.json (chapters 3, 18) |
| 4. Automate testing, code review and conformance |
node:test against a real PostgreSQL, lint, coverage, CI (chapter 15) |
| 5. Avoid dependency creep | Type stripping, --watch, --env-file and the test runner built into Node; one way to raise errors (chapters 3, 10) |
| 6. De-risk your dependencies |
npm ci, npm audit in CI, regular updates (chapters 15, 18) |
| 7. Avoid global variables, config or singletons |
buildApp() factory, state on the instance through decorators, repositories and services that receive their dependencies, no branching on NODE_ENV (chapters 4, 5, 11, 13) |
| 8. Handle errors and provide meaningful logs | Central error handler with typed errors, Pino with levels and redaction, graceful shutdown (chapters 10, 16, 18) |
| 9. Use API specifications and generate clients | OpenAPI document generated from the TypeBox schemas, typed client with openapi-typescript (chapter 7) |
Where to go from here
You now have a typed, validated, authenticated, tested and containerized Fastify API. You also have a mental model of the five building blocks that everything else is built on: the instance, plugins, hooks, decorators and schemas. Natural next steps: database migrations (postgrator, node-pg-migrate) and observability with OpenTelemetry. Thanks for following along, and happy shipping!
⬅️ Previous chapter: Performance
This article is part of the "Fastify with TypeScript" series — chapter 18 of 18.
Top comments (0)