Docker Containerization Guide

Learn how to containerize your applications with Docker.

What is Docker?

Docker is a platform for developing, shipping, and running applications in containers. Containers package your application with all its dependencies.

Basic Dockerfile

Create a Dockerfile for a Node.js application:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Use official Node.js runtime
FROM node:18-alpine

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci --only=production

# Copy application code
COPY . .

# Expose port
EXPOSE 3000

# Set user for security
USER node

# Start application
CMD ["node", "server.js"]

Docker Compose

Orchestrate multiple containers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
version: '3.8'

services:
web:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DATABASE_URL=postgres://db:5432/myapp
depends_on:
- db
volumes:
- ./logs:/app/logs

db:
image: postgres:15-alpine
environment:
- POSTGRES_DB=myapp
- POSTGRES_USER=admin
- POSTGRES_PASSWORD=secret
volumes:
- postgres_data:/var/lib/postgresql/data

volumes:
postgres_data:

Common Docker Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Build an image
docker build -t myapp:latest .

# Run a container
docker run -d -p 3000:3000 --name myapp myapp:latest

# View running containers
docker ps

# View logs
docker logs myapp

# Execute command in container
docker exec -it myapp sh

# Stop and remove container
docker stop myapp
docker rm myapp

# Remove image
docker rmi myapp:latest

Multi-stage Builds

Optimize image size with multi-stage builds:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Production stage
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
USER node
CMD ["node", "dist/server.js"]

Best Practices

  1. Use official base images - Start with trusted images
  2. Minimize layers - Combine RUN commands when possible
  3. Use .dockerignore - Exclude unnecessary files
  4. Don’t run as root - Use USER directive
  5. Keep images small - Use alpine variants
  6. Pin versions - Specify exact image versions

Docker makes deployment consistent and reliable across environments!