Deploying Node applications
Getting a Node service into production with PM2, systemd, Docker and serverless, and handling SIGTERM for graceful shutdown so deploys do not drop requests.
The process objectThe cluster module and multi-core scalingHandling uncaught errors and rejectionsLogging in Node with Pino
Deploying Node applications
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A Node server is one long-lived process on one thread. Something must start it, restart it when it crashes, run enough copies to use all cores, and stop it cleanly. That is what PM2, systemd, Docker and an orchestrator each provide in their own way.
- PM2 runs your app, restarts it on failure and, in cluster mode with `instances`, runs one copy per core behind a shared port. `pm2 reload` restarts workers one at a time, so there is no downtime.
- In a Dockerfile for Node: pin a current LTS base image, `npm ci --omit=dev`, copy dependencies before source for layer caching, add a `.dockerignore`, run as the `node` user, and start with `CMD ["node", "server.js"]` rather than `npm start`.
- Platforms stop a process by sending `SIGTERM`. Handle it: stop accepting connections with `server.close()`, let in-flight requests finish, close the database pool, then exit, with a hard timeout as a backstop.
- Without a handler, a deploy kills the process mid-request. I measured it: an in-flight request got an empty reply, while with a handler it completed and new connections were refused.
- Serverless runs your function per event instead of a long-lived server. It trades process management for cold starts, per-invocation limits and care with connections to a database.
What deploying a Node service needs
Running node server.js in a terminal is not a deployment. The terminal closes and the process dies. The process crashes on an unhandled error, as in handling uncaught errors and rejections, and nothing brings it back. It uses one core of an eight-core machine. And when you ship a new version, you stop the old one and drop whatever it was serving.
So a deployment needs a supervisor that starts the process, restarts it when it dies, runs the right number of copies, routes traffic to them, and stops them cleanly. The options below differ in who plays supervisor. The generic version of this problem, including reverse proxies and health checks, is in web servers, application servers and reverse proxies, containerizing a backend service and health checks and graceful shutdown. This lesson is the Node-specific part.
PM2 on a server
PM2 is a Node process manager. It starts your app, keeps it alive, collects logs, and can run it in cluster mode. A config file describes the app:
// ecosystem.config.cjs
module.exports = {
apps: [{
name: 'web',
script: './server.js',
instances: 2, // or 'max' for one per core
exec_mode: 'cluster',
wait_ready: true, // wait for process.send('ready')
listen_timeout: 5000,
kill_timeout: 5000, // grace period before SIGKILL
max_memory_restart: '300M',
env: { NODE_ENV: 'production' },
}],
};
pm2 start ecosystem.config.cjs
pm2 reload web # rolling restart, one worker at a time
pm2 logs web
pm2 save && pm2 startup # restart apps after a reboot
I ran this with PM2 7 on Node 26 (the config is .cjs because PM2 loads it as CommonJS). It started two cluster workers, and four requests to the shared port were answered by two different PIDs. pm2 reload restarted both workers and the app stayed online. Cluster mode uses Node’s own cluster module underneath, which is the subject of the cluster module and multi-core scaling. max_memory_restart is a safety net for a slow leak, not a fix for one, as discussed in memory leaks and heap snapshots.
PM2 is simple and works on a single VM. It does not give you isolation or reproducible environments, and it does not span machines.
systemd
On a Linux server you may not need PM2 at all, because the init system already supervises processes. A unit file:
# /etc/systemd/system/web.service
[Unit]
Description=Web service
After=network.target
[Service]
User=node
WorkingDirectory=/srv/web
ExecStart=/usr/bin/node server.js
Environment=NODE_ENV=production
EnvironmentFile=/etc/web.env
Restart=on-failure
KillSignal=SIGTERM
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target
systemctl enable --now web starts it and keeps it started across reboots, Restart=on-failure brings it back, and systemctl stop sends SIGTERM and waits up to TimeoutStopSec. For multiple cores, run several instances on different ports behind a reverse proxy. I could not run systemd on this macOS machine, so this unit is the standard shape, not something I tested.
Docker, and what is Node-specific
A container makes the environment reproducible and lets an orchestrator run many copies. The generic ideas are in the backend lesson linked above. What is specific to Node:
FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
- Pin a supported LTS base image. As of this writing, Node 24 and 22 are both in the LTS line, and Node 26, which I used for the examples, has also reached LTS. Use a specific tag, not
latest. - Copy
package*.jsonand runnpm cibefore copying the source. Docker caches layers, so an unchanged dependency list skips the install on later builds. Usenpm ci --omit=dev, as in securing Node dependencies and the supply chain. - Add a
.dockerignorewithnode_modules,.gitand.env, so you do not copy local modules or secrets into the image. - Run as
node, not root. - Use
CMD ["node", "server.js"], notnpm start. Thenpmwrapper becomes the main process and may not passSIGTERMon to Node, so your shutdown handler never runs and the platform eventually force-kills the process. - Pass config through the environment, not baked into the image, as in configuration and environment variables.
Docker was not installed on this machine, so the Dockerfile above is unrun. The video demonstrates the build and run flow with a real app, including the .dockerignore, loading an env file into the container, creating a Docker network and connecting to Postgres.
Graceful shutdown
Whatever supervises your process, it stops it by sending SIGTERM and, after a grace period, SIGKILL. If you do nothing, SIGTERM terminates Node immediately, and any request in flight is dropped. Handle the signal:
import http from 'node:http';
const server = http.createServer(async (req, res) => {
if (req.url === '/slow') { await new Promise((r) => setTimeout(r, 1500)); return res.end('slow done\n'); }
res.end('ok\n');
});
server.listen(3456);
let shuttingDown = false;
function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`${signal} received, draining`);
server.close((err) => process.exit(err ? 1 : 0)); // stop accepting; callback fires when all connections end
server.closeIdleConnections(); // do not wait on idle keep-alive sockets
setTimeout(() => process.exit(1), 5000).unref(); // hard backstop
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
I tested both cases. With this handler, I started a request to /slow, sent SIGTERM 0.3 seconds later, and the slow request still completed with slow done, the server logged server closed, and a new request during the drain was refused. With a bare server and no handler, the same sequence made curl fail with exit code 52, an empty reply: the request was cut off.
In real services also close the database pool and flush logs before exiting (see SQL databases and connection pools and logging with Pino), and make your readiness check start failing as soon as shutdown begins, so a load balancer stops sending traffic. Keep the process’s grace period (terminationGracePeriodSeconds, kill_timeout, TimeoutStopSec) longer than your slowest legitimate request, and the hard timer in the code a little shorter than that.
Serverless
On AWS Lambda, Cloud Functions and similar platforms, there is no server for you to manage. You export a handler, and the platform runs it per event:
export const handler = async (event) => {
return { statusCode: 200, body: JSON.stringify({ ok: true }) };
};
The platform scales instances up and down. The trade-offs are cold starts, where the first request after idle waits for the runtime to boot, limits on duration and memory, no reliable in-memory state between invocations, and a risk of opening too many database connections when many instances run at once. Create clients outside the handler so warm invocations reuse them, and put a connection pooler between functions and a relational database. I did not deploy anything to a cloud platform for this lesson.
Choosing
One VM and one team: systemd or PM2 behind a reverse proxy. Many services or many machines: containers on an orchestrator, which handles restarts, scaling and rolling deploys for you. Spiky or low traffic with little operational capacity: serverless. In all of them, the part Node needs from you is the same: handle SIGTERM, keep the process light, and log to stdout.
What the video covers
Better Stack’s 24-minute video, from August 2024, is a chaptered Docker-for-Node walkthrough: setting up a Fastify project locally, creating a Dockerfile, a .dockerignore, building and running the image, loading an env file into the container, creating a Docker network, connecting to Postgres and running the container on that network. That covers the Docker section above. It does not cover PM2, systemd, serverless or signal handling, which are carried by this lesson’s prose and tests. Its transcript was not available, so I’m describing it from its chapter list and repository description. Software Developer Diaries’ graceful shutdown video, in the “go deeper” links, covers SIGTERM handling for plain servers, Docker and Kubernetes.
Where this fits
A process you can deploy, supervise and stop cleanly is a service. The last lesson here is about packaging Node itself into something you can ship without a Node install: single executable applications and native addons.
Check yourself
Why start a container with `CMD ["node", "server.js"]` instead of `CMD ["npm", "start"]`?
With `npm start`, npm becomes the main process and may not forward `SIGTERM` to Node, so the app never gets the chance to shut down gracefully and the platform kills it after a timeout. Running `node` directly makes it the container's main process, so signals reach your handler. Also run as a non-root user and set `NODE_ENV=production`.
What are the steps of a graceful shutdown for an HTTP server, and why the timeout?
On `SIGTERM`, stop accepting new connections with `server.close()`, close idle keep-alive connections, wait for in-flight requests to finish, close shared resources such as the database pool, then call `process.exit(0)`. A timer, unreferenced so it does not keep the process alive, forces an exit if something never finishes, because the orchestrator will `SIGKILL` the process after its own grace period anyway.
What does PM2's cluster mode give you over running `node server.js` once, and what does it not give you?
It starts several worker processes, usually one per core, which share a listening port, so a CPU-bound or crashed worker does not take the service down and you use more than one core. `pm2 reload` restarts them one at a time without downtime. It does not give you isolation, resource limits or portable environments the way containers do, and it does not add machines.
Where does serverless Node get awkward compared with a long-running server?
Cold starts add latency when no instance is warm, each invocation has time and memory limits, there is no in-memory state to rely on between requests, and many concurrent invocations can each open a database connection and exhaust the server's limit. That is why pooling proxies and short-lived clients matter there.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.