AI Skill Library

Docker Essentials

Dockerfile best practices, multi-stage builds, compose, volumes, networks.

dockerdevops
# Docker Essentials

## Dockerfile (Node example, multi-stage)
```dockerfile
# Stage 1: deps
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev

# Stage 2: build
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 3: runtime
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/.next ./.next
COPY --from=build /app/public ./public
COPY package.json ./
EXPOSE 3000
CMD ["npm", "start"]
```

## Best practices
- Pin base image versions (e.g. `node:20-alpine`, not `latest`).
- Order layers by change frequency (deps before source).
- Use `.dockerignore` (mirror .gitignore + add node_modules, .next, .git).
- Run as non-root: `USER node`.
- One process per container; use `tini` if needed for signal handling.

## docker-compose.yml
```yaml
services:
  app:
    build: .
    ports: ['3000:3000']
    env_file: .env
    depends_on: [db]
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: pw
    volumes: ['db:/var/lib/postgresql/data']
volumes:
  db:
```

## Useful commands
- `docker build -t app .`
- `docker run -p 3000:3000 --rm app`
- `docker logs -f <id>`
- `docker compose up -d --build`
- `docker exec -it <id> sh`

API: /api/skills/docker-basics