github编辑

21.7 实战案例:Go/Rust/数据库/微服务

本节通过实际项目案例演示如何为不同类型的应用构建最优化的 Docker 镜像,以及如何使用 Docker Compose 构建完整的开发和生产环境。

21.7.1 Go 应用的最小化镜像构建

Go 语言因其编译为静态二进制和快速启动而特别适合容器化。以下展示如何构建极小的 Go 应用镜像。

超小 Go Web 服务

应用代码(main.go):

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"status":"healthy","version":"1.0.0"}`)
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	hostname, _ := os.Hostname()
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"message":"Hello from %s","version":"1.0.0"}`, hostname)
}

func main() {
	http.HandleFunc("/health", healthHandler)
	http.HandleFunc("/hello", helloHandler)
	http.HandleFunc("/", helloHandler)

	port := ":8080"
	log.Printf("Server starting on %s", port)

	if err := http.ListenAndServe(port, nil); err != nil {
		log.Fatalf("Server failed: %v", err)
	}
}

多阶段 Dockerfile:

构建和测试:

go.mod 和 go.sum 示例:

带依赖的 Go 应用

应用代码(使用 Gin 框架):

优化的 Dockerfile:

21.7.2 Rust 应用的最小化镜像构建

Rust 因其性能和安全性在系统级应用中备受青睐。

应用代码(main.rs):

Cargo.toml:

多阶段构建 Dockerfile:

构建和验证:

21.7.3 数据库容器化最佳实践

PostgreSQL 生产部署

自定义 PostgreSQL 镜像:

初始化脚本(init-db.sql):

健康检查脚本(health-check.sh):

Docker Compose 配置:

性能优化配置:

MySQL/MariaDB 部署

自定义 my.cnf:

Redis 缓存部署

redis.conf 配置:

21.7.4 微服务架构的 Docker Compose 编排

三层微服务架构示例:

nginx.conf 配置:

21.7.5 使用 VS Code Dev Containers

Dev Containers 让整个开发环境容器化,提升团队一致性。

.devcontainer/devcontainer.json:

.devcontainer/Dockerfile:

docker-compose 用于 Dev Containers:

最后更新于