Go Web 编程快速入门 13 - 部署与运维:Docker容器化、Kubernetes编排与CI/CD

服务写完只是第一步,稳定、自动化地部署与运维才是走向生产的关键。本章沿用第 04.1 的结构与"可运行模板",提供 Docker 多阶段构建、Compose 本地编排、Kubernetes 核心资源与 GitHub Actions CI/CD 的最小实践。

1 Docker容器化

1.1 多阶段 Dockerfile(最佳实践)

dockerfile 复制代码
# 构建阶段
FROM golang:1.22-alpine AS builder
WORKDIR /app
RUN apk add --no-cache tzdata ca-certificates
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o server ./cmd/server

# 运行阶段
FROM alpine:3.20
RUN apk add --no-cache tzdata ca-certificates
WORKDIR /root
COPY --from=builder /app/server ./server
COPY --from=builder /app/configs ./configs
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget -qO- http://localhost:8080/health || exit 1
ENTRYPOINT ["./server"]

1.2 Docker Compose(本地多服务编排)

yaml 复制代码
version: "3.8"
services:
  gateway:
    build: { context: ., dockerfile: Dockerfile }
    ports: ["8080:8080"]
    environment:
      - ENV=production
      - USER_SERVICE_URL=http://user-service:8081
    depends_on: [user-service]

  user-service:
    build: { context: ., dockerfile: Dockerfile }
    ports: ["8081:8081"]
    environment:
      - ENV=production

2 Kubernetes编排

2.1 Deployment + Service(最小模板)

yaml 复制代码
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gateway
spec:
  replicas: 2
  selector:
    matchLabels: { app: gateway }
  template:
    metadata:
      labels: { app: gateway }
    spec:
      containers:
      - name: gateway
        image: yourrepo/gateway:latest
        ports: [{ containerPort: 8080 }]
        env:
        - name: ENV
          value: production
        resources:
          requests: { cpu: "250m", memory: "256Mi" }
          limits: { cpu: "500m", memory: "512Mi" }
        livenessProbe:
          httpGet: { path: /health, port: 8080 }
          initialDelaySeconds: 30
        readinessProbe:
          httpGet: { path: /health, port: 8080 }
          initialDelaySeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: gateway
spec:
  type: ClusterIP
  selector: { app: gateway }
  ports:
  - name: http
    port: 80
    targetPort: 8080

2.2 配置与机密(ConfigMap/Secret)

yaml 复制代码
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: "info"
---
apiVersion: v1
kind: Secret
metadata:
  name: app-secret
type: Opaque
data:
  DB_PASSWORD: cGFzc3dvcmQ= # base64("password")

3 CI/CD(GitHub Actions 示例)

3.1 构建并推送镜像

yaml 复制代码
name: ci
on: { push: { branches: [ main ] } }
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: "1.22" }
      - name: Build
        run: go build -v ./cmd/server
      - name: Login to Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Build and Push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ghcr.io/yourorg/gateway:latest

3.2 部署到 Kubernetes(可选)

yaml 复制代码
name: cd
on: { workflow_run: { workflows: ["ci"], types: ["completed"], branches: ["main"] } }
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Setup Kubectl
        uses: azure/setup-kubectl@v4
        with: { version: "v1.29.0" }
      - name: Kubeconfig
        run: echo "${{ secrets.KUBECONFIG }}" > kubeconfig && chmod 600 kubeconfig
      - name: Deploy
        run: KUBECONFIG=./kubeconfig kubectl apply -f k8s/

4 完整示例:一键启动到生产路径

  • 本地开发:docker compose up -d 启动多服务并联调。
  • 构建镜像:docker build -t yourrepo/gateway:latest .
  • 推送镜像:docker push yourrepo/gateway:latest
  • 部署集群:准备 k8s/ 资源清单并通过 CI/CD 自动 kubectl apply

通过本章的模板,你能快速建立"从代码到生产"的基础路径。建议逐步引入:灰度发布、滚动升级、观测(Prometheus/Grafana)、日志汇总与告警、金丝雀与回滚策略,以持续提升系统的可运维性与可靠性。

相关推荐
Hi_kenyon2 小时前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
起名时在学Aiifox2 小时前
Vue 3 响应式缓存策略:从页面状态追踪到智能数据管理
前端·vue.js·缓存
正在学习前端的---小方同学2 小时前
Harbor部署教程
linux·运维
奋进的芋圆2 小时前
DataSyncManager 详解与 Spring Boot 迁移指南
java·spring boot·后端
计算机程序设计小李同学3 小时前
个人数据管理系统
java·vue.js·spring boot·后端·web安全
李剑一3 小时前
uni-app实现本地MQTT连接
前端·trae
牛奔3 小时前
Docker Compose 两种安装与使用方式详解(适用于 Docker 19.03 版本)
运维·docker·云原生·容器·eureka
EndingCoder3 小时前
Any、Unknown 和 Void:特殊类型的用法
前端·javascript·typescript
oden3 小时前
代码高亮、数学公式、流程图... Astro 博客进阶全指南
前端