Service Mesh - gRPC 本地联调远程服务
anoyi 人气:0
![](https://img2020.cnblogs.com/other/1699441/202003/1699441-20200308135725270-2010436485.png)
## Description
Service Mesh 架构下,服务间调用会通过服务名(Service Name)互相调用,比如在 Kubernetes 、Docker Swarm 集群中,服务 IP 均由集群动态分配,外部网络无法直接访问到集群内部的服务。对于大型系统,微服务的数量较多,服务间的调用关系也错综复杂,遇到问题时,本地启动整个服务集群去 Debug,不仅需要本地电脑有很高的配置,而且操作起来也比较麻烦。比较优雅一点的做法是本地启动相应服务,gRPC 调用都连接到远程集群。
![](https://img2020.cnblogs.com/other/1699441/202003/1699441-20200308135725765-1690359190.png)
## Nginx gRPC Module
Nginx 版本 `1.13.10` 之后支持 gRPC 反向代理,这样我们就能通过在集群中部署 Nginx 服务,来连通外部网络和集群内的服务。
![](https://img2020.cnblogs.com/other/1699441/202003/1699441-20200308135725946-1161991749.png)
## Kubernetes Demo
**1、Deploy gRPC Server In Kubernetes Cluster**
- 首先,在 Kubernetes 集群中部署镜像为 `python:3` 的容器,为下面的代码提供运行环境
- 然后,克隆项目 [https://github.com/ChinaSilence/python-grpc](https://github.com/ChinaSilence/python-grpc),执行 `pip install python-grpc` 安装依赖
- 接着,在 `python-grpc` 目录下执行 `python server/server.py`,观察日志,等待 gRPC server 启动成功
- 最后,创建 Kubernetes Service,暴露 gRPC 服务
```yaml
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 请求的转发能力:
```yaml
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**
- 添加 host 记录:`
加载全部内容