feat: 新增 go 示例(Go 1.23 标准库 Web,两阶段构建)
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
app
|
||||
.git/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,2 @@
|
||||
app
|
||||
/go-demo
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
```
|
||||
Executable
+11
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
module demo
|
||||
|
||||
go 1.22
|
||||
@@ -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 = `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head><meta charset="UTF-8"><title>go demo</title>
|
||||
<style>body{font-family:-apple-system,"PingFang SC",sans-serif;margin:40px;color:#222}
|
||||
table{border-collapse:collapse}th,td{border:1px solid #ddd;padding:6px 12px;text-align:left}th{background:#f5f5f5}</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>go demo 运行信息</h1>
|
||||
<table>
|
||||
<tr><th>go</th><td>%s</td></tr>
|
||||
<tr><th>hostname</th><td>%s</td></tr>
|
||||
<tr><th>time</th><td>%s</td></tr>
|
||||
</table>
|
||||
<p>其他接口:<code>/health</code>、<code>/api/hello?name=x</code></p>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
func writeJSON(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
log.Printf("encode json failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func hostname() string {
|
||||
if h, err := os.Hostname(); err == nil {
|
||||
return h
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func env(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p go-demo down
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
docker-compose -f docker-compose.yml -p go-demo up -d
|
||||
Reference in New Issue
Block a user