Deploying Node.js apps

Topic 4 of 4 in Production9 min readIntermediateFree course

Overview

Your API works, has tests, logs and health checks, and is packaged in a container. The final step is getting it in front of users — reliably, repeatedly, and without drama. This lesson covers where to host, how to automate the path from git push to production, and the habits that make deploys boring (which is exactly what you want).

Where to run Node.js

Option Examples You manage Good for
Platform as a service Render, Railway, Fly.io, Heroku, DigitalOcean App Platform your code (or image) and settings most new projects and small teams
Managed containers Google Cloud Run, AWS ECS/Fargate, Azure Container Apps your image, scaling rules, networking growing apps that want cloud-native services
Kubernetes GKE, EKS, AKS a lot — cluster, manifests, upgrades many services and a platform team
Virtual machines EC2, a VPS with PM2 or systemd everything: OS, security patches, scaling full control, special requirements
Serverless functions AWS Lambda, Vercel/Netlify functions, Cloudflare Workers individual functions spiky traffic, event handlers, small APIs

For a typical Express API with Postgres and Redis, a PaaS or managed container service plus managed Postgres and Redis is the sweet spot: you deploy a container, and backups, patching and failover for the databases are someone else’s job.

Serverless needs a slightly different mindset: functions start cold, may run in many short-lived copies (so connection pooling needs a proxy such as PgBouncer or the provider’s data proxy), and long-running WebSockets or background workers usually need a different service. Edge runtimes like Cloudflare Workers support many Node APIs, but not all of them, so check compatibility for the modules you use.

The deployment pipeline

Continuous integration (CI) runs your checks on every push and pull request. Continuous delivery/deployment (CD) takes a green main branch all the way to production automatically.

A deployment pipeline: git push triggers CI which runs lint and tests, then builds a Docker image tagged with the commit, pushes it to a registry, runs database migrations as a release step, and rolls it out to production with health checks; the previous version stays available for a one-step rollback. Afterwards, watch the errors and latency dashboards.

CI with GitHub Actions

YAML
# .github/workflows/ci.yml
name: CI
on:
  push:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_USER: app
          POSTGRES_PASSWORD: app
          POSTGRES_DB: app_test
        ports: ['5432:5432']
        options: >-
          --health-cmd "pg_isready -U app"
          --health-interval 5s
          --health-retries 10
    env:
      DATABASE_URL: postgres://app:app@localhost:5432/app_test
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v5
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: node scripts/migrate.js
      - run: npm test

The service container gives the tests a real Postgres, so the integration tests from the Testing chapter run in CI exactly as they do locally. Protect main so pull requests can’t merge until this workflow passes.

Continuous deployment

Once tests pass on main, the pipeline builds an image, tags it with the commit SHA, pushes it to a registry (GitHub Container Registry, Docker Hub, ECR, Artifact Registry) and tells the platform to deploy it. Most platforms also offer a simpler route: connect the repository, and they build and deploy on every push to main — useful when you’re starting out.

Configuration and secrets

The same image runs in staging and production; only the environment differs. Set configuration in your platform’s dashboard, CLI or secrets manager (AWS Secrets Manager, Google Secret Manager, Doppler, Vault):

  • NODE_ENV=production, PORT (often provided by the platform), LOG_LEVEL,
  • DATABASE_URL, REDIS_URL,
  • JWT_SECRET, API keys, CORS_ORIGIN.

Validate them at startup (as in Environment and configuration), so a missing secret fails the deploy immediately instead of breaking at the first request. CI secrets live in your CI provider’s encrypted secrets, never in the workflow file.

Migrations during deploys

Database migrations are the riskiest part of a deploy. Two rules:

  1. Run them as a separate release step, once, before the new code receives traffic — not at app startup, where ten instances would race to migrate.
  2. Keep them backward compatible. During a rolling deploy, old and new code run at the same time against the same database. So you never rename or drop a column in one step. Use expand and contract instead:
    • Deploy 1: add the new column (nullable) and write to both.
    • Backfill existing rows.
    • Deploy 2: read from the new column.
    • Deploy 3: stop writing the old column, then drop it.

It feels slow, but each step can be rolled back safely.

Rolling out safely

  • Rolling deploys — new instances start, pass readiness, and only then do old instances receive SIGTERM and drain. Your graceful shutdown and /readyz endpoint make this seamless.
  • Blue–green — run the new version alongside the old one and switch traffic over at once; switching back is instant.
  • Canary — send a small percentage of traffic to the new version first, watch error rates, then increase.
  • Feature flags — deploy code switched off, then enable it for some users. Deploying and releasing become separate decisions.

After the deploy

A deploy isn’t done when the pipeline turns green. For the next 15 minutes, watch your dashboards: error rate, p95 latency, event-loop delay and memory. If something is wrong, roll back first, investigate second — redeploying the previous image tag is a one-step command on every platform, and it’s why you tag images with commit SHAs.

A production checklist

Before you launch, check that the API:

  • ✅ validates configuration at startup and reads secrets from the environment,
  • ✅ uses helmet, CORS restricted to known origins, rate limiting and input validation,
  • ✅ serves only HTTPS (usually terminated by the platform or load balancer — set app.set('trust proxy', 1) so Express sees the real client IP and protocol),
  • ✅ logs structured JSON with request IDs, and reports errors to an error tracker,
  • ✅ exposes /livez and /readyz, and shuts down gracefully on SIGTERM,
  • ✅ is stateless — sessions, cache and files live in shared services,
  • ✅ has automated tests running in CI, and a protected main branch,
  • ✅ uses managed, backed-up databases — and you’ve tested restoring a backup,
  • ✅ has dashboards and alerts for errors, latency and saturation,
  • ✅ can be rolled back in one step.

Where to go next

You’ve gone from running a single JavaScript file to deploying a tested, observable, production-ready API. Natural next steps:

  • TypeScript for type safety across a growing codebase.
  • Fastify or NestJS to see other approaches to structuring Node servers.
  • GraphQL or tRPC as alternatives to REST.
  • Event-driven architecture with message brokers such as Kafka or RabbitMQ.
  • Deeper observability with OpenTelemetry tracing across multiple services.

Ship something. The best way to cement this course is to deploy a real project — even a small one — and run it for a few weeks. You’ll learn more from your first production incident than from any lesson.

Exercise

A CI pipeline for the courses API

Write .github/workflows/ci.yml that runs on every push and pull request: checks out the code, sets up Node 26 with npm caching, runs npm ci, npm run lint and npm test against a Postgres 18 service container (pass DATABASE_URL as an environment variable). Add a second job, docker, that only runs on pushes to main after tests pass, and builds the Docker image tagged with the commit SHA.

YAML
name: CI
on:
  push:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    # your code here

Summary

  • Platform-as-a-service, containers, VMs and serverless trade convenience against control.
  • CI runs lint and tests on every push; CD deploys automatically when main is green.
  • Configuration and secrets come from the platform's environment settings, never from the repository.
  • Run migrations as a separate release step, and keep them backward compatible with the running code.
  • Deploy small changes often, watch the metrics afterwards, and know how to roll back in one step.