介绍

Ingress 为外部访问集群提供了一个 统一 入口,避免了对外暴露集群端口;
功能类似 Nginx,可以根据域名、路径把请求转发到不同的 Service。
可以配置 https

6.Ingress - 图1

使用

要使用 Ingress,需要一个负载均衡器 + Ingress Controller
如果是裸机(bare metal) 搭建的集群,你需要自己安装一个负载均衡插件,可以安装 metallb
如果是云服务商,会自动给你配置,否则你的外部 IP 会是 “pending” 状态,无法使用。

安装Nginx Ingress Controller

  1. # 部署nginx-ingress-controller
  2. $ kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.2.0/deploy/static/provider/cloud/deploy.yaml
  3. # 等待安装状态
  4. $ kubectl wait --namespace ingress-nginx \
  5. --for=condition=ready pod \
  6. --selector=app.kubernetes.io/component=controller \
  7. --timeout=120s


Nginx示例Ingress
nginx-ingress.yaml

apiVersion: networking.k8s.io/v1      # api版本声明
kind: Ingress                         # 指定创建资源的类型
metadata:                             # 资源的元数据/属性
  name: nginx-ingress                 # ingress名称
  namespace: demo                     # ingress的命名空间
spec:                                 # 资源规格定义
  ingressClassName: nginx             # IngressClass名称
  rules:                              # 路由规则
  - host: demo.lechuang.com           # 域名,填写IP无效
    http:                             # 类型,目前只支持http/tls
      paths:                          # 路由路径
      - backend:                      # 代理的后端配置
          service:
            name: nginx-service       # Service的名称
            port:
              number: 8081            # Service的端口,非nodePort端口
        path: /
        pathType: ImplementationSpecific
#  tls:                               # tls配置
#  - hosts:
#    - demo.lechuang.com
#    secretName: lechuang-com-tls-secret

应用ingress

$ kubectl apply -f nginx-ingress.yaml

访问测试

# 因为是随意指定的域名,先配置hosts
$ echo '192.168.0.230 demo.lechuang.com' > /etc/hosts

# 返回999,表示配置成功
$ curl -w '%{http_code}' http://demo.lechuang.com
999