node app.js runs fine on your laptop. Then you close the lid, and your API stops with it. Besides, localhost:3000 only opens on your own laptop, not on a friend's phone.
Deploying means moving notes-api from your laptop to a server that is on 24 hours a day and reachable by other people. A server that is always on needs a few things you never think about on a laptop:
- a process manager: a program that starts the app again when it stops,
- a reverse proxy: a front door that takes visitors and holds the HTTPS certificate (HTTPS is encrypted HTTP),
- a health check: a sign that can be checked remotely to show the app is alive,
- graceful shutdown: a way to stop the app when you switch versions, which first finishes the requests already in progress.
The deploy checklist
| # | What to check | Why |
|---|---|---|
| 1 | NODE_ENV=production |
Express hides stack traces, npm skips devDependencies |
| 2 | PORT and secrets from the environment |
The server sets the values, the code doesn't hold them |
| 3 | A process manager (PM2 or systemd) or Docker | Starts the app again after a crash and after a reboot (the server restarting) |
| 4 | A reverse proxy (Nginx) with HTTPS | Takes ports 80/443, forwards to port 3000 |
| 5 | GET /health |
Load balancers and monitors know the app is alive |
| 6 | Graceful shutdown on SIGTERM and SIGINT |
A request in progress isn't cut off during a deploy |
| 7 | Logs to stdout | Collected by systemd, PM2 or Docker |
You already did numbers 1 and 2 in the Environment & Config lesson. The rest is below.
GET /health: a sign the server is alive
This route answers that the app is alive, with how long it has been running:
app.get("/health", (req, res) => {
res.json({ status: "ok", uptime: Math.round(process.uptime()) });
});
From anywhere, you can check the result with curl:
$ curl -s https://notes.example.com/health
{"status":"ok","uptime":125}
process.uptime() is how many seconds this process has been running. A load balancer (it divides requests among several servers), Docker or a monitoring service (a service that watches servers) calls this endpoint every few seconds. A 200 answer with "status":"ok" means healthy. If there is no answer or an error, the app needs to be replaced or restarted.
Graceful shutdown: finish first, then close
During a deploy, the process manager stops the old process with a signal, a message from the operating system to a process. SIGTERM is sent by systemd, Docker and Kubernetes. SIGINT is sent by PM2 and by Ctrl+C. Without a handler for that signal (a function that runs when the signal arrives), Node exits right away, and the request in progress is cut off with it. So keep the server that app.listen returns, then add the handler:
const server = app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
function shutdown(signal) {
console.log(`Received signal ${signal}...`);
console.log("Closing the HTTP server...");
server.close(async () => {
console.log("Closing the database connection...");
await db.end(); // the pool from the Database Connection lesson
console.log("Server shut down cleanly");
process.exit(0);
});
setTimeout(() => {
console.error("Requests still open after 10 seconds, forcing exit");
process.exit(1);
}, 10_000).unref();
}
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown)installs a handler. Once there is a handler, Node no longer exits by itself: your code decides when to exit.server.close(callback)stops taking new connections, waits for the requests in progress to finish, then calls its callback.- The database is closed inside the callback, after the last request is done, because that request may still need the database.
setTimeout(...).unref()is a deadline: if a request isn't done within 10 seconds, the program exits by force.unref()means this timer doesn't hold the process: when there is no other work, the process may end before the 10 seconds have passed.
This is the order of events during a deploy, with a POST /notes that takes 800 ms:
| Time | What happens |
|---|---|
| 0 ms | POST /notes arrives |
| 100 ms | systemd sends SIGTERM: Received signal SIGTERM... and Closing the HTTP server... are printed |
| 800 ms | POST /notes finishes, the client gets a 201 {"id":3,"title":"Workout","content":"run 5 km"} |
| 800 ms | the callback runs: Closing the database connection..., Server shut down cleanly, exit with exit code 0 |
Without a handler, the process stops right away at 100 ms, and the client gets curl: (52) Empty reply from server. The answer is empty, so the client can't tell whether the note was saved.
Process manager: PM2 or systemd
node app.js started over SSH (a way to open a server's terminal remotely) stops as soon as that terminal is closed. After a crash or a reboot, nothing starts it again. Pick one process manager:
PM2, which you met in the Clustering lesson, is set up in the file ecosystem.config.js:
// ecosystem.config.js
module.exports = {
apps: [{
name: "notes-api",
script: "app.js",
instances: "max",
exec_mode: "cluster",
kill_timeout: 10000, // wait 10 seconds before SIGKILL (the default is 1,600 ms)
env_production: { NODE_ENV: "production", PORT: 3000 },
}],
};
kill_timeout is how long PM2 waits before it sends SIGKILL, a signal that ends a process with no way to refuse it. The PM2 commands you use:
pm2 start ecosystem.config.js --env productionstarts the app with the values fromenv_production.pm2 reload notes-apiis used to deploy.pm2 saveand thenpm2 startupmake the app come back after a reboot.
systemd, built into Linux, is set up in a unit file (the settings file of a service) at /etc/systemd/system/notes-api.service:
[Unit]
Description=notes-api
After=network.target
[Service]
User=budi
WorkingDirectory=/home/budi/notes-api
ExecStart=/usr/bin/node app.js
Environment=NODE_ENV=production
Environment=PORT=3000
EnvironmentFile=/etc/notes-api.env
Restart=on-failure
[Install]
WantedBy=multi-user.target
sudo systemctl enable --now notes-api starts the app now and every time the server starts (sudo runs a command as the admin). sudo systemctl restart notes-api is used to deploy. Restart=on-failure starts the app again when it stops because of an error. EnvironmentFile points to a file of secrets such as JWT_SECRET. Restrict that file's permissions with chmod 600, so only root (the server's admin) can read it. This is what systemctl status notes-api shows (trimmed, example numbers):
● notes-api.service - notes-api
Loaded: loaded (/etc/systemd/system/notes-api.service; enabled; preset: enabled)
Active: active (running) since Fri 2026-10-09 03:00:00 UTC; 2min 5s ago
Main PID: 5120 (node)
CGroup: /system.slice/notes-api.service
└─5120 /usr/bin/node app.js
Oct 09 03:00:00 vps systemd[1]: Started notes-api.service - notes-api.
Oct 09 03:00:00 vps node[5120]: Server running at http://localhost:3000
A reverse proxy with HTTPS
Node runs on port 3000 as an ordinary user. In front of it, Nginx (a web server program) takes ports 80 and 443. Nginx holds the HTTPS certificate (for example from Let's Encrypt through certbot), then forwards requests to 127.0.0.1:3000, which is Node on the same machine:
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
Requests to Node now come from Nginx, so req.ip holds 127.0.0.1. Add app.set("trust proxy", 1) to Express so req.ip holds the visitor's address, which Nginx sends in the X-Forwarded-For header. This matters for rate limiting. When the app is down, Nginx answers 502 Bad Gateway.
Logs to stdout
Plain console.log (or a JSON logger such as pino) to stdout, the program's standard output, is enough. The process manager collects it: journalctl -u notes-api -f for systemd, pm2 logs for PM2, docker logs for Docker. An app that writes its own log files fills the disk sooner or later.
📌 If you use Docker
This is a Dockerfile, the recipe for building a container that holds notes-api:
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
USER node
EXPOSE 3000
CMD ["node", "app.js"]
--omit=dev skips the devDependencies, and replaces the outdated --only=production. CMD runs node directly, not npm start, so the SIGTERM from docker stop reaches Node. In a container, Node is process number 1. Without a handler, process number 1 ignores SIGTERM, so docker stop waits 10 seconds, then sends SIGKILL.
Other options, where the app runs:
| Place | When to pick it |
|---|---|
| VPS (a rented server) | Full control: you install Node, the process manager and Nginx yourself. This lesson uses a VPS because you see every part. |
| PaaS: Render, Railway, Fly.io or Heroku | The fastest first deploy: push your code, and HTTPS, restarts and logs are handled. Files the app writes to disk are lost on every new deploy, unless they are kept on an extra disk (a volume). |
| Serverless: Vercel Functions or Cloudflare Workers | No server to maintain, and the cost follows the number of requests. Code runs per request, so anything that needs a process that stays on (setInterval, a plain WebSocket server, files on disk) needs another way. |
On a VPS, Caddy can replace Nginx. Caddy gets and renews its HTTPS certificates by itself, without certbot.
In the exercise: a health check and the shutdown order
The starter's healthCheck() already returns the object { status: "ok", version: "1.0.0", environment: "production" }, and the caller prints it with JSON.stringify. gracefulShutdown() already prints three lines. In the exercise, you:
- swap its two middle lines, so the HTTP server is closed before the database. This order is graded, because it is the right order.
- add
console.log("Server shut down cleanly");as the last line inside that function, because the simulator calls that function once more.
⚠️ Deploys that cut requests or lose the app
process.exit()right afterserver.close(), outside its callback. The process exits before the requests finish. The result is the same as having no handler.- Closing the database before the server. A request still in progress fails halfway through a query.
- Handling only
SIGTERM. PM2 and Ctrl+C sendSIGINT. PM2 also only waits 1.6 seconds beforeSIGKILL, unlesskill_timeoutis raised. node app.jsover SSH, or forgettingpm2 saveandpm2 startup. The terminal closes or the server reboots, and the app stops and does not start again.
TL;DR: Deploying means moving the app to a server that is on 24 hours a day. Before deploying, check seven things: NODE_ENV=production, PORT and secrets from the environment, a process manager that starts the app again (PM2 with ecosystem.config.js, or a systemd unit with Restart=on-failure), Nginx (a web server) with HTTPS in front of port 3000, a GET /health that answers {"status":"ok"}, graceful shutdown, and logs to stdout (standard output). Graceful shutdown means finishing the requests in progress before the process stops: when a stop signal comes from the operating system, process.on("SIGTERM") and process.on("SIGINT") call server.close(), which stops taking new connections and waits for the requests in progress. Only in its callback is the database closed and process.exit(0) called. Without a handler, the request in progress gets Empty reply from server.
⚡ GET /health: a sign the server is alive
Write:
app.get("/health", (req, res) => {
res.json({ status: "ok", uptime: Math.round(process.uptime()) });
});
Guess first: a load balancer (it divides requests among several servers) calls this endpoint every few seconds. What for?
For a health check: checking remotely that the app is alive. A 200 answer with "status":"ok" means healthy. If there is no answer, or an error, the app needs to be replaced or restarted.
Meaning: process.uptime() is how many seconds this process has been running. A load balancer, Docker or a monitoring service (a service that watches servers) calls this endpoint.
⚡ Finish first, then close
Write:
function shutdown(signal) {
server.close(async () => {
await db.end();
process.exit(0);
});
}
process.on("SIGTERM", shutdown);
Meaning: During a deploy, the old process is stopped with the SIGTERM signal, a message from the operating system. process.on installs shutdown as its handler. server is the server that app.listen returns. server.close stops taking new connections and waits for the requests in progress to finish. The database (db) is closed inside its callback, after the last request is done, then process.exit(0) ends the process.
⚡ Something has to start it again
Meaning: node app.js started over SSH (a server's terminal, opened remotely) stops as soon as the terminal closes. After a crash or a reboot (the server restarting), nothing starts it again. Use a process manager, a program that starts the app again when it stops: PM2 or systemd.