游戏 DevOps 最佳实践:构建高效研发运维体系

深入探讨游戏研发的DevOps最佳实践,包括容器化部署、自动化运维、监控告警等

现代Web服务器架构:从单体到微服务的演进之路

引言 现代Web服务器架构经历了从单体应用到微服务,从传统部署到云原生的演进。了解不同的架构模式及其适用场景,对于构建可扩展、高可用的Web应用至关重要。本文将系统性地介绍现代Web服务器架构的各个方面。 架构演进 发展历程 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 """ Web架构演进 单体架构: - 单一代码库 - 单一数据库 - 简单部署 微服务架构: - 服务拆分 - 独立部署 - 技术多样 云原生: - 容器化 - 服务网格 - Serverless """ class ArchitectureEvolution: """架构演进""" def __init__(self): self.stages = { "单体应用": { "特点": "单一部署单元", "优势": "简单,快速开发", "劣势": "扩展困难", "适用": "小型应用" }, "垂直拆分": { "特点": "按功能拆分", "优势": "部分独立", "劣势": "共享数据库", "适用": "中型应用" }, "微服务": { "特点": "服务完全独立", "优势": "灵活扩展", "劣势": "复杂度高", "适用": "大型应用" }, "Serverless": { "特点": "函数即服务", "优势": "按需付费", "劣势": "厂商锁定", "适用": "事件驱动" } } def trade_offs(self): """权衡对比""" trade_offs = { "开发速度": { "单体": "最快", "微服务": "慢", "Serverless": "中等" }, "运维复杂度": { "单体": "低", "微服务": "高", "Serverless": "最低" }, "扩展性": { "单体": "难", "微服务": "易", "Serverless": "自动" }, "成本": { "单体": "低", "微服务": "中", "Serverless": "高(高流量时)" } } return trade_offs 微服务架构 服务设计 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 class MicroservicesArchitecture: """微服务架构""" def __init__(self): self.principles = { "单一职责": { "描述": "每个服务一个职责", "边界": "清晰API", "独立": "独立部署" }, "去中心化": { "数据": "每个服务自己的数据库", "技术": "异构技术栈", "治理": "去中心化治理" }, "故障隔离": { "隔离": "服务边界隔离", "降级": "优雅降级", "恢复": "自动恢复" } } def service_decomposition(self): """服务拆分策略""" strategies = { "按业务能力": { "描述": "业务领域划分", "示例": ["用户", "订单", "支付"], "方法": "DDD领域驱动" }, "按数据": { "描述": "数据所有权划分", "示例": ["用户数据", "商品数据"], "方法": "数据子域" }, "按可扩展性": { "描述": "按扩展需求", "示例": ["高并发服务独立"], "方法": "扩展点识别" } } return strategies def communication_patterns(self): """通信模式""" patterns = { "同步": { "REST": "简单, 通用", "GraphQL": "灵活查询", "gRPC": "高性能RPC", "应用": "服务间调用" }, "异步": { "消息队列": "解耦", "事件总线": "事件驱动", "发布订阅": "一对多", "应用": "最终一致性" } } return patterns API网关 网关设计 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class APIGateway: """API网关""" def __init__(self): self.responsibilities = { "路由": { "请求路由": "到后端服务", "负载均衡": "服务实例", "灰度发布": "流量分流" }, "横切关注点": { "认证": "统一认证", "授权": "权限控制", "限流": "请求限流" }, "协议转换": { "HTTP": "外部HTTP", "gRPC": "内部gRPC", "WebSocket": "实时通信" } } def gateway_patterns(self): """网关模式""" patterns = { "BFF": { "全称": "Backend for Frontend", "描述": "按前端定制网关", "优势": "前端友好" }, "网关集群": { "描述": "多网关实例", "优势": "高可用", "挑战": "配置同步" }, "侧车模式": { "描述": "服务旁部署", "优势": "服务自治", "应用": "Service Mesh" } } return patterns 服务发现与注册 动态服务发现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class ServiceDiscovery: """服务发现""" def __init__(self): self.methods = { "客户端发现": { "注册中心": "服务注册", "客户端": "查询地址", "示例": ["Eureka", "Consul", "Etcd"] }, "服务端发现": { "负载均衡": "LB查询注册", "路由": "LB分发", "示例": ["K8s Service", "Nginx"] }, "DNS": { "DNS记录": "服务地址", "TTL": "缓存控制", "示例": ["SkyDNS", "CoreDNS"] } } def health_checking(self): """健康检查""" health = { "类型": { "Liveness": "服务是否存活", "Readiness": "是否接受流量", "Startup": "启动检查" }, "实现": { "HTTP端点": "/health", "TCP": "端口检查", "Exec": "执行脚本" }, "策略": { "失败": "移除流量", "恢复": "恢复流量", "间隔": "检查间隔" } } return health 容器化与编排 Docker和Kubernetes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 class ContainerOrchestration: """容器编排""" def __init__(self): self.technologies = { "Docker": { "容器": "标准容器", "镜像": "分层镜像", "仓库": "镜像仓库", "优势": "环境一致" }, "Kubernetes": { "编排": "容器编排", "调度": "自动调度", "服务": "服务发现", "存储": "存储管理" } } def kubernetes_concepts(self): """Kubernetes核心概念""" concepts = { "Pod": { "描述": "最小部署单元", "组成": "一个或多个容器", "生命周期": "临时性" }, "Service": { "描述": "服务抽象", "类型": ["ClusterIP", "NodePort", "LoadBalancer"], "发现": "DNS服务发现" }, "Deployment": { "描述": "声明式部署", "更新": "滚动更新", "回滚": "版本回滚" }, "ConfigMap/Secret": { "描述": "配置和敏感数据", "挂载": "卷挂载", "更新": "热更新" } } return concepts def scaling_strategies(self): """扩展策略""" scaling = { "水平": { "Manual": "手动调整副本", "Auto": "HPA自动调整", "Custom": "自定义指标" }, "垂直": { "资源": "CPU/内存调整", "限制": "资源配置", "申请": "资源请求" }, "集群": { "节点": "自动扩缩节点", "Cluster Autoscaler": "K8s组件", "云提供商": "云服务集成" } } return scaling 服务网格 Service Mesh 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class ServiceMesh: """服务网格""" def __init__(self): self.concept = { "定义": "基础设施层处理服务通信", "Sidecar": "每个服务旁部署代理", "功能": ["流量管理", "安全", "可观测性"], "实现": ["Istio", "Linkerd", "Consul"] } def istio_architecture(self): """Istio架构""" istio = { "数据平面": { "Envoy": "Sidecar代理", "功能": "流量拦截和转发", "特点": "对应用透明" }, "控制平面": { "Istiod": "统一控制", "功能": ["配置", "证书", "策略"], "优势": "集中管理" }, "特性": { "流量": "灰度, 蓝绿, 金丝雀", "安全": "mTLS, 认证授权", "观察": "指标, 日志, 追踪" } } return istio Serverless架构 函数即服务 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 class ServerlessArchitecture: """Serverless架构""" def __init__(self): self.platforms = { "AWS": ["Lambda", "API Gateway", "DynamoDB"], "Azure": ["Functions", "API Management", "CosmosDB"], "Google": ["Cloud Functions", "API Gateway", "Firestore"] } def use_cases(self): """使用场景""" cases = { "适合": { "事件驱动": "异步处理", "突发流量": "自动扩展", "批处理": "定时任务", "Webhook": "HTTP回调" }, "不适合": { "长运行": "执行时间限制", "状态ful": "需要外部存储", "低延迟": "冷启动" } } return cases def best_practices(self): """最佳实践""" practices = { "设计": { "无状态": "函数无状态", "小函数": "单一职责", "异步": "使用消息队列" }, "性能": { "预热": "保持热度", "优化": "减少冷启动", "并发": "合理并发" }, "监控": { "日志": "集中日志", "指标": "性能指标", "追踪": "请求追踪" } } return practices 数据管理 分布式数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 class DataManagement: """数据管理""" def __init__(self): self.patterns = { "数据库": { "关系型": ["PostgreSQL", "MySQL"], "NoSQL": ["MongoDB", "Cassandra"], "缓存": ["Redis", "Memcached"] }, "策略": { "分片": "水平拆分", "复制": "读写分离", "缓存": "多级缓存" } } def data_consistency(self): """数据一致性""" consistency = { "强一致性": { "ACID": "传统事务", "2PC": "两阶段提交", "应用": "关键数据" }, "最终一致性": { "BASE": "基本可用", "事件": "事件驱动", "应用": "非关键数据" }, "解决方案": { "Saga": "长事务", "CQRS": "读写分离", "事件溯源": "事件存储" } } return consistency 可观测性 监控体系 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class Observability: """可观测性""" def __init__(self): self.pillars = { "日志": { "结构化": "JSON格式", "聚合": "集中收集", "分析": "ELK, Loki" }, "指标": { "类型": ["Counter", "Gauge", "Histogram"], "收集": "Prometheus", "可视化": "Grafana" }, "追踪": { "标准": "OpenTelemetry", "后端": "Jaeger, Zipkin", "用途": "分布式追踪" } } def alerting(self): """告警系统""" alerting = { "规则": { "阈值": "静态阈值", "趋势": "趋势异常", "智能": "AI异常检测" }, "渠道": { "邮件": "邮件通知", "即时通讯": "Slack, 钉钉", "电话": "重要告警" }, "策略": { "分级": "P1-P4", "升级": "未处理升级", "收敛": "告警收敛" } } return alerting 总结 现代Web服务器架构从单体向微服务、云原生演进,提供了更强的可扩展性和灵活性。选择合适的架构模式需要综合考虑团队技能、项目规模和业务需求。 ...

Docker与Kubernetes容器化部署:从零搭建生产级容器化系统

引言 容器化技术彻底改变了应用的部署和运维方式。Docker提供了轻量级的容器化解决方案,而Kubernetes(K8s)则提供了强大的容器编排能力。本文将从零开始,深入讲解如何使用Docker和Kubernetes构建生产级的容器化系统。 一、Docker基础 1.1 Docker核心概念 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # Docker三大核心概念 # 1. 镜像(Image):应用的只读模板 # 2. 容器(Container):镜像的运行实例 # 3. 仓库(Registry):存储和分发镜像 # 查看Docker版本 docker --version docker info # 运行第一个容器 docker run hello-world # 交互式运行容器 docker run -it ubuntu bash 1.2 Dockerfile最佳实践 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 # 1. 选择合适的基础镜像 # 生产环境推荐使用alpine或distroless FROM node:20-alpine AS builder # 2. 设置工作目录 WORKDIR /app # 3. 优化依赖安装(利用Docker缓存) # 先复制package文件,安装依赖后再复制源代码 COPY package*.json ./ RUN npm ci --only=production # 4. 复制源代码 COPY . . # 5. 构建应用 RUN npm run build # 6. 生产镜像(多阶段构建) FROM node:20-alpine # 7. 创建非root用户 RUN addgroup -g 1001 -S nodejs && \ adduser -S nodejs -u 1001 WORKDIR /app # 8. 只复制必要文件 COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules COPY --from=builder --chown=nodejs:nodejs /app/package.json ./ # 9. 切换到非root用户 USER nodejs # 10. 暴露端口 EXPOSE 3000 # 11. 健康检查 HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD node healthcheck.js || exit 1 # 12. 启动命令 CMD ["node", "dist/index.js"] 1.3 Docker Compose本地开发 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 # docker-compose.yml version: '3.8' services: # 前端应用 frontend: build: context: ./frontend dockerfile: Dockerfile target: development ports: - "3000:3000" volumes: - ./frontend:/app - /app/node_modules environment: - NODE_ENV=development - API_URL=http://api:4000 depends_on: - api # 后端API api: build: context: ./backend dockerfile: Dockerfile ports: - "4000:4000" environment: - NODE_ENV=development - DATABASE_URL=postgresql://postgres:password@db:5432/myapp - REDIS_URL=redis://redis:6379 depends_on: - db - redis volumes: - ./backend:/app - /app/node_modules # PostgreSQL数据库 db: image: postgres:16-alpine ports: - "5432:5432" environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password - POSTGRES_DB=myapp volumes: - postgres_data:/var/lib/postgresql/data - ./init.sql:/docker-entrypoint-initdb.d/init.sql # Redis缓存 redis: image: redis:7-alpine ports: - "6379:6379" volumes: - redis_data:/data command: redis-server --appendonly yes # Nginx反向代理 nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - ./nginx/ssl:/etc/nginx/ssl:ro depends_on: - frontend - api volumes: postgres_data: redis_data: 二、Kubernetes核心概念 2.1 Pod与容器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 # pod.yaml - 最小部署单元 apiVersion: v1 kind: Pod metadata: name: nginx-pod labels: app: nginx spec: containers: - name: nginx image: nginx:1.25-alpine ports: - containerPort: 80 resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" cpu: "500m" livenessProbe: httpGet: path: / port: 80 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: / port: 80 initialDelaySeconds: 5 periodSeconds: 5 volumeMounts: - name: config mountPath: /etc/nginx/conf.d volumes: - name: config configMap: name: nginx-config 2.2 Deployment部署 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 # deployment.yaml - 声明式部署 apiVersion: apps/v1 kind: Deployment metadata: name: web-app labels: app: web spec: # 期望的副本数 replicas: 3 # 选择器 selector: matchLabels: app: web # Pod模板 template: metadata: labels: app: web spec: containers: - name: web image: myregistry/web-app:v1.0.0 ports: - containerPort: 3000 env: - name: NODE_ENV value: "production" - name: DATABASE_URL valueFrom: secretKeyRef: name: db-secret key: url resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" livenessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: /ready port: 3000 initialDelaySeconds: 5 periodSeconds: 5 # 更新策略 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 # 最多多1个Pod maxUnavailable: 0 # 不允许不可用Pod # 历史版本限制 revisionHistoryLimit: 10 2.3 Service服务发现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # service.yaml - 服务暴露 apiVersion: v1 kind: Service metadata: name: web-service spec: # ClusterIP: 集群内部访问(默认) # NodePort: 通过节点IP:端口访问 # LoadBalancer: 云服务商负载均衡器 type: ClusterIP # 选择器 selector: app: web # 端口配置 ports: - name: http protocol: TCP port: 80 # Service端口 targetPort: 3000 # Pod端口 # Session保持(可选) sessionAffinity: ClientIP sessionAffinityConfig: clientIP: timeoutSeconds: 10800 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 # ingress.yaml - HTTP路由 apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: web-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/ssl-redirect: "true" cert-manager.io/cluster-issuer: "letsencrypt-prod" spec: ingressClassName: nginx tls: - hosts: - example.com secretName: web-tls rules: - host: example.com http: paths: - path: / pathType: Prefix backend: service: name: web-service port: number: 80 三、Kubernetes高级配置 3.1 ConfigMap配置管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # configmap.yaml apiVersion: v1 kind: ConfigMap metadata: name: app-config data: # 键值对配置 NODE_ENV: "production" LOG_LEVEL: "info" # 文件配置 app.json: | { "port": 3000, "database": { "host": "postgres.default.svc.cluster.local", "port": 5432 } } nginx.conf: | server { listen 80; location / { proxy_pass http://web-service:3000; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 # 使用ConfigMap apiVersion: v1 kind: Pod metadata: name: app-pod spec: containers: - name: app image: myapp:latest env: # 从ConfigMap读取环境变量 - name: NODE_ENV valueFrom: configMapKeyRef: name: app-config key: NODE_ENV volumeMounts: # 挂载文件 - name: config mountPath: /etc/app readOnly: true volumes: - name: config configMap: name: app-config items: - key: app.json path: config.json - key: nginx.conf path: nginx.conf 3.2 Secret密钥管理 1 2 3 4 5 6 7 8 9 10 11 # 创建Secret apiVersion: v1 kind: Secret metadata: name: db-secret type: Opaque data: # Base64编码的值 username: cG9zdGdyZXM= password: cGFzc3dvcmQ= url: cG9zdGdyZXNxbDovL3Bvc3RncmVzOnBhc3N3b3JkQGRiOjU0MzIvbXlhcHA= 1 2 3 4 5 6 7 8 9 10 # 从命令行创建Secret kubectl create secret generic db-secret \ --from-literal=username=postgres \ --from-literal=password=password \ --from-file=cert=./tls.crt # 从文件创建 kubectl create secret tls web-tls \ --cert=path/to/tls.cert \ --key=path/to/tls.key 3.3 PersistentVolume持久化存储 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # persistent-volume.yaml apiVersion: v1 kind: PersistentVolume metadata: name: pv-data spec: capacity: storage: 10Gi accessModes: - ReadWriteOnce # RWO, RWX, ROX persistentVolumeReclaimPolicy: Retain # Retain, Delete, Recycle storageClassName: standard hostPath: path: /data/volume 1 2 3 4 5 6 7 8 9 10 11 12 # persistent-volume-claim.yaml apiVersion: v1 kind: PersistentVolumeClaim metadata: name: pvc-data spec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi storageClassName: standard 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # 使用PVC apiVersion: v1 kind: Pod metadata: name: app-pod spec: containers: - name: app image: myapp:latest volumeMounts: - name: data mountPath: /app/data volumes: - name: data persistentVolumeClaim: claimName: pvc-data 四、自动扩缩容 4.1 Horizontal Pod Autoscaler 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 # hpa.yaml - 水平Pod自动扩缩容 apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: web-hpa spec: # 扩缩容目标 scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: web-app # 最小和最大副本数 minReplicas: 2 maxReplicas: 10 # 指标配置 metrics: # CPU使用率 - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 # 内存使用量 - type: Resource resource: name: memory target: type: AverageValue averageValue: 512Mi # 自定义指标 - type: Pods pods: metric: name: http_requests_per_second target: type: AverageValue averageValue: "100" # 行为配置 behavior: scaleDown: stabilizationWindowSeconds: 300 policies: - type: Percent value: 50 periodSeconds: 60 scaleUp: stabilizationWindowSeconds: 0 policies: - type: Percent value: 100 periodSeconds: 15 - type: Pods value: 2 periodSeconds: 15 selectPolicy: Max 4.2 Vertical Pod Autoscaler 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # vpa.yaml - 垂直Pod自动扩缩容 apiVersion: autoscaling.k8s.io/v1 kind: VerticalPodAutoscaler metadata: name: web-vpa spec: targetRef: apiVersion: apps/v1 kind: Deployment name: web-app updatePolicy: updateMode: Auto # Off, Initial, Recreate, Auto resourcePolicy: containerPolicies: - containerName: '*' minAllowed: cpu: 100m memory: 128Mi maxAllowed: cpu: 1 memory: 1Gi controlledResources: ["cpu", "memory"] controlledValues: RequestsAndLimits 五、CI/CD集成 5.1 GitHub Actions CI/CD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 # .github/workflows/deploy-k8s.yml name: Build and Deploy to Kubernetes on: push: branches: [main] pull_request: branches: [main] env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} jobs: build: runs-on: ubuntu-latest permissions: contents: read packages: write steps: - name: Checkout code uses: actions/checkout@v4 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Login to Container Registry 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=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha,prefix={{branch}}- - name: Build and push Docker image uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max - name: Install kubectl uses: azure/setup-kubectl@v3 with: version: 'latest' - name: Configure kubectl run: | echo "${{ secrets.KUBE_CONFIG }}" | base64 -d > kubeconfig export KUBECONFIG=kubeconfig - name: Deploy to Kubernetes run: | # 更新deployment中的镜像 kubectl set image deployment/web-app \ web=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} # 等待部署完成 kubectl rollout status deployment/web-app # 验证部署 kubectl get pods -l app=web 5.2 Helm Charts管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 # Helm Chart values.yaml replicaCount: 3 image: repository: ghcr.io/myorg/myapp pullPolicy: IfNotPresent tag: "v1.0.0" imagePullSecrets: [] service: type: ClusterIP port: 80 targetPort: 3000 ingress: enabled: true className: nginx annotations: cert-manager.io/cluster-issuer: letsencrypt-prod hosts: - host: app.example.com paths: - path: / pathType: Prefix tls: - secretName: app-tls hosts: - app.example.com resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" autoscaling: enabled: true minReplicas: 2 maxReplicas: 10 targetCPUUtilizationPercentage: 70 targetMemoryUtilizationPercentage: 80 database: host: postgres.default.svc.cluster.local port: 5432 name: myapp existingSecret: db-secret 1 2 3 4 5 6 7 8 # 部署Helm Chart helm upgrade --install myapp ./chart \ --namespace production \ --create-namespace \ --values values.yaml \ --set image.tag=${IMAGE_TAG} \ --wait \ --timeout 5m 六、监控与日志 6.1 Prometheus监控 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # ServiceMonitor for Prometheus Operator apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: web-app labels: app: web spec: selector: matchLabels: app: web endpoints: - port: http path: /metrics interval: 30s scrapeTimeout: 10s 6.2 日志收集 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 # Fluentd ConfigMap apiVersion: v1 kind: ConfigMap metadata: name: fluentd-config data: fluent.conf: | <source> @type tail path /var/log/containers/*.log pos_file /var/log/fluentd-containers.log.pos tag kubernetes.* read_from_head true <parse> @type json </parse> </source> <filter kubernetes.**> @type kubernetes_metadata </filter> <match **> @type elasticsearch host elasticsearch.logging.svc.cluster.local port 9200 logstash_format true logstash_prefix k8s </match> 总结 Docker和Kubernetes构建了现代容器化部署的基础: ...

容器部署最佳实践:从Docker到Kubernetes的完整部署指南

深入探讨现代容器化部署的最佳实践,包括Docker容器化、Docker Compose编排、Kubernetes集群管理、CI/CD集成和监控告警,帮助企业构建可靠的容器化应用部署流程。

Docker容器化完全指南:从入门到生产实践

全面掌握Docker容器化技术,从基础概念到生产环境部署的最佳实践。

Docker容器化最佳实践:从开发到生产的完整指南

全面的Docker最佳实践指南,涵盖镜像优化、容器安全、多环境部署、监控告警等关键主题,帮助你构建可靠的容器化应用。

Docker容器化部署完全指南:从入门到生产环境

全面介绍Docker容器化技术,包括基础概念、镜像构建、容器编排、监控日志、安全配置等,并提供生产环境部署的最佳实践

Docker容器化最佳实践:构建高效安全的容器应用

深入探讨Docker容器化的最佳实践,包括多阶段构建、安全配置、性能优化等关键技术,帮助开发者构建企业级容器应用。

Docker 容器化部署完全指南

全面介绍 Docker 容器化的最佳实践,从基础概念到生产部署