Deploying a Node.js App On-Prem & in the Cloud
Getting a Node.js API running on localhost:3000 takes five minutes. Running that same service reliably across an on-premises data center and a cloud cluster—without dropping active user requests during deployments or leaking secrets in .env files—takes deliberate engineering.
In this guide, you will build a production-grade Node.js service with graceful SIGTERM shutdown, structured JSON logging, and dynamic Vault/Consul-style runtime configuration, then deploy it to both an on-prem host and a cloud-simulated target to verify zero-downtime restarts.
- Why naive Node.js containers drop in-flight HTTP requests during rolling restarts and how
SIGTERMhandling fixes it. - How to emit structured JSON logs with Pino so both on-prem log shippers and cloud aggregators can index them.
- How to inject runtime secrets and dynamic config from Vault/Consul without baking credentials into Docker images.
- Hands-On Lab: Containerize a production Express API, deploy it to local/on-prem and cloud-simulated targets behind a reverse proxy, and run a live zero-downtime restart test.
1. Production Readiness: Local vs. Hybrid Reality
A single Docker image should run unmodified on your on-premises Linux server and in AWS ECS, Kubernetes, or Azure Container Apps. The secret is separating code (immutable container image) from runtime state (secrets, config, and lifecycle signals).
| Concern | Development Habit (Fragile) | Production Hybrid Standard |
|---|---|---|
| Process Shutdown | Container killed abruptly; active requests get 502 Bad Gateway |
Trap SIGTERM, fail /readyz, drain in-flight requests, exit 0 |
| Logging | Unstructured console.log("User ok") |
Structured JSON via pino to stdout with request IDs & latency |
| Secrets & Config | Hardcoded .env file committed or baked into image |
Mounted Vault Agent secret files + Consul KV / environment injection |
| Container PID 1 | CMD ["npm", "start"] (swallows SIGTERM) |
CMD ["node", "server.js"] as non-root user |
2. Architecture: Zero-Downtime Rolling Restart & Dynamic Secrets
Watch how traffic shifts during a deployment. When the orchestrator sends SIGTERM to the old Node.js instance, the app immediately marks itself unready, stops accepting new connections, finishes active requests, and exits cleanly while the new instance serves live traffic using secrets synced from Vault/Consul.
Graceful SIGTERM Drain & Dynamic Vault/Consul Runtime Flow
During a rolling restart, the reverse proxy stops sending new traffic to v1 as soon as SIGTERM flips /readyz to 503, allowing v1 to drain active requests while v2 handles incoming traffic seamlessly.
3. Hands-On Lab: Containerize & Test Zero-Downtime Restarts
In this lab, you will build a Node.js Express API with Pino structured logging, Vault/Consul file-based runtime secret loading, and graceful SIGTERM shutdown. You will then deploy it simultaneously to a local/on-prem container and a cloud-simulated container behind Nginx, and verify zero-downtime restarts under live traffic.
Project folder structure
node-hybrid-lab/
├── package.json
├── server.js
├── Dockerfile
├── nginx.conf
├── docker-compose.yml
├── runtime-config/
│ ├── vault-secrets.json # Simulates Vault Agent rendered secret file
│ └── consul-config.json # Simulates Consul Template dynamic config
└── test-zero-downtime.sh # Live traffic + SIGTERM restart verifier
Step 1: Initialize package.json
File: package.json
{
"name": "upgradix-node-hybrid",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.19.2",
"pino": "^9.4.0",
"pino-http": "^10.3.0"
}
}
Step 2: Build the production server with graceful SIGTERM
Notice three production patterns in server.js: dynamic secret/config loading from mounted Vault/Consul files, separate /healthz (liveness) and /readyz (readiness) endpoints, and an orderly shutdown handler that drains active requests before exiting.
File: server.js
const fs = require("fs");
const express = require("express");
const pino = require("pino");
const pinoHttp = require("pino-http");
const PORT = process.env.PORT || 3000;
const DEPLOY_TARGET = process.env.DEPLOY_TARGET || "onprem-local";
const VAULT_SECRET_PATH = process.env.VAULT_SECRET_PATH || "/run/secrets/vault-secrets.json";
const CONSUL_CONFIG_PATH = process.env.CONSUL_CONFIG_PATH || "/etc/consul/consul-config.json";
const logger = pino({
level: process.env.LOG_LEVEL || "info",
base: { service: "upgradix-api", target: DEPLOY_TARGET }
});
// Read runtime secrets & config dynamically (Vault Agent / Consul Template pattern)
function loadJsonSafe(filePath, fallback) {
try {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch (err) {
logger.warn({ filePath, err: err.message }, "Using fallback config");
return fallback;
}
}
let isShuttingDown = false;
const app = express();
app.use(pinoHttp({ logger }));
// Liveness probe: is the Node process alive?
app.get("/healthz", (req, res) => {
res.status(200).json({ status: "alive", target: DEPLOY_TARGET });
});
// Readiness probe: should the load balancer send new traffic?
app.get("/readyz", (req, res) => {
if (isShuttingDown) {
return res.status(503).json({ status: "draining", target: DEPLOY_TARGET });
}
res.status(200).json({ status: "ready", target: DEPLOY_TARGET });
});
// Simulated work endpoint (takes 400ms to prove in-flight draining works)
app.get("/api/order", (req, res) => {
const secrets = loadJsonSafe(VAULT_SECRET_PATH, { apiKeyVersion: "local-dev" });
const config = loadJsonSafe(CONSUL_CONFIG_PATH, { region: "local-dc", maintenanceMode: false });
setTimeout(() => {
res.json({
message: "Order processed",
target: DEPLOY_TARGET,
region: config.region,
secretVersion: secrets.apiKeyVersion,
timestamp: new Date().toISOString()
});
}, 400);
});
const server = app.listen(PORT, () => {
logger.info({ port: PORT }, "Node.js service started");
});
// Graceful SIGTERM / SIGINT Shutdown Handler
function shutdown(signal) {
if (isShuttingDown) return;
isShuttingDown = true;
logger.info({ signal }, "Shutdown signal received. Marking unready and draining connections...");
// Stop accepting new connections; finish all in-flight requests
server.close((err) => {
if (err) {
logger.error({ err }, "Error during server close");
process.exit(1);
}
logger.info("All in-flight requests drained cleanly. Exiting 0.");
process.exit(0);
});
// Safety timeout if a client hangs forever
setTimeout(() => {
logger.error("Forced shutdown after 10s grace period");
process.exit(1);
}, 10000).unref();
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
Step 3: Create the production Dockerfile
File: Dockerfile
FROM node:20-alpine
WORKDIR /app
# Install production dependencies first for layer caching
COPY package*.json ./
RUN npm install --omit=dev
COPY server.js ./
# Run as non-root user for security
USER node
EXPOSE 3000
# Run node directly as PID 1 so SIGTERM is delivered immediately
CMD ["node", "server.js"]
CMD ["npm", "start"] in production Dockerfiles. npm often swallows SIGTERM signals instead of forwarding them to Node.js, causing Docker or Kubernetes to wait 10–30 seconds and then hard-kill your app with SIGKILL.Step 4: Add Vault/Consul runtime files, Nginx, and Docker Compose
Create the simulated Vault secret and Consul config files inside runtime-config/:
File: runtime-config/vault-secrets.json
{
"apiKeyVersion": "vault-v2026-11",
"dbPasswordRef": "dynamic-lease-9821"
}
File: runtime-config/consul-config.json
{
"region": "hybrid-primary",
"maintenanceMode": false
}
File: nginx.conf
events {}
http {
upstream node_hybrid_pool {
server app_onprem:3000 max_fails=1 fail_timeout=5s;
server app_cloud:3000 max_fails=1 fail_timeout=5s;
}
server {
listen 8080;
location / {
proxy_pass http://node_hybrid_pool;
proxy_next_upstream error timeout http_502 http_503;
}
}
}
File: docker-compose.yml
services:
app_onprem:
build: .
environment:
- DEPLOY_TARGET=onprem-host-01
volumes:
- ./runtime-config/vault-secrets.json:/run/secrets/vault-secrets.json:ro
- ./runtime-config/consul-config.json:/etc/consul/consul-config.json:ro
stop_grace_period: 12s
app_cloud:
build: .
environment:
- DEPLOY_TARGET=cloud-sim-us-east
volumes:
- ./runtime-config/vault-secrets.json:/run/secrets/vault-secrets.json:ro
- ./runtime-config/consul-config.json:/etc/consul/consul-config.json:ro
stop_grace_period: 12s
proxy:
image: nginx:alpine
ports:
- "8080:8080"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- app_onprem
- app_cloud
Step 5: Deploy and test zero-downtime restarts
Start the stack, then run test-zero-downtime.sh to fire continuous requests while sending SIGTERM to restart the on-prem instance.
Start the hybrid stack
docker compose up -d --build
File: test-zero-downtime.sh
#!/usr/bin/env bash
set -euo pipefail
FAILED=0
TOTAL=20
echo "Triggering graceful restart of app_onprem in background..."
(sleep 1 && docker compose restart app_onprem) &
RESTART_PID=$!
for i in $(seq 1 $TOTAL); do
CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/api/order)
if [ "$CODE" != "200" ]; then
echo "Request #$i FAILED with HTTP $CODE"
FAILED=$((FAILED + 1))
else
echo "Request #$i -> HTTP 200 OK"
fi
sleep 0.3
done
wait $RESTART_PID
echo ""
echo "Summary: $((TOTAL - FAILED))/$TOTAL succeeded, $FAILED failed."
if [ "$FAILED" -eq 0 ]; then
echo "PASS: Zero-downtime restart verified!"
else
echo "FAIL: Dropped requests detected."
exit 1
fi
Run the test and inspect structured shutdown logs
chmod +x test-zero-downtime.sh
./test-zero-downtime.sh
docker compose logs --tail=6 app_onprem
Expected output
Request #1 -> HTTP 200 OK
...
Request #20 -> HTTP 200 OK
Summary: 20/20 succeeded, 0 failed.
PASS: Zero-downtime restart verified!
{"level":30,"time":1795702145102,"service":"upgradix-api","target":"onprem-host-01","signal":"SIGTERM","msg":"Shutdown signal received. Marking unready and draining connections..."}
{"level":30,"time":1795702145514,"service":"upgradix-api","target":"onprem-host-01","msg":"All in-flight requests drained cleanly. Exiting 0."}
4. Step-by-Step Execution Breakdown
app_onprem and app_cloud read vault-secrets.json and consul-config.json at runtime. Updating those files via Vault Agent or Consul Template updates the app without rebuilding the container.docker compose restart app_onprem sends SIGTERM directly to PID 1 (node server.js).server.close() stops accepting new TCP connections while allowing the 400ms in-flight /api/order requests to finish and return 200 OK.app_cloud while app_onprem restarts, resulting in zero dropped requests.5. Hands-On Practice
Edit runtime-config/vault-secrets.json and change apiKeyVersion to "vault-v2026-12" without restarting Docker. Call curl http://localhost:8080/api/order and verify the new secret version appears immediately.
Add a simulated closeDbPool() async function inside server.close() so the process only exits after both HTTP requests and database connections have closed cleanly.
When deploying behind AWS ALB or Nginx, set server.keepAliveTimeout = 65000 and server.headersTimeout = 66000 to prevent intermittent 502 Bad Gateway errors caused by Node's default 5-second keep-alive timeout.
6. Interview Questions
/healthz (liveness) and /readyz (readiness) endpoints?
Answer: A liveness probe tells the orchestrator whether to restart a deadlocked container. A readiness probe tells the load balancer whether the container can accept new traffic. During graceful shutdown, /readyz returns 503 immediately so traffic stops, while /healthz stays 200 so the orchestrator doesn't prematurely kill the container while it finishes draining.
console.log in hybrid deployments?
Answer: Structured JSON logs (via Pino or Winston) include consistent fields like level, target, reqId, and responseTime. Log collectors like Fluent Bit, Datadog, or CloudWatch parse JSON natively, making it easy to filter and alert across both on-prem and cloud clusters.
Answer: Vault Agent runs as a sidecar or host daemon, authenticates with Vault, and renders secrets to an in-memory volume (like /run/secrets/). The Node.js app simply reads the local file, keeping it decoupled from Vault's HTTP API and authentication tokens.
Conclusion
Deploying Node.js reliably across on-prem and cloud environments comes down to clean operational boundaries: handle SIGTERM properly as PID 1, emit structured JSON logs to stdout, and externalize secrets and configuration via Vault and Consul.
With this foundation in place, the exact same container image can scale from a single local Linux host to a multi-region cloud cluster with zero-downtime deployments.
Official Documentation
- Node.js Documentation – Process Signal Events (SIGTERM / SIGINT)
- Pino – Super Fast Structured JSON Logger for Node.js
- HashiCorp Vault – Vault Agent Templates
Upgradix by Shrash Studio – Learn Technology. Build Your Future.
Discussion & Comments
0No comments yet
Start the discussion above — ask a question, share a tip, or reply to a comment.