docker
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDocker Containerization Skill
Docker容器化技能
Master Docker containerization for consistent, reproducible development and production environments. This skill covers Dockerfile best practices, multi-stage builds, Docker Compose orchestration, and production-ready configurations.
掌握Docker容器化技术,打造一致、可复现的开发与生产环境。本技能涵盖Dockerfile最佳实践、多阶段构建、Docker Compose编排以及生产就绪的配置方案。
When to Use This Skill
适用场景
USE when:
适合使用的场景:
- Building reproducible development environments
- Creating consistent CI/CD pipelines
- Deploying microservices architectures
- Isolating application dependencies
- Packaging applications for distribution
- Setting up local development with multiple services
- Need portable environments across teams
- 构建可复现的开发环境
- 创建一致的CI/CD流水线
- 部署微服务架构
- 隔离应用依赖
- 打包应用用于分发
- 搭建包含多服务的本地开发环境
- 需要跨团队的可移植环境
DON'T USE when:
不适合使用的场景:
- Simple scripts that don't need isolation
- Applications that require direct hardware access
- Environments where containers aren't permitted
- Tasks better suited for virtual machines (full OS isolation)
- When simpler alternatives like venv suffice
- 无需隔离的简单脚本
- 需要直接访问硬件的应用
- 不允许使用容器的环境
- 更适合用虚拟机(完整操作系统隔离)的任务
- 使用venv等更简单方案即可满足需求的场景
Prerequisites
前置条件
Installation
安装步骤
Linux (Ubuntu/Debian):
bash
undefinedLinux(Ubuntu/Debian):
bash
undefinedInstall Docker Engine
Install Docker Engine
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
Add user to docker group
Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
sudo usermod -aG docker $USER
newgrp docker
Install Docker Compose plugin
Install Docker Compose plugin
sudo apt-get update
sudo apt-get install docker-compose-plugin
sudo apt-get update
sudo apt-get install docker-compose-plugin
Verify installation
Verify installation
docker --version
docker compose version
**macOS:**
```bashdocker --version
docker compose version
**macOS:**
```bashInstall Docker Desktop
Install Docker Desktop
brew install --cask docker
brew install --cask docker
Or download from https://www.docker.com/products/docker-desktop
Or download from https://www.docker.com/products/docker-desktop
Verify installation
Verify installation
docker --version
docker compose version
**Windows:**
```powershelldocker --version
docker compose version
**Windows:**
```powershellInstall Docker Desktop from https://www.docker.com/products/docker-desktop
Install Docker Desktop from https://www.docker.com/products/docker-desktop
Enable WSL 2 backend for best performance
Enable WSL 2 backend for best performance
Verify installation
Verify installation
docker --version
docker compose version
**Additional Tools:**
```bashdocker --version
docker compose version
**附加工具:**
```bashDockerfile linter
Dockerfile linter
brew install hadolint # macOS
brew install hadolint # macOS
Or: docker run --rm -i hadolint/hadolint < Dockerfile
Or: docker run --rm -i hadolint/hadolint < Dockerfile
Image analyzer (inspect layers)
Image analyzer (inspect layers)
brew install dive # macOS
brew install dive # macOS
Or: docker run --rm -it wagoodman/dive:latest <image>
Or: docker run --rm -it wagoodman/dive:latest <image>
Build with BuildKit (enhanced features)
Build with BuildKit (enhanced features)
export DOCKER_BUILDKIT=1
undefinedexport DOCKER_BUILDKIT=1
undefinedCore Capabilities
核心能力
1. Basic Dockerfile Patterns
1. 基础Dockerfile模式
Simple Application Dockerfile:
dockerfile
undefined简单应用Dockerfile:
dockerfile
undefinedBase image with specific version
Base image with specific version
FROM python:3.12-slim
FROM python:3.12-slim
Set working directory
Set working directory
WORKDIR /app
WORKDIR /app
Set environment variables
Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
PYTHONUNBUFFERED=1
PIP_NO_CACHE_DIR=1
PYTHONUNBUFFERED=1
PIP_NO_CACHE_DIR=1
ENV PYTHONDONTWRITEBYTECODE=1
PYTHONUNBUFFERED=1
PIP_NO_CACHE_DIR=1
PYTHONUNBUFFERED=1
PIP_NO_CACHE_DIR=1
Install system dependencies
Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
Copy dependency files first (better caching)
Copy dependency files first (better caching)
COPY requirements.txt .
COPY requirements.txt .
Install Python dependencies
Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
Copy application code
Copy application code
COPY . .
COPY . .
Create non-root user
Create non-root user
RUN useradd --create-home appuser && chown -R appuser:appuser /app
USER appuser
RUN useradd --create-home appuser && chown -R appuser:appuser /app
USER appuser
Expose port
Expose port
EXPOSE 8000
EXPOSE 8000
Health check
Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3
CMD curl -f http://localhost:8000/health || exit 1
CMD curl -f http://localhost:8000/health || exit 1
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3
CMD curl -f http://localhost:8000/health || exit 1
CMD curl -f http://localhost:8000/health || exit 1
Default command
Default command
CMD ["python", "main.py"]
**Node.js Application Dockerfile:**
```dockerfile
FROM node:20-alpine
WORKDIR /appCMD ["python", "main.py"]
**Node.js应用Dockerfile:**
```dockerfile
FROM node:20-alpine
WORKDIR /appCopy package files
Copy package files
COPY package*.json ./
COPY package*.json ./
Install dependencies
Install dependencies
RUN npm ci --only=production
RUN npm ci --only=production
Copy application
Copy application
COPY . .
COPY . .
Non-root user (alpine already has 'node' user)
Non-root user (alpine already has 'node' user)
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "server.js"]
undefinedUSER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "server.js"]
undefined2. Multi-Stage Builds
2. 多阶段构建
Python Multi-Stage Build:
dockerfile
undefinedPython多阶段构建:
dockerfile
undefinedStage 1: Build dependencies
Stage 1: Build dependencies
FROM python:3.12-slim AS builder
WORKDIR /app
FROM python:3.12-slim AS builder
WORKDIR /app
Install build dependencies
Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
Create virtual environment
Create virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
Install dependencies
Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
Stage 2: Production image
Stage 2: Production image
FROM python:3.12-slim AS production
WORKDIR /app
FROM python:3.12-slim AS production
WORKDIR /app
Install runtime dependencies only
Install runtime dependencies only
RUN apt-get update && apt-get install -y --no-install-recommends
libpq5
curl
&& rm -rf /var/lib/apt/lists/*
libpq5
curl
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends
libpq5
curl
&& rm -rf /var/lib/apt/lists/*
libpq5
curl
&& rm -rf /var/lib/apt/lists/*
Copy virtual environment from builder
Copy virtual environment from builder
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
Copy application code
Copy application code
COPY . .
COPY . .
Create non-root user
Create non-root user
RUN useradd --create-home --shell /bin/bash appuser
&& chown -R appuser:appuser /app USER appuser
&& chown -R appuser:appuser /app USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3
CMD curl -f http://localhost:8000/health || exit 1
CMD curl -f http://localhost:8000/health || exit 1
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
**Node.js Multi-Stage Build:**
```dockerfileRUN useradd --create-home --shell /bin/bash appuser
&& chown -R appuser:appuser /app USER appuser
&& chown -R appuser:appuser /app USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3
CMD curl -f http://localhost:8000/health || exit 1
CMD curl -f http://localhost:8000/health || exit 1
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
**Node.js多阶段构建:**
```dockerfileStage 1: Install dependencies
Stage 1: Install dependencies
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
Stage 2: Build application
Stage 2: Build application
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
Stage 3: Production image
Stage 3: Production image
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
Copy only production dependencies
Copy only production dependencies
COPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
**Go Multi-Stage Build (minimal image):**
```dockerfileCOPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
**Go语言多阶段构建(极简镜像):**
```dockerfileStage 1: Build
Stage 1: Build
FROM golang:1.22-alpine AS builder
WORKDIR /app
FROM golang:1.22-alpine AS builder
WORKDIR /app
Download dependencies
Download dependencies
COPY go.mod go.sum ./
RUN go mod download
COPY go.mod go.sum ./
RUN go mod download
Copy source and build
Copy source and build
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /app/main .
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /app/main .
Stage 2: Minimal production image
Stage 2: Minimal production image
FROM scratch
FROM scratch
Copy SSL certificates for HTTPS
Copy SSL certificates for HTTPS
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
Copy binary
Copy binary
COPY --from=builder /app/main /main
EXPOSE 8080
ENTRYPOINT ["/main"]
undefinedCOPY --from=builder /app/main /main
EXPOSE 8080
ENTRYPOINT ["/main"]
undefined3. Docker Compose for Development
3. Docker Compose开发环境配置
Full Stack Development Environment:
yaml
undefined全栈开发环境:
yaml
undefineddocker-compose.yml
docker-compose.yml
version: '3.8'
services:
Application service
app:
build:
context: .
dockerfile: Dockerfile
target: builder # Use builder stage for development
volumes:
- .:/app
- /app/node_modules # Exclude node_modules from bind mount
ports:
- "3000:3000"
environment:
- NODE_ENV=development
- DATABASE_URL=postgres://devuser:devpass@db:5432/devdb
- REDIS_URL=redis://redis:6379
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
command: npm run dev
networks:
- app-network
Database service
db:
image: postgres:16-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
- ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql
environment:
POSTGRES_DB: devdb
POSTGRES_USER: devuser
POSTGRES_PASSWORD: devpass
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U devuser -d devdb"]
interval: 5s
timeout: 5s
retries: 5
networks:
- app-network
Redis cache
redis:
image: redis:7-alpine
volumes:
- redis_data:/data
ports:
- "6379:6379"
command: redis-server --appendonly yes
networks:
- app-network
Adminer for database management
adminer:
image: adminer:latest
ports:
- "8080:8080"
depends_on:
- db
networks:
- app-network
Nginx reverse proxy
nginx:
image: nginx:alpine
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/conf.d:/etc/nginx/conf.d:ro
ports:
- "80:80"
- "443:443"
depends_on:
- app
networks:
- app-network
networks:
app-network:
driver: bridge
volumes:
postgres_data:
redis_data:
**Development Override File:**
```yamlversion: '3.8'
services:
Application service
app:
build:
context: .
dockerfile: Dockerfile
target: builder # Use builder stage for development
volumes:
- .:/app
- /app/node_modules # Exclude node_modules from bind mount
ports:
- "3000:3000"
environment:
- NODE_ENV=development
- DATABASE_URL=postgres://devuser:devpass@db:5432/devdb
- REDIS_URL=redis://redis:6379
depends_on:
db:
condition: service_healthy
redis:
condition: service_started
command: npm run dev
networks:
- app-network
Database service
db:
image: postgres:16-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
- ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql
environment:
POSTGRES_DB: devdb
POSTGRES_USER: devuser
POSTGRES_PASSWORD: devpass
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U devuser -d devdb"]
interval: 5s
timeout: 5s
retries: 5
networks:
- app-network
Redis cache
redis:
image: redis:7-alpine
volumes:
- redis_data:/data
ports:
- "6379:6379"
command: redis-server --appendonly yes
networks:
- app-network
Adminer for database management
adminer:
image: adminer:latest
ports:
- "8080:8080"
depends_on:
- db
networks:
- app-network
Nginx reverse proxy
nginx:
image: nginx:alpine
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/conf.d:/etc/nginx/conf.d:ro
ports:
- "80:80"
- "443:443"
depends_on:
- app
networks:
- app-network
networks:
app-network:
driver: bridge
volumes:
postgres_data:
redis_data:
**开发环境覆盖配置文件:**
```yamldocker-compose.override.yml (automatically applied)
docker-compose.override.yml (automatically applied)
version: '3.8'
services:
app:
build:
target: builder
volumes:
- .:/app
- /app/node_modules
environment:
- DEBUG=true
- LOG_LEVEL=debug
command: npm run dev:watch
db:
ports:
- "5432:5432" # Expose for local tools
redis:
ports:
- "6379:6379" # Expose for local tools
**Production Compose File:**
```yamlversion: '3.8'
services:
app:
build:
target: builder
volumes:
- .:/app
- /app/node_modules
environment:
- DEBUG=true
- LOG_LEVEL=debug
command: npm run dev:watch
db:
ports:
- "5432:5432" # Expose for local tools
redis:
ports:
- "6379:6379" # Expose for local tools
**生产环境Compose配置:**
```yamldocker-compose.prod.yml
docker-compose.prod.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
target: production
restart: always
environment:
- NODE_ENV=production
- DATABASE_URL=${DATABASE_URL}
- REDIS_URL=${REDIS_URL}
deploy:
replicas: 3
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
db:
restart: always
volumes:
- postgres_data:/var/lib/postgresql/data
deploy:
resources:
limits:
cpus: '1'
memory: 1G
undefinedversion: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
target: production
restart: always
environment:
- NODE_ENV=production
- DATABASE_URL=${DATABASE_URL}
- REDIS_URL=${REDIS_URL}
deploy:
replicas: 3
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
db:
restart: always
volumes:
- postgres_data:/var/lib/postgresql/data
deploy:
resources:
limits:
cpus: '1'
memory: 1G
undefined4. Networking Patterns
4. 网络配置模式
Custom Network Configuration:
yaml
version: '3.8'
services:
frontend:
build: ./frontend
networks:
- frontend-network
backend:
build: ./backend
networks:
- frontend-network
- backend-network
db:
image: postgres:16-alpine
networks:
- backend-network
networks:
frontend-network:
driver: bridge
backend-network:
driver: bridge
internal: true # No external accessNetwork Commands:
bash
undefined自定义网络配置:
yaml
version: '3.8'
services:
frontend:
build: ./frontend
networks:
- frontend-network
backend:
build: ./backend
networks:
- frontend-network
- backend-network
db:
image: postgres:16-alpine
networks:
- backend-network
networks:
frontend-network:
driver: bridge
backend-network:
driver: bridge
internal: true # No external access网络操作命令:
bash
undefinedList networks
List networks
docker network ls
docker network ls
Inspect network
Inspect network
docker network inspect app-network
docker network inspect app-network
Create custom network
Create custom network
docker network create --driver bridge my-network
docker network create --driver bridge my-network
Connect container to network
Connect container to network
docker network connect my-network container-name
docker network connect my-network container-name
Disconnect container
Disconnect container
docker network disconnect my-network container-name
undefineddocker network disconnect my-network container-name
undefined5. Volume Management
5. 卷管理
Volume Types and Usage:
yaml
version: '3.8'
services:
app:
image: myapp:latest
volumes:
# Named volume (managed by Docker)
- app_data:/app/data
# Bind mount (host directory)
- ./config:/app/config:ro
# Anonymous volume (for excluding from bind mount)
- /app/node_modules
# tmpfs mount (in-memory)
- type: tmpfs
target: /app/tmp
tmpfs:
size: 100M
volumes:
app_data:
driver: local
driver_opts:
type: none
device: /data/app
o: bindVolume Commands:
bash
undefined卷类型与使用示例:
yaml
version: '3.8'
services:
app:
image: myapp:latest
volumes:
# Named volume (managed by Docker)
- app_data:/app/data
# Bind mount (host directory)
- ./config:/app/config:ro
# Anonymous volume (for excluding from bind mount)
- /app/node_modules
# tmpfs mount (in-memory)
- type: tmpfs
target: /app/tmp
tmpfs:
size: 100M
volumes:
app_data:
driver: local
driver_opts:
type: none
device: /data/app
o: bind卷操作命令:
bash
undefinedList volumes
List volumes
docker volume ls
docker volume ls
Create volume
Create volume
docker volume create my-volume
docker volume create my-volume
Inspect volume
Inspect volume
docker volume inspect my-volume
docker volume inspect my-volume
Remove unused volumes
Remove unused volumes
docker volume prune
docker volume prune
Backup volume
Backup volume
docker run --rm -v my-volume:/data -v $(pwd):/backup alpine
tar czf /backup/volume-backup.tar.gz -C /data .
tar czf /backup/volume-backup.tar.gz -C /data .
docker run --rm -v my-volume:/data -v $(pwd):/backup alpine
tar czf /backup/volume-backup.tar.gz -C /data .
tar czf /backup/volume-backup.tar.gz -C /data .
Restore volume
Restore volume
docker run --rm -v my-volume:/data -v $(pwd):/backup alpine
tar xzf /backup/volume-backup.tar.gz -C /data
tar xzf /backup/volume-backup.tar.gz -C /data
undefineddocker run --rm -v my-volume:/data -v $(pwd):/backup alpine
tar xzf /backup/volume-backup.tar.gz -C /data
tar xzf /backup/volume-backup.tar.gz -C /data
undefined6. Development Workflow Scripts
6. 开发工作流脚本
Makefile for Docker Operations:
makefile
undefinedDocker操作Makefile:
makefile
undefinedMakefile
Makefile
.PHONY: build up down logs shell test clean
.PHONY: build up down logs shell test clean
Variables
Variables
COMPOSE := docker compose
PROJECT := myapp
COMPOSE := docker compose
PROJECT := myapp
Build images
Build images
build:
$(COMPOSE) build --no-cache
build:
$(COMPOSE) build --no-cache
Start services
Start services
up:
$(COMPOSE) up -d
up:
$(COMPOSE) up -d
Start with logs
Start with logs
up-logs:
$(COMPOSE) up
up-logs:
$(COMPOSE) up
Stop services
Stop services
down:
$(COMPOSE) down
down:
$(COMPOSE) down
Stop and remove volumes
Stop and remove volumes
down-clean:
$(COMPOSE) down -v --remove-orphans
down-clean:
$(COMPOSE) down -v --remove-orphans
View logs
View logs
logs:
$(COMPOSE) logs -f
logs:
$(COMPOSE) logs -f
Logs for specific service
Logs for specific service
logs-%:
$(COMPOSE) logs -f $*
logs-%:
$(COMPOSE) logs -f $*
Shell into app container
Shell into app container
shell:
$(COMPOSE) exec app sh
shell:
$(COMPOSE) exec app sh
Run tests
Run tests
test:
$(COMPOSE) exec app npm test
test:
$(COMPOSE) exec app npm test
Lint Dockerfiles
Lint Dockerfiles
lint:
hadolint Dockerfile
hadolint Dockerfile.prod
lint:
hadolint Dockerfile
hadolint Dockerfile.prod
Analyze image
Analyze image
analyze:
dive $(PROJECT):latest
analyze:
dive $(PROJECT):latest
Clean up
Clean up
clean:
docker system prune -f
docker volume prune -f
clean:
docker system prune -f
docker volume prune -f
Production build and push
Production build and push
prod-build:
docker build -t $(PROJECT):latest -f Dockerfile.prod .
prod-push:
docker push $(PROJECT):latest
**Development Helper Script:**
```bash
#!/bin/bashprod-build:
docker build -t $(PROJECT):latest -f Dockerfile.prod .
prod-push:
docker push $(PROJECT):latest
**开发辅助脚本:**
```bash
#!/bin/bashscripts/docker-dev.sh
scripts/docker-dev.sh
ABOUTME: Docker development helper script
ABOUTME: Docker development helper script
ABOUTME: Provides common Docker operations for development
ABOUTME: Provides common Docker operations for development
set -e
set -e
Colors
Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log_info() { echo -e "${GREEN}[INFO]${NC} $"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log_info() { echo -e "${GREEN}[INFO]${NC} $"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
Commands
Commands
case "$1" in
start)
log_info "Starting development environment..."
docker compose up -d
log_info "Services started. Run 'docker compose logs -f' to view logs."
;;
stop)
log_info "Stopping development environment..."
docker compose down
;;
restart)
log_info "Restarting services..."
docker compose restart
;;
rebuild)
log_info "Rebuilding images..."
docker compose build --no-cache
docker compose up -d
;;
logs)
docker compose logs -f "${2:-}"
;;
shell)
SERVICE="${2:-app}"
log_info "Opening shell in $SERVICE..."
docker compose exec "$SERVICE" sh
;;
db)
log_info "Connecting to database..."
docker compose exec db psql -U devuser -d devdb
;;
reset-db)
log_warn "This will delete all data. Continue? (y/N)"
read -r response
if [[ "$response" =~ ^[Yy]$ ]]; then
docker compose down -v
docker compose up -d db
log_info "Database reset complete."
fi
;;
clean)
log_warn "Cleaning up Docker resources..."
docker compose down -v --remove-orphans
docker system prune -f
;;
status)
docker compose ps
;;
*)
echo "Usage: $0 {start|stop|restart|rebuild|logs|shell|db|reset-db|clean|status}"
echo ""
echo "Commands:"
echo " start - Start all services"
echo " stop - Stop all services"
echo " restart - Restart all services"
echo " rebuild - Rebuild images and restart"
echo " logs - View logs (optional: service name)"
echo " shell - Open shell in container (default: app)"
echo " db - Connect to database"
echo " reset-db - Reset database (deletes all data)"
echo " clean - Clean up all Docker resources"
echo " status - Show service status"
exit 1
;;
esac
undefinedcase "$1" in
start)
log_info "Starting development environment..."
docker compose up -d
log_info "Services started. Run 'docker compose logs -f' to view logs."
;;
stop)
log_info "Stopping development environment..."
docker compose down
;;
restart)
log_info "Restarting services..."
docker compose restart
;;
rebuild)
log_info "Rebuilding images..."
docker compose build --no-cache
docker compose up -d
;;
logs)
docker compose logs -f "${2:-}"
;;
shell)
SERVICE="${2:-app}"
log_info "Opening shell in $SERVICE..."
docker compose exec "$SERVICE" sh
;;
db)
log_info "Connecting to database..."
docker compose exec db psql -U devuser -d devdb
;;
reset-db)
log_warn "This will delete all data. Continue? (y/N)"
read -r response
if [[ "$response" =~ ^[Yy]$ ]]; then
docker compose down -v
docker compose up -d db
log_info "Database reset complete."
fi
;;
clean)
log_warn "Cleaning up Docker resources..."
docker compose down -v --remove-orphans
docker system prune -f
;;
status)
docker compose ps
;;
*)
echo "Usage: $0 {start|stop|restart|rebuild|logs|shell|db|reset-db|clean|status}"
echo ""
echo "Commands:"
echo " start - Start all services"
echo " stop - Stop all services"
echo " restart - Restart all services"
echo " rebuild - Rebuild images and restart"
echo " logs - View logs (optional: service name)"
echo " shell - Open shell in container (default: app)"
echo " db - Connect to database"
echo " reset-db - Reset database (deletes all data)"
echo " clean - Clean up all Docker resources"
echo " status - Show service status"
exit 1
;;
esac
undefinedIntegration Examples
集成示例
1. CI/CD Pipeline Integration
1. CI/CD流水线集成
GitHub Actions Workflow:
yaml
undefinedGitHub Actions工作流:
yaml
undefined.github/workflows/docker.yml
.github/workflows/docker.yml
name: Docker Build and Push
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Lint Dockerfile
uses: hadolint/hadolint-action@v3.1.0
with:
dockerfile: Dockerfile
build:
runs-on: ubuntu-latest
needs: lint
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha,prefix=
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
platforms: linux/amd64,linux/arm64undefinedname: Docker Build and Push
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Lint Dockerfile
uses: hadolint/hadolint-action@v3.1.0
with:
dockerfile: Dockerfile
build:
runs-on: ubuntu-latest
needs: lint
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha,prefix=
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
platforms: linux/amd64,linux/arm64undefined2. Local Development with Hot Reload
2. 支持热重载的本地开发环境
Development Dockerfile:
dockerfile
undefined开发专用Dockerfile:
dockerfile
undefinedDockerfile.dev
Dockerfile.dev
FROM node:20-alpine
WORKDIR /app
FROM node:20-alpine
WORKDIR /app
Install development dependencies
Install development dependencies
RUN apk add --no-cache git
RUN apk add --no-cache git
Install nodemon globally for hot reload
Install nodemon globally for hot reload
RUN npm install -g nodemon
RUN npm install -g nodemon
Copy package files
Copy package files
COPY package*.json ./
COPY package*.json ./
Install all dependencies (including devDependencies)
Install all dependencies (including devDependencies)
RUN npm install
RUN npm install
Don't copy source - use volume mount instead
Don't copy source - use volume mount instead
Source will be mounted at runtime
Source will be mounted at runtime
EXPOSE 3000
EXPOSE 3000
Use nodemon for hot reload
Use nodemon for hot reload
CMD ["nodemon", "--watch", "src", "--ext", "js,ts,json", "src/index.js"]
**Development Compose:**
```yamlCMD ["nodemon", "--watch", "src", "--ext", "js,ts,json", "src/index.js"]
**开发环境Compose配置:**
```yamldocker-compose.dev.yml
docker-compose.dev.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
volumes:
- ./src:/app/src
- ./package.json:/app/package.json
ports:
- "3000:3000"
- "9229:9229" # Debug port
environment:
- NODE_ENV=development
- DEBUG=app:*
command: nodemon --inspect=0.0.0.0:9229 src/index.js
undefinedversion: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
volumes:
- ./src:/app/src
- ./package.json:/app/package.json
ports:
- "3000:3000"
- "9229:9229" # Debug port
environment:
- NODE_ENV=development
- DEBUG=app:*
command: nodemon --inspect=0.0.0.0:9229 src/index.js
undefined3. Multi-Environment Configuration
3. 多环境配置方案
Environment-Specific Compose Files:
bash
undefined环境专属Compose文件结构:
bash
undefinedDirectory structure
Directory structure
docker/
├── docker-compose.yml # Base configuration
├── docker-compose.dev.yml # Development overrides
├── docker-compose.test.yml # Test environment
├── docker-compose.prod.yml # Production configuration
└── .env.example # Environment template
**Usage:**
```bashdocker/
├── docker-compose.yml # Base configuration
├── docker-compose.dev.yml # Development overrides
├── docker-compose.test.yml # Test environment
├── docker-compose.prod.yml # Production configuration
└── .env.example # Environment template
**使用方式:**
```bashDevelopment
Development
docker compose -f docker-compose.yml -f docker-compose.dev.yml up
docker compose -f docker-compose.yml -f docker-compose.dev.yml up
Testing
Testing
docker compose -f docker-compose.yml -f docker-compose.test.yml up
docker compose -f docker-compose.yml -f docker-compose.test.yml up
Production
Production
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
undefineddocker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
undefined4. Database Migration Pattern
4. 数据库迁移模式
Migration Service:
yaml
undefined迁移服务配置:
yaml
undefineddocker-compose.yml
docker-compose.yml
services:
migrate:
build:
context: .
dockerfile: Dockerfile
command: npm run migrate
environment:
- DATABASE_URL=postgres://user:pass@db:5432/mydb
depends_on:
db:
condition: service_healthy
profiles:
- migrate # Only run when explicitly requested
seed:
build:
context: .
dockerfile: Dockerfile
command: npm run seed
environment:
- DATABASE_URL=postgres://user:pass@db:5432/mydb
depends_on:
- migrate
profiles:
- seed
**Usage:**
```bashservices:
migrate:
build:
context: .
dockerfile: Dockerfile
command: npm run migrate
environment:
- DATABASE_URL=postgres://user:pass@db:5432/mydb
depends_on:
db:
condition: service_healthy
profiles:
- migrate # Only run when explicitly requested
seed:
build:
context: .
dockerfile: Dockerfile
command: npm run seed
environment:
- DATABASE_URL=postgres://user:pass@db:5432/mydb
depends_on:
- migrate
profiles:
- seed
**使用方式:**
```bashRun migrations
Run migrations
docker compose --profile migrate up migrate
docker compose --profile migrate up migrate
Run migrations and seed
Run migrations and seed
docker compose --profile migrate --profile seed up
undefineddocker compose --profile migrate --profile seed up
undefinedBest Practices
最佳实践
1. Image Optimization
1. 镜像优化
dockerfile
undefineddockerfile
undefinedUse specific versions
Use specific versions
FROM python:3.12.1-slim # Not :latest
FROM python:3.12.1-slim # Not :latest
Combine RUN commands to reduce layers
Combine RUN commands to reduce layers
RUN apt-get update
&& apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
&& pip install --no-cache-dir -r requirements.txt
&& apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
&& pip install --no-cache-dir -r requirements.txt
RUN apt-get update
&& apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
&& pip install --no-cache-dir -r requirements.txt
&& apt-get install -y --no-install-recommends
gcc
libpq-dev
&& rm -rf /var/lib/apt/lists/*
&& pip install --no-cache-dir -r requirements.txt
Use .dockerignore
Use .dockerignore
.dockerignore
.dockerignore
.git
.gitignore
node_modules
npm-debug.log
Dockerfile*
docker-compose*
.dockerignore
.env*
*.md
.pytest_cache
pycache
*.pyc
.coverage
htmlcov
undefined.git
.gitignore
node_modules
npm-debug.log
Dockerfile*
docker-compose*
.dockerignore
.env*
*.md
.pytest_cache
pycache
*.pyc
.coverage
htmlcov
undefined2. Security Best Practices
2. 安全最佳实践
dockerfile
undefineddockerfile
undefinedRun as non-root user
Run as non-root user
RUN useradd --create-home --shell /bin/bash appuser
USER appuser
RUN useradd --create-home --shell /bin/bash appuser
USER appuser
Don't store secrets in images
Don't store secrets in images
Use environment variables or secrets management
Use environment variables or secrets management
Scan images for vulnerabilities
Scan images for vulnerabilities
docker scan myimage:latest
docker scan myimage:latest
Use read-only filesystem where possible
Use read-only filesystem where possible
docker run --read-only myimage
docker run --read-only myimage
undefinedundefined3. Layer Caching Strategy
3. 分层缓存策略
dockerfile
undefineddockerfile
undefinedOrder from least to most frequently changed
Order from least to most frequently changed
FROM node:20-alpine
FROM node:20-alpine
1. System dependencies (rarely change)
1. System dependencies (rarely change)
RUN apk add --no-cache git
RUN apk add --no-cache git
2. Package manifests (change sometimes)
2. Package manifests (change sometimes)
COPY package*.json ./
RUN npm ci
COPY package*.json ./
RUN npm ci
3. Application code (changes often)
3. Application code (changes often)
COPY . .
COPY . .
4. Build step
4. Build step
RUN npm run build
undefinedRUN npm run build
undefined4. Health Checks
4. 健康检查配置
dockerfile
undefineddockerfile
undefinedHTTP health check
HTTP health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3
CMD curl -f http://localhost:8000/health || exit 1
CMD curl -f http://localhost:8000/health || exit 1
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3
CMD curl -f http://localhost:8000/health || exit 1
CMD curl -f http://localhost:8000/health || exit 1
TCP health check
TCP health check
HEALTHCHECK --interval=30s --timeout=3s
CMD nc -z localhost 5432 || exit 1
CMD nc -z localhost 5432 || exit 1
HEALTHCHECK --interval=30s --timeout=3s
CMD nc -z localhost 5432 || exit 1
CMD nc -z localhost 5432 || exit 1
Custom script
Custom script
HEALTHCHECK --interval=30s --timeout=10s
CMD /app/healthcheck.sh || exit 1
CMD /app/healthcheck.sh || exit 1
undefinedHEALTHCHECK --interval=30s --timeout=10s
CMD /app/healthcheck.sh || exit 1
CMD /app/healthcheck.sh || exit 1
undefined5. Logging Best Practices
5. 日志最佳实践
yaml
services:
app:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
labels: "service,environment"
env: "NODE_ENV"yaml
services:
app:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
labels: "service,environment"
env: "NODE_ENV"Troubleshooting
故障排查
Common Issues and Solutions
常见问题与解决方案
Container won't start:
bash
undefined容器无法启动:
bash
undefinedCheck logs
Check logs
docker logs container-name
docker logs container-name
Check container status
Check container status
docker inspect container-name
docker inspect container-name
Run interactively to debug
Run interactively to debug
docker run -it --entrypoint sh image-name
**Permission denied errors:**
```bashdocker run -it --entrypoint sh image-name
**权限拒绝错误:**
```bashFix file ownership
Fix file ownership
docker run --rm -v $(pwd):/app alpine chown -R $(id -u):$(id -g) /app
docker run --rm -v $(pwd):/app alpine chown -R $(id -u):$(id -g) /app
Or use user namespace remapping
Or use user namespace remapping
**Out of disk space:**
```bash
**磁盘空间不足:**
```bashClean up unused resources
Clean up unused resources
docker system prune -a --volumes
docker system prune -a --volumes
Check disk usage
Check disk usage
docker system df
**Slow builds:**
```bashdocker system df
**构建速度慢:**
```bashEnable BuildKit
Enable BuildKit
export DOCKER_BUILDKIT=1
export DOCKER_BUILDKIT=1
Use cache mounts
Use cache mounts
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
**Network connectivity issues:**
```bashRUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
**网络连接问题:**
```bashCheck network
Check network
docker network inspect bridge
docker network inspect bridge
Test connectivity
Test connectivity
docker exec container-name ping other-container
docker exec container-name ping other-container
Check DNS resolution
Check DNS resolution
docker exec container-name nslookup service-name
undefineddocker exec container-name nslookup service-name
undefinedDebug Commands
调试命令
bash
undefinedbash
undefinedShell into running container
Shell into running container
docker exec -it container-name sh
docker exec -it container-name sh
Copy files from container
Copy files from container
docker cp container-name:/app/logs ./logs
docker cp container-name:/app/logs ./logs
View container processes
View container processes
docker top container-name
docker top container-name
Monitor resource usage
Monitor resource usage
docker stats
docker stats
View container changes
View container changes
docker diff container-name
docker diff container-name
Export container filesystem
Export container filesystem
docker export container-name > container.tar
undefineddocker export container-name > container.tar
undefinedVersion History
版本历史
- 1.0.0 (2026-01-17): Initial release
- Dockerfile best practices and multi-stage builds
- Docker Compose orchestration patterns
- Development and production configurations
- CI/CD integration examples
- Networking and volume management
- Troubleshooting guide
Use this skill to build consistent, reproducible containerized environments across development, testing, and production!
- 1.0.0 (2026-01-17): 初始版本
- Dockerfile最佳实践与多阶段构建
- Docker Compose编排模式
- 开发与生产环境配置
- CI/CD集成示例
- 网络与卷管理
- 故障排查指南
使用本技能,为开发、测试与生产环境打造一致、可复现的容器化环境!