君小黑 2020-03-04
Service Mesh 架构下,服务间调用会通过服务名(Service Name)互相调用,比如在 Kubernetes 、Docker Swarm 集群中,服务 IP 均由集群动态分配,外部网络无法直接访问到集群内部的服务。对于大型系统,微服务的数量较多,服务间的调用关系也错综复杂,遇到问题时,本地启动整个服务集群去 Debug,不仅需要本地电脑有很高的配置,而且操作起来也比较麻烦。比较优雅一点的做法是本地启动相应服务,gRPC 调用都连接到远程集群。
Nginx 版本 1.13.10
之后支持 gRPC 反向代理,这样我们就能通过在集群中部署 Nginx 服务,来连通外部网络和集群内的服务。
1、Deploy gRPC Server In Kubernetes Cluster
python:3
的容器,为下面的代码提供运行环境pip install python-grpc
安装依赖python-grpc
目录下执行 python server/server.py
,观察日志,等待 gRPC server 启动成功kind: Service apiVersion: v1 metadata: name: server-a-service namespace: default spec: ports: - port: 6565 targetPort: 6565 selector: app: server-a
2、Deploy Nginx gRPC Proxy In Kubernetes Cluster
以下内容包含 Nginx Config、Nginx Deployment 和 Nginx Service,提供了 gRPC 请求的转发能力:
apiVersion: v1 kind: ConfigMap metadata: name: nginx-grpc-proxy-config namespace: default data: grpc.conf: | server { listen 6565 http2; server_name server-a-service; location / { grpc_pass grpc://server-a-service.default:6565; } } --- apiVersion: apps/v1 kind: Deployment metadata: name: nginx-grpc-proxy-deployment namespace: default spec: replicas: 1 selector: matchLabels: app: nginx-grpc-proxy template: metadata: labels: app: nginx-grpc-proxy spec: containers: - name: nginx-grpc-proxy image: nginx:1.17 ports: - containerPort: 6565 volumeMounts: - mountPath: /etc/nginx/conf.d/ name: nginx-config volumes: - name: nginx-config configMap: name: nginx-grpc-proxy-config --- kind: Service apiVersion: v1 metadata: name: nginx-grpc-proxy-service namespace: default spec: ports: - port: 6565 targetPort: 6565 nodePort: 30000 selector: app: nginx-grpc-proxy type: NodePort
3、Test Local Client Connect Remote Server
<k8s 公网 IP> server-a-service
pip3 install python-grpc
安装依赖(需要 python3 的环境)python-grpc
下修改文件 client/client.py
servers = [Server('test', '127.0.0.1', 6565)] # 变更为 servers = [Server('test', 'server-a-service', 30000)]
python3 client/client.py
测试远程调用是否正常(示例中包含正常调用和异常调用)多个远程 gRPC 服务如何配置 nginx?
nginx 配置文件中添加多个 server 记录:
server { listen 6565 http2; server_name server-a-service; location / { grpc_pass grpc://server-a-service.default:6565; } } server { listen 6565 http2; server_name server-b-service; location / { grpc_pass grpc://server-b-service.default:6565; } }
本地 host 需要添加相应的记录:
<k8s 公网 IP> server-a-service <k8s 公网 IP> server-b-service