diff --git a/demo/app/go/.dockerignore b/demo/app/go/.dockerignore new file mode 100644 index 0000000..db5bb30 --- /dev/null +++ b/demo/app/go/.dockerignore @@ -0,0 +1,3 @@ +app +.git/ +.DS_Store diff --git a/demo/app/go/.gitignore b/demo/app/go/.gitignore new file mode 100644 index 0000000..64695fc --- /dev/null +++ b/demo/app/go/.gitignore @@ -0,0 +1,2 @@ +app +/go-demo diff --git a/demo/app/go/Dockerfile b/demo/app/go/Dockerfile new file mode 100644 index 0000000..4148f65 --- /dev/null +++ b/demo/app/go/Dockerfile @@ -0,0 +1,22 @@ +# 编译阶段:compile-go123(Go 1.23 + goproxy.cn) +FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-go123 AS build +WORKDIR /src + +# 先只拷贝 go.mod / go.sum 预热依赖层;本示例只用标准库,没有 go.sum 也不影响 +COPY go.mod go.sum* ./ +RUN go mod download + +COPY *.go ./ +# 静态编译:运行镜像里不依赖 glibc 等动态库,也不必带 go 工具链 +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /src/app . + +# 运行阶段:runtime-go123(仅 Go 运行时) +FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-go123 AS runtime +LABEL MAINTAINER="tianjun@odboy.cn" +ENV TimeZone=Asia/Shanghai +ENV APP_PORT=8086 +WORKDIR /home/admin +COPY --from=build /src/app ./app +EXPOSE 8086 +# exec 形式,保证 docker stop 的 SIGTERM 能传到进程 +ENTRYPOINT ["/home/admin/app"] diff --git a/demo/app/go/README.md b/demo/app/go/README.md new file mode 100644 index 0000000..24e2c7d --- /dev/null +++ b/demo/app/go/README.md @@ -0,0 +1,56 @@ +# go 示例 + +演示如何用 `compile-go123` + `runtime-go123` 两阶段构建一个 Go 1.23 Web 服务。只用标准库,无第三方依赖(不需要 `go.sum`)。 + +| 阶段 | 镜像 | 说明 | +| --- | --- | --- | +| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-go123` | Go + `GOPROXY=goproxy.cn`,常见 Makefile / cgo 工具链 | +| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-go123` | 仅 Go 运行时 | + +### 示例内容 + +``` +go/ +├── go.mod # module demo, go 1.22(1.23 镜像可直接编译) +├── main.go # 标准库 net/http:/、/health、/api/hello、/page +├── Dockerfile # 两阶段:compile-go123 -> runtime-go123 +├── build.sh # 构建镜像(PUSH=1 时同时推送) +├── docker-compose.yml # 部署编排(端口 8086,固定 IP 172.31.0.20) +├── startup.sh # docker-compose up -d +└── shutdown.sh # docker-compose down +``` + +### 构建与部署 + +```shell +sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-go . +PUSH=1 sh build.sh # 构建并推送 +sh startup.sh # docker-compose -f docker-compose.yml -p go-demo up -d +``` + +访问: + +```shell +curl http://127.0.0.1:8086/ # {"message":"go demo is running","go":"go1.23.12",...} +curl http://127.0.0.1:8086/health # ok +curl http://127.0.0.1:8086/api/hello?name=demo # {"message":"Hello, demo!",...} +``` + +浏览器打开 http://127.0.0.1:8086/page 可看到 HTML 页面。 + +### 关键点 + +**静态编译**:`CGO_ENABLED=0 go build -trimpath -ldflags="-s -w"`。产物是静态二进制,运行镜像里不需要 glibc 之外的任何东西; +`-trimpath` 去掉本机绝对路径,`-s -w` 去掉符号表与调试信息,镜像更小。 + +**依赖层缓存**:先 `COPY go.mod` 执行 `go mod download`,再 `COPY *.go` 编译;本示例无依赖,换成有依赖的项目时这一步才有意义。 + +**端口**:容器内 8086(`APP_PORT`),避开前面示例占用的 8080-8085。 + +**模板内嵌**:`/page` 的 HTML 以常量写进二进制,运行时不需要额外拷贝文件——这也是 Go 镜像可以只带一个二进制的原因。 + +### 停止 + +```shell +sh shutdown.sh +``` diff --git a/demo/app/go/build.sh b/demo/app/go/build.sh new file mode 100755 index 0000000..4da1501 --- /dev/null +++ b/demo/app/go/build.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成) +set -euo pipefail +cd "$(dirname "$0")" + +IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-go} +docker build -t "${IMAGE}" . + +if [ "${PUSH:-0}" = "1" ]; then + docker push "${IMAGE}" +fi diff --git a/demo/app/go/docker-compose.yml b/demo/app/go/docker-compose.yml new file mode 100644 index 0000000..a80704f --- /dev/null +++ b/demo/app/go/docker-compose.yml @@ -0,0 +1,29 @@ +version: '3.8' + +networks: + go-demo: + ipam: + driver: default + config: + - subnet: "172.31.0.0/24" + +services: + demo: + image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-go # 镜像由 build.sh 构建 + container_name: go-demo + restart: unless-stopped + ports: # 映射端口 + - "8086:8086" + environment: # 设置环境变量,相当于docker run命令中的-e + TZ: Asia/Shanghai + APP_PORT: "8086" + healthcheck: + # 运行镜像自带 net-tools,直接用端口探测,不额外安装 curl + test: ["CMD-SHELL", "netstat -tln | grep -q ':8086 '"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 5s + networks: + go-demo: + ipv4_address: 172.31.0.20 diff --git a/demo/app/go/go.mod b/demo/app/go/go.mod new file mode 100644 index 0000000..2287625 --- /dev/null +++ b/demo/app/go/go.mod @@ -0,0 +1,3 @@ +module demo + +go 1.22 diff --git a/demo/app/go/main.go b/demo/app/go/main.go new file mode 100644 index 0000000..01e98bd --- /dev/null +++ b/demo/app/go/main.go @@ -0,0 +1,121 @@ +package main + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "runtime" + "time" +) + +// 国内时区 UTC+8,容器内 TZ 即使没生效也能输出正确时间 +var tz8 = time.FixedZone("CST", 8*3600) + +var startTime = time.Now() + +func main() { + http.HandleFunc("/", withMethod(info)) + http.HandleFunc("/health", withMethod(health)) + http.HandleFunc("/api/hello", withMethod(hello)) + http.HandleFunc("/page", withMethod(page)) + + port := env("APP_PORT", "8086") + addr := ":" + port + log.Printf("go demo listening on %s (go %s)", addr, runtime.Version()) + // 只注册 GET 路由,其余请求由 default mux 返回 404 + if err := http.ListenAndServe(addr, nil); err != nil { + log.Fatalf("listen failed: %v", err) + } +} + +// withMethod 只放行 GET/HEAD,避免被当作任意方法都能调用的演示 +func withMethod(h func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + h(w, r) + } +} + +func info(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + writeJSON(w, map[string]any{ + "message": "go demo is running", + "go": runtime.Version(), + "os": runtime.GOOS + "/" + runtime.GOARCH, + "hostname": hostname(), + "zoneId": time.Now().In(tz8).Format("-07:00"), + "time": time.Now().In(tz8).Format("2006-01-02 15:04:05 -07:00"), + "uptime": time.Since(startTime).Truncate(time.Second).String(), + }) +} + +func health(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + fmt.Fprintln(w, "ok") +} + +func hello(w http.ResponseWriter, r *http.Request) { + name := r.URL.Query().Get("name") + if name == "" { + name = "demo" + } + writeJSON(w, map[string]any{ + "message": "Hello, " + name + "!", + "time": time.Now().In(tz8).Format("2006-01-02 15:04:05 -07:00"), + }) +} + +// page 返回一个简单的 HTML 页面;模板在编译期以常量嵌入二进制,运行时不需要额外文件 +func page(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + fmt.Fprintf(w, pageHTML, runtime.Version(), hostname(), + time.Now().In(tz8).Format("2006-01-02 15:04:05 -07:00")) +} + +const pageHTML = ` + +
| go | %s |
|---|---|
| hostname | %s |
| time | %s |
其他接口:/health、/api/hello?name=x