TL;DR: Create a Node.js API with a package.json and server file, write a Dockerfile and a docker-compose.yml that builds and runs it, then run docker compose up --build to launch it. This guide walks through each file and command so you can containerize and deploy your API in minutes.
Step 1: Prepare Your Node.js API
Start with a minimal Express API. Create a project folder, run npm init -y, and install Express with npm install express. Add a server.js that listens on process.env.PORT || 3000 and exposes a simple health route. Keep your app reading the port from an environment variable so Compose can override it later. Add a start script to package.json so the container has a clear entry point.
If you want to dig deeper, check out our guide on How Remote-First Companies Are Restructuring for Global Tale.
Step 2: Write the Dockerfile
Create a Dockerfile in the project root. Use FROM node:20-alpine for a small base image. Set WORKDIR /app, copy package*.json first, and run npm ci --omit=dev so dependencies are cached in their own layer. Then copy the rest of the source, expose port 3000, and set CMD ["node", "server.js"]. Copying package files before source code is the single biggest build-speed win.
Step 3: Create docker-compose.yml
Add a docker-compose.yml with a single service named api. Set build: . so Compose builds from your Dockerfile, map "3000:3000" under ports, and define PORT=3000 under environment. Add a restart: unless-stopped policy for resilience. If your API needs a database, add a second service (for example Postgres) and reference it by service name as the hostname.
Step 4: Build and Run
From the project root, run docker compose up --build. Compose builds the image, creates the container, and streams logs to your terminal. Visit http://localhost:3000 to confirm the API responds. Use docker compose up -d to run detached, and docker compose logs -f api to tail output. Stop everything with docker compose down.
Tips for a Smooth Deployment
Add a .dockerignore containing node_modules and .git to keep build context small. Never bake secrets into the image—use an .env file referenced by Compose. Pin image tags instead of using latest for reproducible deploys. If you edit source frequently, mount it as a volume and use a dev-only command for hot reload.
FAQ
Q: Do I need a Dockerfile if I use Docker Compose?
A: Yes for custom code—Compose orchestrates containers but still needs a Dockerfile to build your Node.js image, unless you point the service at a prebuilt image.
Q: How do I connect my API to a database in Compose?
A: Add the database as a second service and use its service name as the hostname in your connection string, for example postgres://user:pass@db:5432/app.
Q: Why does my container exit immediately after starting?
A: Usually the start command is wrong or the
Leave a Reply