Kubernetes Ingress 简介

Kubernetes Ingress 简介创建一个 Ingress 资源来定义外部访问的规则

大家好,欢迎来到IT知识分享网。

前言

Ingress 是 Kubernetes 中的一种资源对象,用于管理从集群外部到内部服务的 HTTP 和 HTTPS 路由。它提供了灵活的路由功能、SSL/TLS 终止、负载均衡和虚拟主机支持。Ingress 需要一个 Ingress 控制器来实际处理路由,并且可以通过配置不同的控制器来满足不同的需求,目前公司内在使用微服务项目部署的时候也是使用该组件进行的路由配置,这里做下学习记录,了解基本使用和原理即可。
在这里插入图片描述

一、Ingress是什么?

Ingress 是 Kubernetes 中的一种资源对象,用于管理从集群外部访问集群内服务的 HTTP 和 HTTPS 路由。它提供了一种灵活的方式来定义如何将外部请求路由到集群内部的服务,通常用于暴露 HTTP 和 HTTPS 服务。

  • 为什么使用 Ingress?

    在 Kubernetes 中,虽然可以通过 Service 的类型为 NodePort 或 LoadBalancer 将服务暴露给外部,但 Ingress 提供了更高级和灵活的流量管理功能,包括:

    • 基于主机名和路径的路由:可以根据请求的 URL 路径和主机名将流量路由到不同的服务。
    • TLS/SSL 终止:可以在 Ingress 层处理 SSL/TLS,加密外部到 Ingress 的流量。
    • 负载均衡:可以在多个服务之间分配流量。
    • 虚拟主机:可以在同一个 IP 地址上处理多个域名(虚拟主机)。
  • Ingress 控制器
    Ingress 资源本身并不直接管理流量,它需要一个 Ingress 控制器来实际处理路由。Ingress 控制器是集群中的一个组件,负责根据 Ingress 资源的定义配置负载均衡器或代理服务器。常见的 Ingress 控制器有:
    • NGINX Ingress Controller
    • Traefik
    • HAProxy
    • Istio Ingress Gateway

    我们这里使用了 NGINX Ingress controller。

二、使用步骤

1. 使用 kubectl安装 ingress

➜ ~ kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml namespace/ingress-nginx created serviceaccount/ingress-nginx created serviceaccount/ingress-nginx-admission created role.rbac.authorization.k8s.io/ingress-nginx created role.rbac.authorization.k8s.io/ingress-nginx-admission created clusterrole.rbac.authorization.k8s.io/ingress-nginx created clusterrole.rbac.authorization.k8s.io/ingress-nginx-admission created rolebinding.rbac.authorization.k8s.io/ingress-nginx created rolebinding.rbac.authorization.k8s.io/ingress-nginx-admission created clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx created clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx-admission created configmap/ingress-nginx-controller created service/ingress-nginx-controller created service/ingress-nginx-controller-admission created deployment.apps/ingress-nginx-controller created job.batch/ingress-nginx-admission-create created job.batch/ingress-nginx-admission-patch created ingressclass.networking.k8s.io/nginx created validatingwebhookconfiguration.admissionregistration.k8s.io/ingress-nginx-admission created 

2. 创建部署资源

  • 创建资源
  1. example-deployment.yaml
    定义一个名为 example-deployment 的 Deployment 资源。这个资源会创建并管理一组 Nginx 容器。如下所示:
apiVersion: apps/v1 # API 版本,apps/v1 用于描述 Deployment 资源 kind: Deployment # 资源类型,这里是 Deployment metadata: name: example-deployment # Deployment 的名称 spec: replicas: 2 # 副本数量,这里指定创建 2 个 Pod 实例 selector: matchLabels: app: example # 选择器,匹配具有 app=example 标签的 Pod template: metadata: labels: app: example # Pod 模板的标签,确保 Pod 拥有 app=example 标签 spec: containers: - name: nginx # 容器的名称 image: nginx:latest # 使用的 Docker 镜像,这里是最新版本的 nginx ports: - containerPort: 80 # 容器暴露的端口,这里是 80 端口 
  1. example-service.yaml
    这个 Service 会找到所有带有 app=example 标签的 Pod(即 example-deployment 创建的 2 个 Pod),并将请求转发到这些 Pod 的 80 端口。Service 本身是一个负载均衡器,可以将流量均匀分布到所有匹配的 Pod 上。
apiVersion: v1 # API 版本,v1 用于描述 Service 资源 kind: Service # 资源类型,这里是 Service metadata: name: example-service # Service 的名称 spec: selector: app: example # 选择器,匹配具有 app=example 标签的 Pod ports: - protocol: TCP # 使用的协议,这里是 TCP port: 80 # Service 暴露的端口 targetPort: 80 # 目标容器的端口,Service 会将请求转发到这个端口 
  1. example-ingress.yaml
    在 example-ingress.yaml 中,定义了一个 Ingress 对象,它管理外部访问到集群内服务的 HTTP 和 HTTPS 路由。

将访问 example.local 主机名和 / 路径的 HTTP 请求转发到名为 example-service 的 Service 的 80 端口。Ingress 控制器会根据这些规则配置负载均衡器,并处理外部流量的路由。

apiVersion: networking.k8s.io/v1 # API 版本,networking.k8s.io/v1 用于描述 Ingress 资源 kind: Ingress # 资源类型,这里是 Ingress metadata: name: example-ingress # Ingress 的名称 annotations: nginx.ingress.kubernetes.io/rewrite-target: / # 这是一个 NGINX Ingress 特有的注解,用于将匹配的路径重写为根路径。 spec: rules: - host: example.local # 规则中的主机名 http: paths: - path: / # 路径规则 pathType: Prefix # 路径类型,这里是前缀匹配 backend: service: name: example-service # 后端服务的名称 port: number: 80 # 后端服务的端口 
  • 执行命令
➜ k8s-ingress-demo kubectl apply -f example-deployment.yaml deployment.apps/example-deployment created ➜ k8s-ingress-demo kubectl apply -f example-service.yaml service/example-service created ➜ k8s-ingress-demo kubectl apply -f example-ingress.yaml ingress.networking.k8s.io/example-ingress created 
  • 更新本地 host 映射:
    ➜ k8s-ingress-demo sudo vim /etc/hosts
    127.0.0.1 example.local
  • 验证 Ingress 设置:
    打开浏览器,访问 http://example.local,可以看到 Nginx 的欢迎页面。
    至此,一个 demo就

查看服务的状态

现在我们来看它会启动几个 example-deployment,example-service,example-ingress

查看deployment

# 查看启动了几个deployment,如下,共启动了 2 个 ➜ k8s-ingress-demo k get deployments NAME READY UP-TO-DATE AVAILABLE AGE example-deployment 2/2 2 2 29m nginx-deployment 3/3 3 3 7d7h # 详细查看example-deployment ➜ k8s-ingress-demo kubectl describe deployment example-deployment Name: example-deployment Namespace: default CreationTimestamp: Sat, 22 Jun 2024 16:33:52 +0800 Labels: <none> Annotations: deployment.kubernetes.io/revision: 1 Selector: app=example Replicas: 2 desired | 2 updated | 2 total | 2 available | 0 unavailable StrategyType: RollingUpdate MinReadySeconds: 0 RollingUpdateStrategy: 25% max unavailable, 25% max surge Pod Template: Labels: app=example Containers: nginx: Image: nginx:latest Port: 80/TCP Host Port: 0/TCP Environment: <none> Mounts: <none> Volumes: <none> Conditions: Type Status Reason ---- ------ ------ Available True MinimumReplicasAvailable Progressing True NewReplicaSetAvailable OldReplicaSets: <none> NewReplicaSet: example-deployment-6678c6f87f (2/2 replicas created) Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal ScalingReplicaSet 32m deployment-controller Scaled up replica set example-deployment-6678c6f87f to 2 

查看Pod状态

# 查看pod状态 ➜ k8s-ingress-demo kubectl get pods -l app=example NAME READY STATUS RESTARTS AGE example-deployment-6678c6f87f-7vnfp 1/1 Running 0 34m example-deployment-6678c6f87f-h5jsm 1/1 Running 0 34m # 查看单个pod详情 ➜ k8s-ingress-demo kubectl describe pod example-deployment-6678c6f87f-7vnfp Name: example-deployment-6678c6f87f-7vnfp Namespace: default Priority: 0 Service Account: default Node: docker-desktop/192.168.65.3 Start Time: Sat, 22 Jun 2024 16:33:53 +0800 Labels: app=example pod-template-hash=6678c6f87f Annotations: <none> Status: Running IP: 10.1.0.131 IPs: IP: 10.1.0.131 Controlled By: ReplicaSet/example-deployment-6678c6f87f Containers: nginx: Container ID: docker://e61df1f25e486f85176c4efe03b9bc36f4dac70203b2637 Image: nginx:latest Image ID: docker-pullable://nginx@sha256:9cdf9a6b18cb8eb7fe84aea09bebcb83543d46e Port: 80/TCP Host Port: 0/TCP State: Running Started: Sat, 22 Jun 2024 16:34:34 +0800 Ready: True Restart Count: 0 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-952jq (ro) Conditions: Type Status PodReadyToStartContainers True Initialized True Ready True ContainersReady True PodScheduled True Volumes: kube-api-access-952jq: Type: Projected (a volume that contains injected data from multiple sources) TokenExpirationSeconds: 3607 ConfigMapName: kube-root-ca.crt ConfigMapOptional: <nil> DownwardAPI: true QoS Class: BestEffort Node-Selectors: <none> Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 35m default-scheduler Successfully assigned default/example-deployment-6678c6f87f-7vnfp to docker-desktop Normal Pulling 35m kubelet Pulling image "nginx:latest" Normal Pulled 34m kubelet Successfully pulled image "nginx:latest" in 8.892s (41.029s including waiting) Normal Created 34m kubelet Created container nginx Normal Started 34m kubelet Started container nginx 

查看service状态

➜ k8s-ingress-demo kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE example-service ClusterIP 10.99.210.105 <none> 80/TCP 38m kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 21d nginx-service LoadBalancer 10.110.142.82 localhost 80:30452/TCP 7d7h # 查看更详细的信息 ➜ k8s-ingress-demo kubectl describe service example-service Name: example-service Namespace: default Labels: <none> Annotations: <none> Selector: app=example Type: ClusterIP IP Family Policy: SingleStack IP Families: IPv4 IP: 10.99.210.105 IPs: 10.99.210.105 Port: <unset> 80/TCP TargetPort: 80/TCP Endpoints: 10.1.0.130:80,10.1.0.131:80 Session Affinity: None Events: <none> 

查看Ingress状态

➜ k8s-ingress-demo kubectl get ingresses NAME CLASS HOSTS ADDRESS PORTS AGE example-ingress <none> example.local 80 37m ➜ k8s-ingress-demo kubectl get ingress example-ingress NAME CLASS HOSTS ADDRESS PORTS AGE example-ingress <none> example.local 80 38m # 查看更详细的 ingress 状态 ➜ k8s-ingress-demo kubectl describe ingress example-ingress Name: example-ingress Labels: <none> Namespace: default Address: Ingress Class: <none> Default backend: <default> Rules: Host Path Backends ---- ---- -------- example.local / example-service:80 (10.1.0.130:80,10.1.0.131:80) Annotations: nginx.ingress.kubernetes.io/rewrite-target: / Events: <none> 

清理不需要的资源

➜ k8s-demo k get pods NAME READY STATUS RESTARTS AGE example-deployment-6678c6f87f-7vnfp 1/1 Running 0 52m example-deployment-6678c6f87f-h5jsm 1/1 Running 0 52m nginx-deployment-765d7cffb-5zv7k 1/1 Running 7 (4d17h ago) 7d7h nginx-deployment-765d7cffb-dl6p4 1/1 Running 7 (4d17h ago) 7d7h nginx-deployment-765d7cffb-nsckc 1/1 Running 7 (4d17h ago) 7d7h 

我们看这里有我上次测试的nginx-deployment部署资源,而且还启动了 3 个 pod,有点费资源,我现在查看明细。

➜ k8s-demo kubectl get deployment nginx-deployment -o yaml apiVersion: apps/v1 kind: Deployment metadata: annotations: deployment.kubernetes.io/revision: "1" kubectl.kubernetes.io/last-applied-configuration: | { 
   "apiVersion":"apps/v1","kind":"Deployment","metadata":{ 
   "annotations":{ 
   },"labels":{ 
   "app":"nginx"},"name":"nginx-deployment","namespace":"default"},"spec":{ 
   "replicas":3,"selector":{ 
   "matchLabels":{ 
   "app":"nginx"}},"template":{ 
   "metadata":{ 
   "labels":{ 
   "app":"nginx"}},"spec":{ 
   "containers":[{ 
   "image":"nginx:1.17.1","name":"nginx","ports":[{ 
   "containerPort":80}]}]}}}} creationTimestamp: "2024-06-15T01:36:46Z" generation: 1 labels: app: nginx name: nginx-deployment namespace: default resourceVersion: "66130" uid: 988e5ed1-453b-4a62-97bf-25f879be893e spec: progressDeadlineSeconds: 600 replicas: 3 revisionHistoryLimit: 10 selector: matchLabels: app: nginx ....... 

这里有完整 YAML 定义,这是之前创建 pod,给个 3 个副本做演示使用的,没有什么用来,现在删除。

➜ k8s-demo kubectl get pods
NAME READY STATUS RESTARTS AGE
example-deployment-6678c6f87f-7vnfp 1/1 Running 0 57m
example-deployment-6678c6f87f-h5jsm 1/1 Running 0 57m

➜ k8s-demo kubectl get events --sort-by=.metadata.creationTimestamp LAST SEEN TYPE REASON OBJECT MESSAGE 58m Normal Scheduled pod/example-deployment-6678c6f87f-7vnfp Successfully assigned default/example-deployment-6678c6f87f-7vnfp to docker-desktop 58m Normal Pulling pod/example-deployment-6678c6f87f-7vnfp Pulling image "nginx:latest" 58m Normal ScalingReplicaSet deployment/example-deployment Scaled up replica set example-deployment-6678c6f87f to 2 58m Normal SuccessfulCreate replicaset/example-deployment-6678c6f87f Created pod: example-deployment-6678c6f87f-7vnfp 58m Normal SuccessfulCreate replicaset/example-deployment-6678c6f87f Created pod: example-deployment-6678c6f87f-h5jsm 58m Normal Scheduled pod/example-deployment-6678c6f87f-h5jsm Successfully assigned default/example-deployment-6678c6f87f-h5jsm to docker-desktop 58m Normal Pulling pod/example-deployment-6678c6f87f-h5jsm Pulling image "nginx:latest" 57m Normal Pulled pod/example-deployment-6678c6f87f-h5jsm Successfully pulled image "nginx:latest" in 32.14s (32.141s including waiting) 57m Normal Created pod/example-deployment-6678c6f87f-h5jsm Created container nginx 57m Normal Started pod/example-deployment-6678c6f87f-h5jsm Started container nginx 57m Normal Started pod/example-deployment-6678c6f87f-7vnfp Started container nginx 57m Normal Created pod/example-deployment-6678c6f87f-7vnfp Created container nginx 57m Normal Pulled pod/example-deployment-6678c6f87f-7vnfp Successfully pulled image "nginx:latest" in 8.892s (41.029s including waiting) 56s Normal Killing pod/nginx-deployment-765d7cffb-5zv7k Stopping container nginx 56s Normal Killing pod/nginx-deployment-765d7cffb-dl6p4 Stopping container nginx 56s Normal Killing pod/nginx-deployment-765d7cffb-nsckc Stopping container nginx 

三、 Ingress 的工作原理

Ingress 是 Kubernetes 中的一种资源,用于管理从集群外部访问集群内部服务的 HTTP 和 HTTPS 路由。它的工作原理涉及多个组件和步骤,包括 Ingress 控制器、负载均衡、路由规则等。以下是 Ingress 的工作原理详细解释:

1. 定义 Ingress 资源

创建一个 Ingress 资源来定义外部访问的规则。这些规则包括主机名、路径、目标服务等。

apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: example-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - host: example.local http: paths: - path: / pathType: Prefix backend: service: name: example-service port: number: 80 

在这个示例中,Ingress 定义了将 example.local 主机名下的 / 路径的请求路由到名为 example-service 的 Service 的 80 端口。

2. 部署 Ingress 控制器

Ingress 控制器是一个运行在 Kubernetes 集群中的组件,它负责解释和实现 Ingress 资源中的规则。常见的 Ingress 控制器包括 NGINX、Traefik、HAProxy、Istio 等。

安装 NGINX Ingress 控制器的示例命令:

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml 

3. Ingress 控制器的工作

3.1 监听 Ingress 资源变化

Ingress 控制器会监控 Kubernetes 集群中的 Ingress 资源的变化。一旦检测到新的 Ingress 资源或已有资源的更新,它会自动重新配置自己以匹配这些变化。

3.2 配置负载均衡器

根据 Ingress 资源定义的规则,Ingress 控制器会配置其内部的负载均衡器或代理服务器(例如 NGINX)。这包括设置主机名、路径匹配规则、后端服务等。

3.3 处理流量

Ingress 控制器接收到外部流量时,会根据配置的规则将流量路由到相应的后端服务。具体的流程如下:

  • 解析主机名:根据请求的主机名,确定应该使用的 Ingress 规则。
  • 路径匹配:根据请求的路径,找到最匹配的路径规则。
  • 转发请求:将请求转发到对应的后端服务和端口。

4. TLS/SSL 终止

Ingress 可以配置 TLS/SSL 终止,确保外部流量以加密方式传输到 Ingress 控制器,然后在 Ingress 控制器处解密,再转发到后端服务。示例如下:

apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: example-ingress spec: tls: - hosts: - example.local secretName: example-tls rules: - host: example.local http: paths: - path: / pathType: Prefix backend: service: name: example-service port: number: 80 

在这个示例中,example-tls 是一个包含 TLS 证书和私钥的 Kubernetes Secret。

5. 高可用和扩展

Ingress 控制器本身通常作为 Deployment 运行,具有高可用性和可扩展性。你可以调整副本数来扩展 Ingress 控制器的容量,确保其能够处理大量的外部请求。

6. 集群内部的通信

当 Ingress 控制器决定将流量转发到后端服务时,它会使用 Kubernetes Service 进行服务发现和负载均衡。Service 会根据标签选择器找到相应的 Pod,并将请求分发给这些 Pod。

总结

本文主要讲解了 ingress 的基本介绍和使用 demo,最后将工作原理总如如下六大部分。

Ingress 的工作原理涉及以下关键步骤和组件:

  1. 定义 Ingress 资源:定义外部访问规则。
  2. 部署 Ingress 控制器:安装和配置 Ingress 控制器。
  3. Ingress 控制器的工作
    • 监听 Ingress 资源变化。
    • 配置内部负载均衡器或代理服务器。
    • 处理外部流量并路由到后端服务。
  4. TLS/SSL 终止:处理加密流量。
  5. 高可用和扩展:通过 Deployment 提供高可用性和扩展能力。
  6. 集群内部的通信:使用 Kubernetes Service 进行服务发现和负载均衡。

通过以上机制,Ingress 提供了一种灵活、高效的方式来管理 Kubernetes 集群中服务的外部访问。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/147391.html

(0)
上一篇 2025-04-07 21:00
下一篇 2025-04-07 21:10

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信