Script Valley
REST API Development: Complete Course from Beginner to Production
Production and Best Practices: Logging, Monitoring, Documentation, and DeploymentLesson 6.4

Containerizing REST APIs with Docker

Docker, Dockerfile, docker-compose, containerization, environment variables in Docker, multi-stage build, .dockerignore

Containerizing REST APIs with Docker

Docker packages your REST API and all its dependencies into a portable container that runs identically in development, staging, and production. It eliminates the classic works-on-my-machine problem and is the foundation of modern cloud deployment.

DiagramDocker Multi-Stage Build and Compose Stack

IMAGE PROMPT (replace this block with your generated image):

Flat two-section diagram on white background. Title: Docker Setup for REST APIs. Top section: Multi-Stage Dockerfile Build. Three boxes in a row connected by right arrows. Box 1: Stage 1 — Builder (node:20-alpine). Contains: npm ci, devDependencies, build tools. Arrow labeled COPY node_modules only. Box 2: Stage 2 — Production (node:20-alpine). Contains: No devDependencies, Non-root user appuser, PORT 3000 exposed, HEALTHCHECK configured. Box 3: Final Docker Image — small size badge e.g. ~120MB. Blue arrow from box 1 to 2 labeled Multi-stage = smaller image. Bottom section: docker-compose Stack. Three service boxes arranged in a triangle connected by arrows. Box 1: API Service (fill #3A5EFF, white text) — port 3000:3000, depends_on mongo and redis, .env volume. Box 2: MongoDB Service (dark fill) — port 27017, mongo_data volume. Box 3: Redis Service (red fill) — port 6379. Arrows between services showing API depends on both MongoDB and Redis. Command badge: docker-compose up. White background, clean layout.

Writing a Production Dockerfile

FROM node:20-alpine AS builder

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:20-alpine

RUN addgroup -S appgroup && adduser -S appuser -G appgroup

WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY src ./src
COPY package.json ./

USER appuser
EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=3s \
  CMD wget -qO- http://localhost:3000/health || exit 1

CMD ["node", "src/index.js"]

Docker Compose for Development

version: '3.8'
services:
  api:
    build: .
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=development
      - MONGODB_URI=mongodb://mongo:27017/myapi
    depends_on:
      - mongo
      - redis

  mongo:
    image: mongo:7
    volumes:
      - mongo_data:/data/db

  redis:
    image: redis:7-alpine

volumes:
  mongo_data:

docker-compose up starts your entire stack — API, MongoDB, and Redis — with one command. Volume mounts ensure code changes are reflected without rebuilding the image during development.

Up next

CI/CD, Health Checks, and Production Readiness Checklist

Sign in to track progress