前置条件:使用 Kubeadm 部署 Kubernetes(K8S) 安装
安装ingress-nginx组件(在master节点执行)
- 通过 ip+port 号进行访问,使用 Service 里的 NodePort 实现,把端口对外暴露
缺陷:一个端口只能使用一次,一个端口对应一个应用,实际使用中都是用域名,根据不同的域名跳转到不同的端口服务中 - Ingress 作为统一入口,不同的域名 关联 Service ,由 Service 关联一组 Pod 实现负载均衡
创建 nginx 应用
# 创建 nginx 应用,对外暴露端口使用 NodePort [root@k8smaster ~]# kubectl create deployment nginx --image=nginx # 对外暴露 80 端口 [root@k8smaster ~]# kubectl expose deployment nginx --port=80 --type=NodePort NAME READY STATUS RESTARTS AGE pod/javademo1-d7856c75c-czv2g 1/1 Running 0 152m pod/javademo1-d7856c75c-n28rs 1/1 Running 0 151m pod/javademo1-d7856c75c-xzqjc 1/1 Running 0 151m pod/nginx-f89759699-5hkdw 1/1 Running 0 26d NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/javademo1 NodePort 10.106.43.46 <none> 8111:31452/TCP 20d service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 26d service/nginx NodePort 10.103.87.81 <none> 80:30339/TCP 26d
访问地址:http://NodeIP:Port
部署 Ingress Controller
https://github.com/kubernetes/ingress-nginx/blob/nginx-0.30.0/deploy/static/
hostNetwork:true 新版的没有这个属性,后面再看
[root@k8smaster ~]# kubectl apply -f ingress-nginx.yaml namespace/ingress-nginx created configmap/nginx-configuration created configmap/tcp-services created configmap/udp-services created serviceaccount/nginx-ingress-serviceaccount created clusterrole.rbac.authorization.k8s.io/nginx-ingress-clusterrole created role.rbac.authorization.k8s.io/nginx-ingress-role created rolebinding.rbac.authorization.k8s.io/nginx-ingress-role-nisa-binding created clusterrolebinding.rbac.authorization.k8s.io/nginx-ingress-clusterrole-nisa-binding created deployment.apps/nginx-ingress-controller created limitrange/ingress-nginx created service/ingress-nginx created #查看 ingress-nginx 的状态(yaml 中 namespace: ingress-nginx) [root@k8smaster ~]# kubectl get pods -n ingress-nginx NAME READY STATUS RESTARTS AGE nginx-ingress-controller-5cb8688798-gspq4 1/1 Running 0 64m [root@k8smaster ~]#
创建 Ingress 规则
ingress-demo.yaml
apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: example-ingress spec: rules: - host: example.ingressdemo.com http: paths: - path: / backend: serviceName: web servicePort: 80
[root@k8smaster ~]# cat ./ingress-demo.yaml apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: example-ingress spec: rules: - host: example.ingressdemo.com http: paths: - path: / backend: serviceName: web servicePort: 80 [root@k8smaster ~]# kubectl apply -f ingress-demo.yaml ingress.networking.k8s.io/example-ingress created [root@k8smaster ~]# kubectl get pods -n ingress-nginx -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES nginx-ingress-controller-5cb8688798-gspq4 1/1 Running 0 18h 10.244.2.39 k8snode2 <none> <none>
修改Host文件
C:\Windows\System32\drivers\etc hosts 文件
10.244.2.39 example.ingressdemo.com
ip地址,对应 kubectl get pods -n ingress-nginx -o wide 命令中的 IP