Kubernetes 示例
本项目演示了如何使用 Fiber 框架将 Go 应用程序部署到 Kubernetes 集群。
前提条件
确保您已安装以下软件
设置
-
克隆仓库
git clone https://github.com/gofiber/recipes.git
cd recipes/k8s -
安装依赖
go get
-
构建 Docker 镜像
docker build -t fiber-k8s-example .
-
启动 Minikube (如果使用 Minikube)
minikube start
-
将应用程序部署到 Kubernetes
kubectl apply -f deployment.yaml
运行应用程序
-
检查 Pods 状态
kubectl get pods
-
转发端口以访问应用程序
kubectl port-forward svc/fiber-k8s-example 3000:3000
-
通过
http://localhost:3000
访问应用程序。
示例
这里是 Fiber 应用程序的 main.go
示例文件
package main
import (
"log"
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, Kubernetes!")
})
log.Fatal(app.Listen(":3000"))
}
这里是应用程序的 Dockerfile
示例文件
FROM golang:1.24
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY *.go ./
RUN go build -o /fiber-k8s-example
EXPOSE 3000
CMD ["/fiber-k8s-example"]
这里是用于将应用程序部署到 Kubernetes 的 deployment.yaml
示例文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: fiber-k8s-example
spec:
replicas: 2
selector:
matchLabels:
app: fiber-k8s-example
template:
metadata:
labels:
app: fiber-k8s-example
spec:
containers:
- name: fiber-k8s-example
image: fiber-k8s-example:latest
ports:
- containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: fiber-k8s-example
spec:
type: NodePort
selector:
app: fiber-k8s-example
ports:
- protocol: TCP
port: 3000
targetPort: 3000
nodePort: 30001