docker-helper
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDocker Helper Skill
Docker Helper 技能
Docker Compose generation, optimization, and troubleshooting assistance.
Docker Compose生成、优化及故障排查辅助支持。
Instructions
说明
You are a Docker and containerization expert. When invoked:
-
Generate Docker Files:
- Create Dockerfile based on project type
- Generate docker-compose.yml for multi-service apps
- Optimize for build time and image size
- Follow best practices for security and performance
-
Optimize Existing Configurations:
- Reduce image sizes (multi-stage builds)
- Improve layer caching
- Security hardening
- Resource limits and health checks
-
Troubleshoot Issues:
- Container startup failures
- Network connectivity problems
- Volume mounting issues
- Performance problems
-
Provide Best Practices:
- Image naming and tagging
- Secrets management
- Logging configuration
- Development vs production configs
你是一名Docker和容器化专家。被调用时:
-
生成Docker文件:
- 根据项目类型创建Dockerfile
- 为多服务应用生成docker-compose.yml
- 针对构建时间和镜像大小进行优化
- 遵循安全与性能最佳实践
-
优化现有配置:
- 减小镜像大小(多阶段构建)
- 改进分层缓存
- 安全加固
- 资源限制与健康检查
-
排查问题:
- 容器启动失败
- 网络连接问题
- 卷挂载问题
- 性能问题
-
提供最佳实践:
- 镜像命名与打标签
- 密钥管理
- 日志配置
- 开发与生产环境配置差异
Dockerfile Best Practices
Dockerfile 最佳实践
Node.js Application
Node.js 应用
dockerfile
undefineddockerfile
undefinedMulti-stage build for smaller image
Multi-stage build for smaller image
FROM node:18-alpine AS builder
WORKDIR /app
FROM node:18-alpine AS builder
WORKDIR /app
Copy package files first (better layer caching)
Copy package files first (better layer caching)
COPY package*.json ./
RUN npm ci --only=production
COPY package*.json ./
RUN npm ci --only=production
Copy application code
Copy application code
COPY . .
RUN npm run build
COPY . .
RUN npm run build
Production stage
Production stage
FROM node:18-alpine
WORKDIR /app
FROM node:18-alpine
WORKDIR /app
Run as non-root user
Run as non-root user
RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001
adduser -S nodejs -u 1001
RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001
adduser -S nodejs -u 1001
Copy only necessary files from builder
Copy only necessary files from builder
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --chown=nodejs:nodejs package*.json ./
USER nodejs
EXPOSE 3000
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --chown=nodejs:nodejs package*.json ./
USER nodejs
EXPOSE 3000
Use exec form for proper signal handling
Use exec form for proper signal handling
CMD ["node", "dist/index.js"]
CMD ["node", "dist/index.js"]
Health check
Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3
CMD node healthcheck.js
CMD node healthcheck.js
undefinedHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3
CMD node healthcheck.js
CMD node healthcheck.js
undefinedPython Application
Python 应用
dockerfile
FROM python:3.11-slim
WORKDIR /appdockerfile
FROM python:3.11-slim
WORKDIR /appInstall dependencies in separate layer
Install dependencies in separate layer
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
Copy application
Copy application
COPY . .
COPY . .
Create non-root user
Create non-root user
RUN useradd -m -u 1001 appuser &&
chown -R appuser:appuser /app
chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["python", "app.py"]
undefinedRUN useradd -m -u 1001 appuser &&
chown -R appuser:appuser /app
chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["python", "app.py"]
undefinedGo Application
Go 应用
dockerfile
undefineddockerfile
undefinedBuild stage
Build stage
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
Final stage - minimal image
Final stage - minimal image
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/main .
EXPOSE 8080
CMD ["./main"]
undefinedFROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/main .
EXPOSE 8080
CMD ["./main"]
undefinedDocker Compose Examples
Docker Compose 示例
Full Stack Application
全栈应用
yaml
version: '3.8'
services:
# Frontend
web:
build:
context: ./web
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- API_URL=http://api:8000
depends_on:
api:
condition: service_healthy
networks:
- frontend
restart: unless-stopped
# Backend API
api:
build:
context: ./api
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/myapp
- REDIS_URL=redis://cache:6379
env_file:
- .env
depends_on:
db:
condition: service_healthy
cache:
condition: service_started
networks:
- frontend
- backend
volumes:
- ./logs:/app/logs
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
# Database
db:
image: postgres:15-alpine
environment:
- POSTGRES_DB=myapp
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
networks:
- backend
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
interval: 10s
timeout: 5s
retries: 5
# Redis Cache
cache:
image: redis:7-alpine
command: redis-server --appendonly yes
volumes:
- redis_data:/data
networks:
- backend
restart: unless-stopped
# Nginx Reverse Proxy
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/nginx/ssl:ro
depends_on:
- web
- api
networks:
- frontend
restart: unless-stopped
networks:
frontend:
driver: bridge
backend:
driver: bridge
volumes:
postgres_data:
redis_data:yaml
version: '3.8'
services:
# Frontend
web:
build:
context: ./web
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- API_URL=http://api:8000
depends_on:
api:
condition: service_healthy
networks:
- frontend
restart: unless-stopped
# Backend API
api:
build:
context: ./api
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/myapp
- REDIS_URL=redis://cache:6379
env_file:
- .env
depends_on:
db:
condition: service_healthy
cache:
condition: service_started
networks:
- frontend
- backend
volumes:
- ./logs:/app/logs
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
# Database
db:
image: postgres:15-alpine
environment:
- POSTGRES_DB=myapp
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
networks:
- backend
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d myapp"]
interval: 10s
timeout: 5s
retries: 5
# Redis Cache
cache:
image: redis:7-alpine
command: redis-server --appendonly yes
volumes:
- redis_data:/data
networks:
- backend
restart: unless-stopped
# Nginx Reverse Proxy
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/nginx/ssl:ro
depends_on:
- web
- api
networks:
- frontend
restart: unless-stopped
networks:
frontend:
driver: bridge
backend:
driver: bridge
volumes:
postgres_data:
redis_data:Development Environment
开发环境
yaml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
environment:
- NODE_ENV=development
volumes:
- .:/app
- /app/node_modules # Anonymous volume for node_modules
command: npm run dev
networks:
- dev_network
db:
image: postgres:15-alpine
environment:
- POSTGRES_DB=dev_db
- POSTGRES_USER=dev
- POSTGRES_PASSWORD=dev_password
ports:
- "5432:5432"
volumes:
- dev_db_data:/var/lib/postgresql/data
networks:
- dev_network
volumes:
dev_db_data:
networks:
dev_network:yaml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
environment:
- NODE_ENV=development
volumes:
- .:/app
- /app/node_modules # Anonymous volume for node_modules
command: npm run dev
networks:
- dev_network
db:
image: postgres:15-alpine
environment:
- POSTGRES_DB=dev_db
- POSTGRES_USER=dev
- POSTGRES_PASSWORD=dev_password
ports:
- "5432:5432"
volumes:
- dev_db_data:/var/lib/postgresql/data
networks:
- dev_network
volumes:
dev_db_data:
networks:
dev_network:Usage Examples
使用示例
@docker-helper
@docker-helper --generate-dockerfile
@docker-helper --optimize
@docker-helper --compose
@docker-helper --troubleshoot@docker-helper
@docker-helper --generate-dockerfile
@docker-helper --optimize
@docker-helper --compose
@docker-helper --troubleshootOptimization Techniques
优化技巧
Multi-Stage Builds
多阶段构建
dockerfile
undefineddockerfile
undefinedReduces final image size by 70-90%
Reduces final image size by 70-90%
FROM node:18 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
CMD ["node", "dist/index.js"]
undefinedFROM node:18 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
CMD ["node", "dist/index.js"]
undefinedLayer Caching
分层缓存
dockerfile
undefineddockerfile
undefined❌ Bad - Invalidates cache on any file change
❌ Bad - Invalidates cache on any file change
COPY . .
RUN npm install
COPY . .
RUN npm install
✓ Good - Cache dependencies separately
✓ Good - Cache dependencies separately
COPY package*.json ./
RUN npm install
COPY . .
undefinedCOPY package*.json ./
RUN npm install
COPY . .
undefinedReduce Image Size
减小镜像大小
dockerfile
undefineddockerfile
undefinedUse alpine variants (much smaller)
Use alpine variants (much smaller)
FROM node:18-alpine # ~170MB vs ~900MB for node:18
FROM node:18-alpine # ~170MB vs ~900MB for node:18
Clean up in same layer
Clean up in same layer
RUN apt-get update &&
apt-get install -y package &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
apt-get install -y package &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
RUN apt-get update &&
apt-get install -y package &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
apt-get install -y package &&
apt-get clean &&
rm -rf /var/lib/apt/lists/*
Use .dockerignore
Use .dockerignore
Create .dockerignore file:
Create .dockerignore file:
node_modules
node_modules
.git
.git
*.md
*.md
.env*
.env*
undefinedundefinedSecurity Best Practices
安全最佳实践
dockerfile
undefineddockerfile
undefinedDon't run as root
Don't run as root
RUN adduser -D -u 1001 appuser
USER appuser
RUN adduser -D -u 1001 appuser
USER appuser
Scan for vulnerabilities
Scan for vulnerabilities
Use: docker scan myimage:tag
Use: docker scan myimage:tag
Use specific tags, not 'latest'
Use specific tags, not 'latest'
FROM node:18.16.0-alpine # Not: FROM node:latest
FROM node:18.16.0-alpine # Not: FROM node:latest
Don't store secrets in image
Don't store secrets in image
Use environment variables or secrets management
Use environment variables or secrets management
Minimize attack surface
Minimize attack surface
Use minimal base images (alpine, distroless)
Use minimal base images (alpine, distroless)
Keep base images updated
Keep base images updated
Regularly rebuild and update
Regularly rebuild and update
undefinedundefinedCommon Issues & Solutions
常见问题与解决方案
Issue: Container Exits Immediately
问题:容器立即退出
bash
undefinedbash
undefinedCheck logs
Check logs
docker logs <container_id>
docker logs <container_id>
Run interactively to debug
Run interactively to debug
docker run -it <image> /bin/sh
docker run -it <image> /bin/sh
Check entrypoint/command
Check entrypoint/command
docker inspect <container_id> | grep -A5 Cmd
undefineddocker inspect <container_id> | grep -A5 Cmd
undefinedIssue: Cannot Connect to Service
问题:无法连接到服务
yaml
undefinedyaml
undefinedEnsure services are on same network
Ensure services are on same network
networks:
- mynetwork
networks:
- mynetwork
Use service name as hostname
Use service name as hostname
DATABASE_URL=postgresql://db:5432/myapp # 'db' is service name
DATABASE_URL=postgresql://db:5432/myapp # 'db' is service name
Check if service is ready
Check if service is ready
depends_on:
db:
condition: service_healthy
undefineddepends_on:
db:
condition: service_healthy
undefinedIssue: Volume Permission Problems
问题:卷权限问题
dockerfile
undefineddockerfile
undefinedMatch host user ID
Match host user ID
RUN adduser -u 1001 appuser
USER appuser
RUN adduser -u 1001 appuser
USER appuser
Or change ownership in entrypoint
Or change ownership in entrypoint
ENTRYPOINT ["sh", "-c", "chown -R appuser:appuser /data && exec "$@""]
undefinedENTRYPOINT ["sh", "-c", "chown -R appuser:appuser /data && exec "$@""]
undefinedIssue: Slow Builds
问题:构建速度慢
dockerfile
undefineddockerfile
undefinedUse build cache effectively
Use build cache effectively
COPY package*.json ./
RUN npm ci
COPY . .
COPY package*.json ./
RUN npm ci
COPY . .
Use BuildKit
Use BuildKit
Set: DOCKER_BUILDKIT=1
Set: DOCKER_BUILDKIT=1
Use .dockerignore
Use .dockerignore
Exclude: node_modules, .git, build artifacts
Exclude: node_modules, .git, build artifacts
undefinedundefinedDocker Commands Reference
Docker 命令参考
bash
undefinedbash
undefinedBuild image
Build image
docker build -t myapp:latest .
docker build -t myapp:latest .
Run container
Run container
docker run -d -p 3000:3000 --name myapp myapp:latest
docker run -d -p 3000:3000 --name myapp myapp:latest
View logs
View logs
docker logs -f myapp
docker logs -f myapp
Execute command in container
Execute command in container
docker exec -it myapp /bin/sh
docker exec -it myapp /bin/sh
Stop and remove
Stop and remove
docker stop myapp && docker rm myapp
docker stop myapp && docker rm myapp
Compose commands
Compose commands
docker-compose up -d
docker-compose down
docker-compose logs -f
docker-compose ps
docker-compose up -d
docker-compose down
docker-compose logs -f
docker-compose ps
Clean up
Clean up
docker system prune -a
docker volume prune
undefineddocker system prune -a
docker volume prune
undefinedHealth Checks
健康检查
dockerfile
undefineddockerfile
undefinedNode.js
Node.js
HEALTHCHECK --interval=30s --timeout=3s
CMD node healthcheck.js || exit 1
CMD node healthcheck.js || exit 1
HEALTHCHECK --interval=30s --timeout=3s
CMD node healthcheck.js || exit 1
CMD node healthcheck.js || exit 1
Python
Python
HEALTHCHECK --interval=30s --timeout=3s
CMD python -c "import requests; requests.get('http://localhost:8000/health')" || exit 1
CMD python -c "import requests; requests.get('http://localhost:8000/health')" || exit 1
HEALTHCHECK --interval=30s --timeout=3s
CMD python -c "import requests; requests.get('http://localhost:8000/health')" || exit 1
CMD python -c "import requests; requests.get('http://localhost:8000/health')" || exit 1
Simple HTTP check
Simple HTTP check
HEALTHCHECK --interval=30s --timeout=3s
CMD wget --no-verbose --tries=1 --spider http://localhost:8000/health || exit 1
CMD wget --no-verbose --tries=1 --spider http://localhost:8000/health || exit 1
undefinedHEALTHCHECK --interval=30s --timeout=3s
CMD wget --no-verbose --tries=1 --spider http://localhost:8000/health || exit 1
CMD wget --no-verbose --tries=1 --spider http://localhost:8000/health || exit 1
undefinedNotes
注意事项
- Always use specific version tags, not
latest - Implement health checks for critical services
- Use multi-stage builds to reduce image size
- Never store secrets in Dockerfiles or images
- Use to exclude unnecessary files
.dockerignore - Run containers as non-root users
- Implement proper logging (stdout/stderr)
- Use volumes for persistent data
- Configure resource limits in production
- Regularly update base images for security patches
- 始终使用特定版本标签,而非
latest - 为关键服务实现健康检查
- 使用多阶段构建减小镜像大小
- 切勿在Dockerfile或镜像中存储密钥
- 使用 排除不必要的文件
.dockerignore - 以非root用户运行容器
- 实现适当的日志记录(stdout/stderr)
- 使用卷存储持久化数据
- 在生产环境中配置资源限制
- 定期更新基础镜像以获取安全补丁