首先编写监听8080端口的Golang应用,接着构建镜像并推送到仓库,然后创建Deployment部署应用,再根据访问需求选择ClusterIP、NodePort或LoadBalancer类型Service暴露服务,最后通过kubectl应用配置并验证服务可达性。

在使用 Golang 开发的应用部署到 Kubernetes 时,如果希望外部或其他服务能够访问该应用,需要通过 Kubernetes Service 来暴露它。Service 是一种抽象,用于定义一组 Pod 的访问策略以及如何对外提供服务。
确保你的 Golang 应用监听一个端口(例如 8080),并提供 HTTP 接口:
<strong>package main</strong><p><strong>import</strong> (
"fmt"
"net/http"
)</p><p><strong>func</strong> hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from Go app!")
}</p><p><strong>func</strong> main() {
http.HandleFunc("/", hello)
fmt.Println("Server starting on port 8080...")
http.ListenAndServe(":8080", nil)
}这个程序会在 8080 端口启动一个简单的 Web 服务。
创建 Dockerfile:
立即学习“go语言免费学习笔记(深入)”;
<strong>FROM</strong> golang:alpine <strong>AS</strong> builder WORKDIR /app COPY . . RUN go build -o main . <p><strong>FROM</strong> alpine RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --from=builder /app/main . CMD ["./main"]
构建并推送镜像:
编写 deployment.yaml 定义 Pod 部署:
<strong>apiVersion:</strong> apps/v1
<strong>kind:</strong> Deployment
<strong>metadata:</strong>
name: go-app-deployment
<strong>spec:</strong>
replicas: 2
selector:
matchLabels:
app: go-app
template:
metadata:
labels:
app: go-app
spec:
containers:
- name: go-app
image: your-registry/go-app:v1
ports:
- containerPort: 8080根据访问需求选择合适的 Service 类型。常用类型包括 ClusterIP、NodePort 和 LoadBalancer。
ClusterIP(集群内部访问)
内容:使用Bundle在Activity间传递数据、Log与DDMS(查看Log等信息)、Activity生命周期、Android应用开发4使用Service、如何使用服务、服务生命周期、进程生命周期、使用服务进行音乐播放、AndroidUI布局等……
0
<strong>apiVersion:</strong> v1
<strong>kind:</strong> Service
<strong>metadata:</strong>
name: go-app-service
<strong>spec:</strong>
selector:
app: go-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIP该方式只能在集群内通过服务名或 ClusterIP 访问,适用于内部微服务调用。
NodePort(节点端口,供外部测试)
<strong>apiVersion:</strong> v1
<strong>kind:</strong> Service
<strong>metadata:</strong>
name: go-app-service
<strong>spec:</strong>
selector:
app: go-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
nodePort: 30080
type: NodePort外部可通过任意节点 IP 加端口 30080 访问服务(如 http://<node-ip>:30080)。
LoadBalancer(云平台负载均衡器)
<strong>apiVersion:</strong> v1
<strong>kind:</strong> Service
<strong>metadata:</strong>
name: go-app-service
<strong>spec:</strong>
selector:
app: go-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer在 AWS、GCP 或阿里云等环境中,Kubernetes 会自动创建一个外部负载均衡器,并分配公网 IP。
使用 kubectl 部署:
基本上就这些。只要你的 Golang 服务正常运行,Pod 正确打上标签,Service 能通过 selector 找到它们,服务就能被成功暴露。关键是匹配 label 和端口设置。不复杂但容易忽略细节。
以上就是Golang如何使用Kubernetes Service暴露应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号