Difficulty: Intermediate
What is Docker? Explain images, containers, and how you'd containerize a Node.js application.
Docker packages applications with their dependencies into containers - lightweight, portable, isolated environments.
Key concepts: - Image: Read-only template (like a class). Built from Dockerfile. - Container: Running instance of an image (like an object). Isolated process. - Dockerfile: Instructions to build an image - Volume: Persistent storage (containers are ephemeral) - Docker Compose: Run multi-container applications
Why Docker? - 'Works on my machine' → works everywhere - Consistent dev/staging/prod environments - Easy scaling and deployment - Microservices architecture enabler
# Multi-stage build for production
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: Production
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY package*.json ./
# Don't run as root
USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]
# .dockerignore
# node_modules
# .git
# .env
# dist
Multi-stage builds reduce image size. Stage 1 has all build tools, Stage 2 only has production files. The .dockerignore prevents copying unnecessary files.
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- '3000:3000'
environment:
- DATABASE_URL=postgresql://user:pass@db:5432/mydb
- REDIS_URL=redis://cache:6379
depends_on:
- db
- cache
volumes:
- ./src:/app/src # hot reload in dev
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- '5432:5432'
cache:
image: redis:7-alpine
ports:
- '6379:6379'
volumes:
pgdata: # named volume persists data
# Commands:
# docker compose up -d # start all services
# docker compose logs -f # stream logs
# docker compose down # stop all
# docker compose down -v # stop + remove volumes
Docker Compose defines multi-container applications. Each service runs in its own container but can communicate via the internal network.
# Build and run
docker build -t myapp:1.0 .
docker run -d -p 3000:3000 --name myapp myapp:1.0
# List and manage
docker ps # running containers
docker ps -a # all containers
docker images # local images
docker logs myapp # container logs
docker exec -it myapp sh # shell into container
# Cleanup
docker stop myapp # stop container
docker rm myapp # remove container
docker rmi myapp:1.0 # remove image
docker system prune -a # remove everything unused
# Debugging
docker inspect myapp # detailed container info
docker stats # CPU/memory usage
docker logs --tail 50 myapp # last 50 log lines
These are the most commonly used Docker commands. Know them by heart for interviews and daily work.
Docker, Container, Image, Dockerfile, Docker Compose, Volume