零度AI
高级18 分钟阅读

Claude Code DevOps 实战

学习使用 Claude Code 进行 DevOps 实践,包括容器化、监控、自动化部署

Claude CodeDevOpsDockerKubernetes监控

DevOps 概述

DevOps 是开发和运维的融合,目标是快速、可靠地交付软件。Claude Code 可以帮助你:

  • 🐳 容器化应用
  • 🚀 自动化部署
  • 📊 监控和告警
  • 🔧 运维自动化

Docker 容器化

1. 基础 Dockerfile

dockerfile
# Dockerfile
FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

2. .dockerignore

# .dockerignore node_modules npm-debug.log .git .env .next

3. 构建和运行

bash
# 构建镜像
docker build -t my-app .

# 运行容器
docker run -d -p 3000:3000 --name my-container my-app

# 查看日志
docker logs my-container

# 停止容器
docker stop my-container

Docker Compose

1. 多服务编排

yaml
# docker-compose.yml
version: '3.8'
services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgres://user:password@db:5432/mydb
    depends_on:
      - db
    networks:
      - app-network

  db:
    image: postgres:15-alpine
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=mydb
    volumes:
      - postgres-data:/var/lib/postgresql/data
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  postgres-data:

2. 常用命令

bash
# 启动所有服务
docker-compose up -d

# 查看服务状态
docker-compose ps

# 查看日志
docker-compose logs -f

# 停止服务
docker-compose down

Kubernetes 入门

1. Deployment

yaml
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: my-app:latest
        ports:
        - containerPort: 3000
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"
          limits:
            cpu: "500m"
            memory: "512Mi"
        livenessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 3000
          initialDelaySeconds: 5
          periodSeconds: 5

2. Service

yaml
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app-service
spec:
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 3000
  type: LoadBalancer

3. 常用命令

bash
# 应用配置
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml

# 查看状态
kubectl get deployments
kubectl get pods
kubectl get services

# 查看日志
kubectl logs -f deployment/my-app

# 扩容
kubectl scale deployment my-app --replicas=5

监控和日志

1. Prometheus + Grafana

yaml
# prometheus-config.yaml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']
  - job_name: 'app'
    static_configs:
      - targets: ['app:3000']

2. 应用指标

javascript
// src/metrics.js
import promClient from 'prom-client'

const register = new promClient.Registry()

const httpRequestDurationMicroseconds = new promClient.Histogram({
  name: 'http_request_duration_ms',
  help: 'Duration of HTTP requests in ms',
  labelNames: ['method', 'route', 'code'],
  buckets: [0.1, 5, 15, 50, 100, 300, 500, 1000, 3000, 5000]
})

register.registerMetric(httpRequestDurationMicroseconds)

export function recordRequest(method, route, code, duration) {
  httpRequestDurationMicroseconds
    .labels(method, route, code)
    .observe(duration)
}

export { register }

3. 日志聚合

javascript
// 使用 Winston 结构化日志
import winston from 'winston'

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
})

logger.info('用户登录', { userId: '123', ip: '192.168.1.1' })
logger.error('数据库连接失败', { error: 'ECONNREFUSED' })

CI/CD 流水线

1. GitHub Actions - 完整流程

yaml
# .github/workflows/deploy.yml
name: Deploy to Production

on:
  push:
    branches: [main]

env:
  DOCKER_REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Lint code
        run: npm run lint

  build-and-push:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.DOCKER_REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:latest
            ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}

  deploy:
    needs: build-and-push
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Deploy to Kubernetes
        uses: azure/k8s-deploy@v4
        with:
          manifests: |
            k8s/deployment.yaml
            k8s/service.yaml
          images: |
            ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}

基础设施即代码

1. Terraform 基础

hcl
# main.tf
provider "aws" {
  region = "us-east-1"
}

# 创建 VPC
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "main-vpc"
  }
}

# 创建子网
resource "aws_subnet" "public" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"

  tags = {
    Name = "public-subnet"
  }
}

# 创建安全组
resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "Allow HTTP and HTTPS traffic"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

实战案例:完整 DevOps 流程

容器化应用

帮我为这个 Next.js 应用创建 Dockerfile 和 docker-compose.yml

Claude Code 会生成:

  • Dockerfile
  • .dockerignore
  • docker-compose.yml(包含数据库)

配置监控

帮我配置 Prometheus 和 Grafana 监控

Claude Code 会帮你:

  • 配置应用指标
  • 设置 Prometheus
  • 创建 Grafana 仪表板

设置 CI/CD

帮我创建 GitHub Actions 流水线,自动测试、构建、部署

Claude Code 会帮你:

  • 创建测试阶段
  • 配置 Docker 镜像构建
  • 设置部署到 Kubernetes

基础设施即代码

帮我用 Terraform 创建 AWS 基础设施

Claude Code 会帮你:

  • 配置 VPC 和网络
  • 创建 EKS 集群
  • 设置负载均衡

常见问题

Q: 如何优化 Docker 镜像大小?

帮我优化这个 Dockerfile,减少镜像大小

Q: 如何处理容器日志?

帮我配置 ELK 日志栈

Q: 如何实现零停机部署?

帮我配置蓝绿部署

下一步

掌握了 DevOps 后,接下来可以学习:

  • Claude Code 架构设计 - 系统架构设计
  • Claude Code 安全运维 - 运维安全
  • Claude Code 性能优化 - 系统性能优化

自动化一切!

DevOps 的目标是自动化繁琐的工作,让你专注于创新。Claude Code 可以帮你从一开始就建立良好的 DevOps 实践!