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.
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.
