Guide ·

How to Dockerize a Node.js API for Production: Dockerfile, MySQL and Deploys

How to run a Node.js and Express API in Docker on your own server: a small Dockerfile, secrets, health checks, graceful shutdown, MySQL, logs and rollbacks.

By Ritesh Singh, full-stack developer

Many of the backends I build are Node.js and Express APIs with MySQL, and I usually ship them as Docker containers on a VPS the client owns, deployed through Coolify with Cloudflare in front. The AEPS payments dashboard runs its separate backend service this way. Getting an API to start in Docker is quick; making it restart cleanly, keep its data and roll back safely takes more care. This guide is the setup I use.

1. Keep the image small and predictable

Start from an official Node.js image with a fixed major version, such as node:22-slim, rather than latest, so a rebuild next month does not quietly change the runtime. Use a multi-stage Dockerfile: the first stage installs all dependencies and runs the TypeScript build if there is one; the final stage copies only package.json, the lock file and the built output, then runs npm ci --omit=dev.

Copy package.json and the lock file before the rest of the code, so Docker can reuse the cached dependency layer when only your code changes. Add a .dockerignore that excludes node_modules, .git, test files, local uploads and every .env file, or secrets can end up in the image.

2. Run as a normal user and start Node directly

Containers run as root by default. The official Node.js images include a user called node, so add USER node before the start command and give that user ownership of any folder the app writes to.

Set NODE_ENV=production and start the app with CMD ["node", "dist/server.js"] rather than npm start. When npm sits in the middle, the stop signal Docker sends on every deploy may not reach your app, so it gets killed instead of shutting down. Running with Docker's --init option, or init: true in Docker Compose, adds a tiny process that passes signals on and cleans up child processes.

3. Configuration and secrets come from the environment

Build one image and run it everywhere: on a laptop, on staging and in production. Everything that differs between them, such as the database URL, JWT secret, payment gateway keys and API base URLs, comes from environment variables set in Coolify or a Compose env_file kept outside Git. Check the required variables when the app starts and exit with a clear message if one is missing.

Never bake secrets into the image with ENV or a copied .env file. Anyone who can pull the image can read every layer of it, including files deleted in a later step.

4. Health checks and graceful shutdown

Add a GET /health route that returns 200 when the app is running and can reach the database, so Docker's HEALTHCHECK, Coolify and uptime monitors can tell a running container from a working one. Slim images often have no curl, so the check can be a one-line node -e script that calls the route with fetch.

On every deploy the old container receives SIGTERM and has a few seconds before it is killed. Listen for it: stop accepting new connections with server.close(), let requests in progress finish, close the MySQL pool, then exit. Without this, a deploy can cut off a payment callback or a file upload halfway through. For anything that moves money, the bank or gateway status check still has to settle what really happened, as I explain in my bulk payout API integration guide.

5. The database lives outside the app container

Run MySQL as its own container, or as a database resource in Coolify, with its data on a named volume so it survives restarts and upgrades. The API reaches it by service name over the internal Docker network. Do not publish the database port to the internet at all.

Docker Compose starts containers in order, but a started database is not yet a ready database. Use depends_on with condition: service_healthy and a health check on MySQL, and let the API retry its first connection for a short while instead of crashing. Run schema migrations as a separate step before the new version takes traffic, not from several app containers starting at once.

6. Logs, uploads and other files

Treat the container's filesystem as temporary: it is replaced on every deploy. Write logs to stdout and stderr, not to files inside the container, so docker logs and Coolify can show them. Turn on log rotation in Docker's daemon.json (for example max-size and max-file for the json-file driver), because unrotated logs are a common reason a small VPS runs out of disk. Keep personal data, tokens and full card or bank details out of the logs.

User uploads, generated PDFs and exports go on a mounted volume or in S3-compatible object storage, never in the image.

7. Ports, proxies and real visitor IPs

Only the reverse proxy should listen on ports 80 and 443; the API container stays on the internal network. Ports published with -p bypass UFW, because Docker writes its own firewall rules, a trap I describe in my Cloudflare setup guide for a VPS. Behind Coolify's proxy and Cloudflare, set Express's trust proxy to match the proxies in front of it, so rate limits and audit logs see the visitor's IP rather than the proxy's.

8. Deploys and rollbacks

With Coolify, a push to the main branch builds the image and swaps the container, and each build is tied to a Git commit, so rolling back means redeploying the previous one. Deploying by hand with Compose? Tag images with the commit hash, not only latest. I walk through that setup, including the database and backups, in my guide to deploying Next.js and a Node.js API with Coolify.

A rollback only works if the database still fits the old code. Make migrations additive: add a column, ship code that uses it, and remove the old column in a later release. If you are moving an older PHP or Node.js app off shared hosting at the same time, my shared hosting to VPS migration guide covers the steps around the move itself.

Docker checklist for a Node.js API

  • Fixed Node.js major version and a multi-stage build with production dependencies only.
  • .dockerignore excluding node_modules, .git and every .env file.
  • App runs as the node user and is started with node, not npm start.
  • Secrets in environment variables, checked at startup, never in the image.
  • /health route and a Docker health check.
  • SIGTERM handled: stop new requests, finish current ones, close the database pool.
  • MySQL on a named volume, not published to the internet, with a readiness check.
  • Migrations run once per deploy and kept backward compatible.
  • Logs to stdout with rotation; uploads on a volume or object storage.
  • Only the proxy publishes ports; trust proxy set correctly.
  • Every deploy tied to a commit, with a tested rollback and tested backups.

Need a Node.js or PHP API built, or an existing one moved into Docker on a server you own? I build the backend and set up the deployment, so one person is responsible for both. See my VPS setup and Docker deployment service and Node.js and PHP backend development, or send a short project brief.

In practice

Case studies using this approach

Keep reading

Related guides

Related services

Hire me for this

Want this done for your product?

Start your project →