讓nginx-controller使用external 80 port

在寫k8s使用nginx-controller的時候出現404這篇文章的時候

當時使用了NodePort去當Nginx-Controller的endpoint

設定檔如下

apiVersion: v1
kind: Service
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
spec:
  type: NodePort
  ports:
  - name: http
    port: 80
    targetPort: 80
    protocol: TCP
  - name: https
    port: 443
    targetPort: 443
    protocol: TCP
  selector:
    app: ingress-nginx

這樣有個問題,就是NodePort會隨機選一個port當做Nginx-Controller的出口

這樣一來每次restart就會不知道是什麼port

雖然我可以直接設定NodePort為80 port,但是k8s port range預設範圍是30000~32767

沒辦法指定80 port當作node port的設定

後來重新去看了官方文件,可以直接把type: NodePort改成type: LoadBalancer

這樣一來預設出口就是80 port了

檢查一下controller的endpoint

$ kubectl describe svc ingress-nginx -n ingress-nginx
Name:                     ingress-nginx
Namespace:                ingress-nginx
Labels:                   <none>
Annotations:              <none>
Selector:                 app=ingress-nginx
Type:                     LoadBalancer
IP:                       10.110.43.7
Port:                     http  80/TCP
TargetPort:               80/TCP
NodePort:                 http  31144/TCP
Endpoints:                10.46.0.6:80
Port:                     https  443/TCP
TargetPort:               443/TCP
NodePort:                 https  30474/TCP
Endpoints:                10.46.0.6:443
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

哎呀,拿到的IP是一個k8s的內部的IP,如次一來外面就無法存取了

後來查了一下可以替他設定externalIP,當作endpoint

修改了一下Nginx-Controller的endpoint設定

apiVersion: v1
kind: Service
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
spec:
  type: LoadBalancer
  externalIPs:
  - 你的external IP or VIP
  ports:
  - name: http
    port: 80
    targetPort: 80
    protocol: TCP
  - name: https
    port: 443
    targetPort: 443
    protocol: TCP
  selector:
    app: ingress-nginx

在重新檢查一下controller的endpoint

$ kubectl describe svc ingress-nginx -n ingress-nginx
Name:                     ingress-nginx
Namespace:                ingress-nginx
Labels:                   <none>
Annotations:              <none>
Selector:                 app=ingress-nginx
Type:                     LoadBalancer
IP:                       10.110.43.7
External IPs:             xxx.xxx.xxx.xxx
Port:                     http  80/TCP
TargetPort:               80/TCP
NodePort:                 http  31144/TCP
Endpoints:                10.46.0.6:80
Port:                     https  443/TCP
TargetPort:               443/TCP
NodePort:                 https  30474/TCP
Endpoints:                10.46.0.6:443
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

多了一個External IPs的設定

將service type改成LoadBalancer,然後設定externalIPs就可以讓Nginx-Controller使用external 80 port了

今天玩了一下這設定,總算有比較清楚service設定LoadBalancer的效果

comments powered by Disqus