# 第 8 章 部署与进阶 > 学完本章你将:编译与部署 Gin 服务,用 Docker 容器化,掌握生产配置与后续学习路线。 ## 8.1 编译与运行 ```bash make build # go build -o bin/streambox ./cmd/server ./bin/streambox # 直接运行二进制 # 交叉编译 GOOS=linux GOARCH=amd64 go build -o bin/streambox-linux ./cmd/server # 运行时配置 SERVER_PORT=9090 LOG_LEVEL=info ./bin/streambox # 或修改 config/config.yaml ``` 二进制无依赖,拷贝到服务器即可运行。 ## 8.2 优雅关闭回顾 `cmd/server/main.go` 已实现: ```go quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() srv.Shutdown(ctx) ``` `Shutdown` 会等待正在处理的请求完成(最多 10 秒),再退出进程,避免 k8s 滚动更新时丢请求。需配合 `ReadTimeout`/`WriteTimeout`(见 `config.yaml`)。 ## 8.3 生产配置 | 项 | 建议 | |----|------| | `server.mode` | `release`(关闭 Gin debug 日志) | | `log.level` | `info` 或 `warn` | | `log.encoding` | `json`(便于日志收集) | | `cors.allow_origins` | 具体域名,不用 `*` | | 端口 | 环境变量 `SERVER_PORT` 覆盖,避免改文件 | 敏感信息(DB 密码、JWT 密钥)务必走环境变量或 Secret,不提交到 Git。参考 `.env.example`。 ## 8.4 Dockerfile ```dockerfile # 构建阶段 FROM golang:1.26-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -o /streambox ./cmd/server # 运行阶段 FROM alpine:3.20 WORKDIR /app COPY --from=builder /streambox /app/streambox COPY config/config.yaml /app/config/config.yaml EXPOSE 8080 CMD ["/app/streambox"] ``` ```bash docker build -t streambox:latest . docker run -p 8080:8080 -e SERVER_PORT=8080 streambox:latest curl http://localhost:8080/health ``` > 若使用 `glebarez/sqlite`(纯 Go 驱动),`CGO_ENABLED=0` 可用;若用 `mattn/go-sqlite3` 需 `CGO_ENABLED=1`。 ## 8.5 反向代理与多实例 生产常在 Gin 前加 Nginx/Caddy 做 TLS、静态资源、限流: ```nginx upstream streambox { server 127.0.0.1:8080; } server { listen 80; location / { proxy_pass http://streambox; } } ``` 多实例用 k8s Deployment + Service,或 systemd 多进程 + LB。 ## 8.6 性能与可观测性 - **pprof**:`import _ "net/http/pprof"` + `r.GET("/debug/pprof/*any", gin.WrapH(http.DefaultServeMux))`(仅内网暴露) - **压测**:`go test -bench`、`wrk`、`hey` - **追踪**:日志中加入 `requestID`(见第 5 章中间件) - **指标**:可接入 Prometheus(`ginprom` 中间件) ## 8.7 下一步学习路线 1. **数据库**:GORM + SQLite/PostgreSQL,事务与迁移 2. **鉴权**:JWT(`golang-jwt/jwt`)+ Casbin(本项目已引入) 3. **文档**:Swagger(`swaggo/gin-swagger` 本项目已引入,`swag init` 生成) 4. **验证**:深入 `validator` 自定义规则 5. **测试**:`httptest` + `testify` 做 handler 集成测试 6. **进阶**:依赖注入(Wire/Fx)、配置中心、消息队列 ## 8.8 常用命令速查 ```bash make run # 开发运行 make build # 编译 make tidy # 整理依赖 make fmt # 格式化 go test ./... # 测试 go vet ./... # 静态检查 curl http://localhost:8080/health ``` --- 至此,Go + Gin 从入门到部署已全部覆盖。建议从第 7 章的 Book CRUD 开始,亲手扩展一个完整模块,遇到问题回查对应章节。