Kubernetes – 设置 Nginx Ingress Controller (Ingress控制器)

假设你的Kubernetes集群中,已经安装了1个服务nginx1

[root@qikegu-centos5 k8s_demo]# kubectl get svc
NAME           TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes     ClusterIP   10.96.0.1       <none>        443/TCP    14d
nginx1         ClusterIP   10.106.165.12   <none>        81/TCP     29m

现在需要配置Ingress路由访问nginx1服务。

安装 Nginx Ingress Controller

1. 安装Kubernetes社区版本的Nginx Ingress Controller

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/static/mandatory.yaml

查看安装结果:

kubectl get pods -n ingress-nginx
NAME                                        READY   STATUS    RESTARTS   AGE
nginx-ingress-controller-568867bf56-7lj9l   1/1     Running   0          97m

2. 部署Ingress Controller服务

Nginx Ingress控制器本身也是一个服务,需要把外部流量接入进来,然后导向后方服务(nginx1)。

注意 此处使用Ingress暴露了内部服务nginx1,但是Nginx Ingress控制器本身也是一个服务,也需要对外暴露,通常使用外部的负载均衡器接入外部流量,此处为简单起见,使用nodePort接入外部流量。

nginx-ingress-svc.yaml

kind: Service
apiVersion: v1
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
spec:
  #externalTrafficPolicy: Local
  #type: LoadBalancer
  type: NodePort
  selector:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
  ports:
    - name: http
      port: 80
      targetPort: 80
      nodePort: 30080
    - name: https
      port: 443
      targetPort: 443
      nodePort: 30443

创建服务:

kubectl apply -f nginx-ingress-svc.yaml

查看创建的服务:

kubectl get svc -n ingress-nginx
NAME            TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
ingress-nginx   NodePort   10.103.202.115   <none>        80:30080/TCP,443:30443/TCP   17m

创建Ingress对象,配置路由

ingress.yaml

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: test-ingress
spec:
  backend:
    serviceName: nginx1
    servicePort: 81

创建Ingress对象:

kubectl create -f ./ingress.yaml

查看Ingress对象:

[root@qikegu-centos5 k8s_demo]# kubectl get ingress
NAME           HOSTS   ADDRESS          PORTS   AGE
test-ingress   *       10.103.202.115   80      52m

访问验证

使用nginx控制器的CLUSTER-IP访问:

curl  10.103.202.115:80

输出


<!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> ...

由于设置了nodePort,也可以使用节点主机名/IP访问:

curl qikegu-knode1:30080


浙ICP备17015664号 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载