nginx-ingress基於gRPC協議通信
此文檔演示如何通過nginx-ingress將流量路由到gRPC服務上。
環境
環境 | 版本 |
---|---|
kubernetes | 1.17.4 |
Rancher | v2.4.5 |
nginx-ingress | 0.25.1 |
示例
以下gRPC應用基於ingress自帶的示例,您也可以使用自己的gRPC應用進行測試
地址:https://github.com/kubernetes/ingress-nginx/tree/master/docs/examples/grpc
- 部署一個gRPC應用
該應用程序通過go實現gRPC服務,並監聽50051端口
# cat app.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: fortune-teller-app
labels:
k8s-app: fortune-teller-app
namespace: default
spec:
replicas: 1
selector:
matchLabels:
k8s-app: fortune-teller-app
template:
metadata:
labels:
k8s-app: fortune-teller-app
spec:
containers:
- name: fortune-teller-app
image: quay.io/kubernetes-ingress-controller/grpc-fortune-teller:0.1
ports:
- containerPort: 50051
name: grpc
- 部署service,通過selector選擇對應label的pod
# cat svc.yaml
apiVersion: v1
kind: Service
metadata:
name: fortune-teller-service
namespace: default
spec:
selector:
k8s-app: fortune-teller-app
ports:
- port: 50051
targetPort: 50051
name: grpc
- 部署ingress
這里主要設置這個參數來使用gRPC協議:nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
還配置了SSL證書,默認使用ingress頒發的證書
# cat ingress.yaml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
name: fortune-ingress
namespace: default
spec:
rules:
- host: fortune-teller.stack.build
http:
paths:
- backend:
serviceName: fortune-teller-service
servicePort: grpc
tls:
- secretName: fortune-teller.stack.build
hosts:
- fortune-teller.stack.build
- kubectl執行以上文件
# kubectl apply -f app.yaml
# kubectl apply -f svc.yaml
# kubectl apply -f ingress.yaml
- 使用grpcurl測試應用
grpcurl命令下載地址如下:https://github.com/fullstorydev/grpcurl/releases
例如下載 grpcurl_1.6.1_linux_x86_64.tar.gz
# wget https://github.com/fullstorydev/grpcurl/releases/download/v1.6.1/grpcurl_1.6.1_linux_x86_64.tar.gz
# tar -zxvf grpcurl_1.6.1_linux_x86_64.tar.gz
# cp grpcurl /usr/local/bin/grpcurl
測試基於ingress訪問gRPC應用(示例中,message的值會不一樣)
# grpcurl -insecure fortune-teller.stack.build:443 build.stack.fortune.FortuneTeller/Predict
{
"message": "[We] use bad software and bad machines for the wrong things.\n\t\t-- R. W. Hamming"
}