Deploy a Node.js app to production

Turn a working Express app into one that starts, stops, logs and connects to PostgreSQL the way a production platform expects.

Hexagonal cream and terracotta tiles fitted together beside a potted plant

An Express app that runs on your laptop is not automatically ready for production. On a hosting platform it has to listen on the port it is given, answer a health check, shut down cleanly when a new version replaces it, and read secrets from the environment instead of a file.

This tutorial is for developers who have a Node.js app (or want to start one) and need to put it online properly. You will build a small Express API with those habits baked in, connect it to PostgreSQL through a DATABASE_URL variable, and deploy it from GitHub on Launchpad.

The code assumes Node.js 22 LTS, Express 5 and pg 8. It uses ES modules ("type": "module").

What production-ready means for a Node app

Most deployment problems come from a handful of assumptions that hold locally and fail on a server:

  • The port is not yours to choose. The platform sets PORT and routes traffic to it. Hard-coding 3000 works only by luck.
  • localhost is the wrong address. Inside a container, 127.0.0.1 is only reachable from inside that container. Listen on 0.0.0.0.
  • Something checks that you are alive. Launchpad calls a health check path and only switches traffic to a new deployment once it answers with a 2xx status.
  • Your process will be stopped. Every deploy sends the old version SIGTERM. A good app finishes in-flight requests and closes its database pool before exiting.
  • Logs go to standard output. The platform collects whatever you write to stdout and stderr. Log files inside a container disappear on the next deploy.

Step by step: build the app

  1. Create the project and install the dependencies:
Terminal
mkdir example-api && cd example-api
npm init -y
npm install express@5 helmet compression pg
  1. Edit package.json so it declares the Node version, uses ES modules and has a start script. Your dependency versions may be newer than these:
JSON
{
  "name": "example-api",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "main": "server.js",
  "engines": {
    "node": "22.x"
  },
  "scripts": {
    "start": "node server.js",
    "dev": "node --watch server.js"
  },
  "dependencies": {
    "compression": "^1.8.0",
    "express": "^5.1.0",
    "helmet": "^8.1.0",
    "pg": "^8.16.0"
  }
}
  1. Create server.js:
JavaScript
import express from 'express';
import helmet from 'helmet';
import compression from 'compression';
import pg from 'pg';

const port = Number(process.env.PORT ?? 3000);
const isProduction = process.env.NODE_ENV === 'production';

const pool = process.env.DATABASE_URL
  ? new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 })
  : null;

const app = express();
app.set('trust proxy', 1); // HTTPS ends at the platform's proxy
app.use(helmet());
app.use(compression());
app.use(express.json({ limit: '1mb' }));

// One JSON line per request, written to stdout
app.use((req, res, next) => {
  const started = Date.now();
  res.on('finish', () => {
    console.log(JSON.stringify({
      method: req.method,
      path: req.path,
      status: res.statusCode,
      ms: Date.now() - started,
    }));
  });
  next();
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.get('/', (req, res) => {
  res.json({ message: 'Hello from production' });
});

app.get('/db-time', async (req, res) => {
  if (!pool) return res.status(503).json({ error: 'No database connected' });
  const { rows } = await pool.query('SELECT now() AS now');
  res.json({ now: rows[0].now });
});

app.use((req, res) => {
  res.status(404).json({ error: 'Not found' });
});

// Express 5 sends rejected promises from async routes here too
app.use((err, req, res, next) => {
  console.error(err);
  const status = err.status ?? 500;
  const message = status >= 500 && isProduction ? 'Internal server error' : err.message;
  res.status(status).json({ error: message });
});

const server = app.listen(port, '0.0.0.0', () => {
  console.log(`Listening on 0.0.0.0:${port}`);
});

function shutdown(signal) {
  console.log(`${signal} received, closing the server`);
  server.close(async () => {
    if (pool) await pool.end();
    process.exit(0);
  });
  // Give up after 10 seconds rather than hang
  setTimeout(() => process.exit(1), 10_000).unref();
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
  1. Add a .gitignore and a .env.example. Launchpad pre-fills the app's variables from .env.example, so list every key you need with no real values:
Text
# .gitignore
node_modules/
.env
Config
# .env.example
NODE_ENV=production
DATABASE_URL=
  1. Run it locally with npm run dev, open http://localhost:3000/health, then commit everything, including package-lock.json, and push to GitHub.

Why each piece is there

process.env.PORT ?? 3000 uses the platform's port in production and 3000 on your machine. Launchpad sets PORT to the port shown under the app's Networking tab.

The health route does no database work on purpose. If PostgreSQL has a brief hiccup, you want the app to report the error on the routes that need the database, not to be marked unhealthy and restarted. If you would rather block a deploy when the database is unreachable, add a SELECT 1 to a separate readiness route and point the health check at that.

Graceful shutdown matters because a new deployment replaces the old one. server.close() stops accepting new connections and waits for open requests; then the pool is closed. The 10-second timer stops a stuck connection from holding up the stop forever.

helmet sets sensible security headers and compression gzips responses. Both are optional, small and widely used. trust proxy makes req.ip and req.protocol reflect the real visitor, because HTTPS ends at the platform's proxy in front of your app.

The lockfile decides which package manager Launchpad uses. With package-lock.json committed, installs run npm ci, which installs exactly the versions you tested. With no lockfile you get npm install and whatever versions are current that day.

Step by step: deploy on Launchpad

  1. In your dashboard, open Launchpad, choose Deploy from GitHub and click Connect GitHub. Allow access to the repository.
  2. Click Step-by-step setup at the bottom of the repository list if you want to review settings first. Launchpad should show Express, Node 22, npm ci and npm run start. Set the Health check path to /health.
  3. Deploy. If you are warned that DATABASE_URL has no value, deploy anyway; step 5 fills it in. The build log streams while it runs. When the status turns Live, open the address ending in remotegeeks.online.
  4. Open the app's Variables tab and set NODE_ENV to production if it is not already there.
  5. Open the Databases tab, choose New database, pick PostgreSQL, keep Connect it to this app ticked and create it. This adds DATABASE_URL to the app.
  6. Press Redeploy now on the banner, then visit /db-time to confirm the connection.
A push builds the app, the health check passes and the new version goes live; a failed build keeps the previous version
Each deploy must pass its health check before it replaces the live version.

From now on, each push to the deployed branch redeploys automatically. If you already deployed with the defaults, change the health check later under Networking. The full walkthrough is in Deploy your first app.

Connecting to PostgreSQL safely

pg.Pool accepts the connection string as it is. Keep one pool for the whole process; creating a pool per request exhausts the database's connection limit quickly. A max of 10 is plenty for a small app.

On SSL: the DATABASE_URL Launchpad adds points at the database over your project's private network. Use the string exactly as given and don't force SSL options it doesn't ask for. If you connect to an external managed database whose provider requires SSL, follow that provider's connection string and instructions (often ?sslmode=require or an ssl option in the pool). Avoid rejectUnauthorized: false outside quick experiments, because it turns off certificate checks.

Common mistakes

  • Listening on localhost. The health check can't reach the app, and the deploy never goes live. Fix: app.listen(port, '0.0.0.0').
  • Hard-coding the port. Fix: read process.env.PORT, falling back to a local default.
  • No start script. Launchpad falls back to running your main file with node, which may not be what you meant. Fix: add "start": "node server.js".
  • Lockfile not committed. Builds pick up untested versions. Fix: commit package-lock.json (or your pnpm or Yarn lockfile).
  • Putting real secrets in .env.example. It is committed to Git. Fix: leave values blank and set them under Variables.
  • Writing uploads anywhere in the container. Most of its filesystem is rebuilt on every deploy. Fix: keep files in the app's /data folder (kept across deploys and backed up daily), the database or object storage.

Security notes

  • Keep secrets in Variables. They are stored encrypted, hidden in the dashboard and never written to logs.
  • Don't send stack traces to visitors. The error handler above shows a generic message for server errors in production.
  • Limit request bodies (express.json({ limit: '1mb' })) so one request can't use all your memory.
  • Run npm audit before releases and keep Express, pg and helmet up to date.
  • Use parameterised queries (pool.query('SELECT * FROM users WHERE id = $1', [id])), never string concatenation.

Troubleshooting

SymptomLikely causeFix
Build passes, deploy fails the health checkApp listens on the wrong port or address, or the path returns 404Listen on 0.0.0.0 and PORT; check the Health check path under Networking
Cannot use import statement outside a module"type": "module" missingAdd it to package.json, or use require
ECONNREFUSED to the databaseDATABASE_URL unset or an old valueConnect the database, then Redeploy now
self-signed certificate errorSSL forced on a connection that doesn't use it, or a provider with its own CAFollow the connection string; for external providers, use their CA certificate
Requests cut off during deploysNo SIGTERM handlerAdd the shutdown function above

When a deploy fails, the previous version keeps running, and the Deployments tab summarises the reason in plain words.

Frequently asked questions

Should I use PM2 or the cluster module?

Not inside a container on Launchpad. The platform already restarts apps that stop responding, and a process manager inside the container hides crashes from it. Run node server.js directly.

Which Node version will Launchpad use?

The one in engines.node (or .nvmrc). Without either, Node 20 is assumed, so declare it explicitly.

Do I need a Dockerfile?

No. Launchpad detects Express from package.json. If you add a Dockerfile, it takes priority and you control the build yourself. See Docker for web apps.

Can I deploy without GitHub?

Yes. Zip the project without node_modules and use Upload files; a package.json with a start script is enough. See Upload files.

Next steps

Your app now listens where it should, reports its health, logs to stdout and shuts down cleanly. That covers most of what separates a demo from a service people can rely on.

Share this articleLinkedIn (opens in a new tab)X (opens in a new tab)Facebook (opens in a new tab)
Was this article helpful?

Get new guides in your inbox.

One email a month. Unsubscribe anytime.