Kubernetes 提供了两种负载均衡的机制用于发布公共服务,一种是工作在传输层的Service资源,一种是Ingress资源。前者只能实现”TCP负载均衡”,而无法实现 HTTPS 协议,而Ingress 的出现为我们提供了应用层HTTP(S)的访问能力。
部署 Ingress Controller
Ingress 是 Kubernetes API 的标准类型资源,它是一组 基于DNS 名称或者 URL 路径把用户请求转发到指定的Service资源的规则,用于将集群外部的请求流量转发至集群内部完成服务发布。然而, Ingress 本身并不能进行流量转发,它仅仅是一组路由规则,如果想要真正的使这对规则生效,则需要先部署 Ingress 的控制器,Ingress 控制器能够监听某一个套接字,然后根据Ingress上的路由规则对用户的请求进行转发。
~]# kubectl apply -f https://raw.githubusercontent.com/imirsh/kubernetes/master/mainfests/ingress-nginx/v0.33.0/deploy.yaml
验证安装
确认 ingress controller pods 是否启动
~]# kubectl get pods -n ingress-nginx -l app.kubernetes.io/name=ingress-nginx --watch
NAME READY STATUS RESTARTS AGE
ingress-nginx-admission-create-hh2ht 0/1 Completed 0 20m
ingress-nginx-admission-patch-9npbv 0/1 Completed 0 20m
ingress-nginx-controller-566d9467c5-8lssn 1/1 Running 0 20m
~]# kubectl get svc -n ingress-nginx
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
ingress-nginx-controller NodePort 10.103.127.175 80:30080/TCP,443:30443/TCP 21m
ingress-nginx-controller-admission ClusterIP 10.98.11.81 443/TCP 21m
测试http 7层负载
部署了完 ingress-nginx后,部署了一个 deployment,并它创建了一个名为 myapp-svc-v1 的 service:
~]# vim myapp-deploy.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: deploy-http-v1
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: myapp-v1
version: v1
template:
metadata:
namespace: default
labels:
app: myapp-v1
version: v1
spec:
containers:
- name: myapp-v1
image: ikubernetes/myapp:v1
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: myapp-svc-v1
namespace: default
labels:
app: myapp-v1
version: v1
spec:
type: ClusterIP
selector:
app: myapp-v1
version: v1
ports:
- name: http
port: 80
protocol: TCP
targetPort: 80
然后创建对应的一个ingress对象来暴露集群里这个 deployment 的 http 服务:
~]# vim ingress-myapp.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-myapp-v1
annotations:
kubernetes.io/ingress.class: "nginx"
spec:
rules:
- host: myapp-v1.linux.io
http:
paths:
- path: /
backend:
serviceName: myapp-svc-v1
servicePort: 80
hosts 文件解析后,即可通过域名访问了
~]# curl http://myapp-v1.linux.io:30080/
Hello MyApp | Version: v1 | Pod Name