这是一个完整的 Go 应用 Kubernetes 部署示例,包含 GitHub Actions CI/CD 配置。
- ✅ Go HTTP 服务器
- ✅ Docker 多阶段构建
- ✅ GitHub Actions CI/CD
- ✅ 自动构建和推送镜像到 GitHub Container Registry
- ✅ 自动部署到 Kubernetes
# 运行应用
CGO_ENABLED=0 go run main.go
# 或构建后运行
CGO_ENABLED=0 go build -o hello-go main.go
./hello-godocker build -t hello-go:latest .
docker run -p 8080:8080 hello-go:latest在 GitHub 仓库 Settings > Secrets and variables > Actions 中添加:
- KUBECONFIG: Kubernetes 集群配置(base64 编码)
cat ~/.kube/config | base64
- KUBERNETES_NAMESPACE (可选): 目标命名空间,默认为
default
编辑 k8s/deployment.yaml,将 OWNER 替换为你的 GitHub 用户名或组织名:
image: ghcr.io/jaxgg/hello-go:latestkubectl apply -f k8s/deployment.yaml
kubectl get pods -l app=hello
kubectl get svc hello# 如果使用 NodePort
kubectl port-forward svc/hello 8080:8080- Push 到 main/master: 构建镜像并自动部署
- Pull Request: 仅构建镜像,不部署
在 GitHub Actions 页面可以手动运行 workflow。
.
├── .github/
│ └── workflows/
│ └── ci-cd.yml # GitHub Actions CI/CD 配置
├── k8s/
│ └── deployment.yaml # Kubernetes 部署配置
├── Dockerfile # Docker 镜像构建文件
├── main.go # Go 应用主文件
└── go.mod # Go 模块配置
默认使用 GitHub Container Registry (ghcr.io),如需使用 Docker Hub:
- 修改
.github/workflows/ci-cd.yml中的REGISTRY为docker.io - 添加
DOCKER_USERNAME和DOCKER_PASSWORDsecrets - 更新登录步骤使用 Docker Hub 凭据