D
DevOps工程师
3周前
Docker 容器化开发最佳实践
DockerDevOps容器化
Docker 容器化最佳实践
从开发到生产的 Docker 使用指南。
1. Dockerfile 优化
dockerfile
# 多阶段构建
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
CMD ["node", "server.js"]
2. 镜像瘦身
dockerfile
RUN npm ci && npm cache clean --force
3. 安全实践
dockerfile
# 非 root 用户运行
USER node
# 只读文件系统
docker run --read-only myapp
4. Docker Compose
yaml
services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
5. 常用命令
bash
# 构建并推送
docker build -t myapp:latest .
docker push myapp:latest
# 清理资源
docker system prune -a
2.5k 阅读