如果不想build 或没有镜像仓库,可以直接看5.3的红色内容

1、创建 Go 项目

mkdir test-go
cd test-go
go mod init test-go
go get -u github.com/gin-gonic/gin

2、编写 Gin 简单 API

package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()

    // 定义一个 GET 接口:/hello
    r.GET("/hello", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello World")
    })

    // 监听端口,K8s 中通常用 8080
    r.Run(":8080")
}

3、测试本地运行

go run main.go

打开浏览器或使用curl

curl http://localhost:8080/hello

输出Hello World 

成功!说明代码没问题。

✅ 最终项目结构
test-go/
├── main.go
├── go.mod
├── go.sum
├── Dockerfile
├── k8s.yaml

4、创建 Docker 镜像

 4.1 创建 Dockerfile(在项目根目录)

# 使用官方 Go 镜像作为构建环境
FROM golang:1.24-alpine AS builder

# 设置工作目录
WORKDIR /app

# 复制 go mod 文件
COPY go.mod ./
COPY go.sum ./

# 下载依赖(使用缓存优化)
RUN go mod download

# 复制源码
COPY . .

# 构建二进制文件(静态编译,适合 Alpine)
RUN CGO_ENABLED=0 GOOS=linux go build -o main .

# 最终镜像(轻量)
FROM alpine:latest

RUN apk --no-cache add ca-certificates

WORKDIR /root/

# 从构建阶段复制二进制文件
COPY --from=builder /app/main .

# 声明暴露端口
EXPOSE 8080

# 运行程序
CMD ["./main"]

5、构建并推送 Docker 镜像

5.1登录公司镜像仓库

docker login your-registry.company.com
# 输入用户名密码

5.2构建镜像

docker build -t test-go:v1 .

5.3推送镜像

docker push test-go:v1

✅ 成功后,镜像就在公司仓库中了,K8s 可以拉取。

这里有很多人因为网络原因build失败,没有镜像仓库等这种原因会失败,可以用我build好的,直接使用,省掉前面的1-5步骤。

阿里云镜像仓库:registry.cn-hangzhou.aliyuncs.com/jack8888/test-go:v1

6、编写 Kubernetes 部署文件

在项目根目录创建 k8s.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-go-deployment
  labels:
    app: test-go
spec:
  replicas: 2
  selector:
    matchLabels:
      app: test-go
  template:
    metadata:
      labels:
        app: test-go
    spec:
      containers:
      - name: test-go
        image: registry.cn-hangzhou.aliyuncs.com/jack8888/test-go:v1 #镜像仓库地址
        ports:
        - containerPort: 8080
        resources:
          requests:
            memory: "64Mi"
            cpu: "250m"
          limits:
            memory: "128Mi"
            cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
  name: test-go-service
spec:
  selector:
    app: test-go
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
      nodePort: 30080   #暴漏端口
  type: NodePort

7、部署到 Kubernetes(到master机器操作)

1、确保 kubectl 配置正确

kubectl config current-context
kubectl get nodes

2. 应用部署(需要把k8s.yaml文件传输到master 机器上)

kubectl apply -f k8s.yaml

3. 查看 Pod 状态

kubectl get pods -l app=test-go

等待状态变为 Running

4. 查看 Service

kubectl get svc test-go-service

8、测试服务

 使用 Port Forward 本地测试

kubectl port-forward svc/test-go-service 8080:80

然后浏览器访问任一结点的IP:30080/hello,比如我机器的

http://192.168.31.133:30080/hello

http://192.168.31.134:30080/hello

访问两个地址都会输出

Hello World

至此Kubernetes ,NodePort,访问模式部署成功。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐