Kubernetes 实战:使用 Service 连接前端与后端微服务
website Kubernetes website and documentation repo: 项目地址: https://gitcode.com/gh_mirrors/webs/website
前言
在现代微服务架构中,前后端分离是常见的设计模式。Kubernetes 提供了强大的服务发现和负载均衡机制,使得前后端微服务之间的通信变得简单可靠。本文将详细介绍如何在 Kubernetes 中部署前后端微服务,并通过 Service 实现它们之间的通信。
架构概述
我们将构建一个简单的应用架构:
- 后端服务:一个返回欢迎信息的 Go 应用
- 前端服务:一个 Nginx 服务器,代理请求到后端服务
后端服务部署
创建后端 Deployment
后端应用使用一个简单的 Go 程序,返回 JSON 格式的欢迎信息。我们通过 Deployment 来管理后端 Pod:
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
spec:
selector:
matchLabels:
app: hello
tier: backend
track: stable
replicas: 3
template:
metadata:
labels:
app: hello
tier: backend
track: stable
spec:
containers:
- name: hello
image: "gcr.io/google-samples/hello-go-gke:1.0"
ports:
- containerPort: 80
关键点说明:
- 定义了 3 个副本确保高可用
- 使用特定标签(app: hello, tier: backend)标识 Pod
- 容器暴露 80 端口
创建后端 Service
为了让前端能够访问后端,我们需要创建 Service:
apiVersion: v1
kind: Service
metadata:
name: hello
spec:
selector:
app: hello
tier: backend
ports:
- protocol: TCP
port: 80
targetPort: 80
Service 特点:
- 通过标签选择器关联后端 Pod
- 在集群内部创建 DNS 记录"hello"
- 提供稳定的 IP 地址
前端服务部署
配置 Nginx
前端使用 Nginx 作为反向代理,配置如下:
server {
listen 80;
location / {
proxy_pass http://hello;
}
}
这个配置将所有请求代理到后端 Service "hello"。
创建前端 Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
selector:
matchLabels:
app: hello
tier: frontend
track: stable
replicas: 2
template:
metadata:
labels:
app: hello
tier: frontend
track: stable
spec:
containers:
- name: nginx
image: "nginx:1.19"
ports:
- containerPort: 80
volumeMounts:
- mountPath: "/etc/nginx/conf.d"
name: nginx-config
volumes:
- name: nginx-config
configMap:
name: frontend-nginx-config
注意:
- 使用 ConfigMap 存储 Nginx 配置(生产环境推荐做法)
- 部署 2 个副本保证可用性
创建前端 Service
为了让外部能够访问前端,我们使用 LoadBalancer 类型的 Service:
apiVersion: v1
kind: Service
metadata:
name: frontend
spec:
type: LoadBalancer
selector:
app: hello
tier: frontend
ports:
- protocol: TCP
port: 80
targetPort: 80
关键特性:
- LoadBalancer 类型会自动创建外部负载均衡器
- 将外部流量路由到前端 Pod
验证部署
-
获取前端 Service 的外部 IP:
kubectl get service frontend -w
-
使用 curl 测试:
curl http://<EXTERNAL-IP>
应该看到后端返回的 {"message":"Hello"} 响应。
生产环境建议
- 配置健康检查:为前后端添加 readiness 和 liveness 探针
- 资源限制:为 Pod 设置合理的资源请求和限制
- 自动扩缩:考虑使用 HPA 根据负载自动调整副本数
- 配置分离:使用 ConfigMap 管理应用配置
- 安全加固:配置网络策略限制不必要的访问
清理资源
完成测试后,记得删除创建的资源:
kubectl delete service frontend backend
kubectl delete deployment frontend backend
总结
通过本文,我们学习了如何在 Kubernetes 中:
- 使用 Deployment 部署多副本应用
- 通过 Service 实现服务发现和负载均衡
- 配置前端代理访问后端服务
- 使用 LoadBalancer 暴露服务到集群外部
这种前后端分离的架构可以轻松扩展,适应各种复杂的应用场景。
website Kubernetes website and documentation repo: 项目地址: https://gitcode.com/gh_mirrors/webs/website
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考