Docker Guide

Containerize your Express.js application with Docker for consistent development and production environments.

Generate Docker Configuration

xacos make:docker

Dockerfile

The generated Dockerfile uses multi-stage builds for optimization:

FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY package*.json ./
EXPOSE 3000
CMD ["npm", "start"]

Docker Compose

Run your entire stack with one command:

version: '3.8'

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgresql://user:pass@db:5432/mydb
    depends_on:
      - db
      - redis

  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: password
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  postgres_data:

Common Commands

# Build image
docker build -t my-api .

# Run container
docker run -p 3000:3000 my-api

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f

# Stop all services
docker-compose down

Best Practices

  • Use multi-stage builds to reduce image size
  • Run as non-root user for security
  • Use .dockerignore to exclude unnecessary files
  • Leverage build cache with proper layer ordering
  • Use specific version tags instead of latest