将Go HTTP服务器容器化:完整Dockerfile实战案例
引言
将应用容器化是云原生开发的关键步骤。本文将完整演示如何将之前编写的 Go HTTP 服务器容器化,从 Dockerfile 编写到镜像构建、运行测试,让你掌握容器化的完整流程。
一、项目准备
1.1 项目结构
http-server/ ├── main.go ├── go.mod ├── go.sum ├── Dockerfile ├── .dockerignore └── README.md1.2 Go HTTP 服务器代码
创建main.go:
packagemainimport("encoding/json""fmt""log""net/http""os""time")typeResponsestruct{Messagestring`json:"message"`Timestamp time.Time`json:"timestamp"`Hostnamestring`json:"hostname"`}funchealthHandler(w http.ResponseWriter,r*http.Request){hostname,_:=os.Hostname()response:=Response{Message:"服务健康",Timestamp:time.Now(),Hostname:hostname,}w.Header().Set("Content-Type","application/json")json.NewEncoder(w).Encode(response)}funchelloHandler(w http.ResponseWriter,r*http.Request){hostname,_:=os.Hostname()response:=Response{Message:"Hello, Docker!",Timestamp:time.Now(),Hostname:hostname,}w.Header().Set("Content-Type","application/json")json.NewEncoder(w)