Service详解【六】

文章目录

  • 6. Service详解
    • 6.1 Service介绍
    • 6.2 Service类型
    • 6.3 Service使用
      • 6.3.1 实验环境准备
      • 6.3.2 ClusterIP类型的Service
      • 6.3.3 HeadLiness类型的Service
      • 6.3.4 NodePort类型的Service
      • 6.3.5 LoadBalancer类型的Service
      • 6.3.6 ExternalName类型的Service
    • 6.4 Ingress介绍
    • 6.5 Ingress使用
      • 6.5.1 环境准备
      • 6.5.2 Http代理
      • 6.5.3 Https代理

6. Service详解

6.1 Service介绍

在kubernetes中,pod是应用程序的载体,我们可以通过pod的ip来访问应用程序,但是pod的ip地址不是固定的,这也就意味着不方便直接采用pod的ip对服务进行访问。

为了解决这个问题,kubernetes提供了Service资源,Service会对提供同一个服务的多个pod进行聚合,并且提供一个统一的入口地址。通过访问Service的入口地址就能访问到后面的pod服务。
在这里插入图片描述

Service在很多情况下只是一个概念,真正起作用的其实是kube-proxy服务进程,每个Node节点上都运行着一个kube-proxy服务进程。当创建Service的时候会通过api-server向etcd写入创建的service的信息,而kube-proxy会基于监听的机制发现这种Service的变动,然后它会将最新的Service信息转换成对应的访问规则

在这里插入图片描述

# 10.98.132.219:80 是service提供的访问入口
# 当访问这个入口的时候,可以发现后面有三个pod的服务在等待调用,
# kube-proxy会基于rr(轮询)的策略,将请求分发到其中一个pod上去
# 这个规则会同时在集群内的所有节点上都生成,所以在任何一个节点上访问都可以。
[root@k8s-master ~]# ipvsadm -Ln
TCP  10.98.132.219:80 rr
  -> 10.244.1.74:80               Masq    1      0          0         
  -> 10.244.1.75:80               Masq    1      0          0         
  -> 10.244.2.39:80               Masq    1      0          0  

kube-proxy目前支持三种工作模式:

userspace 模式

userspace模式下,kube-proxy会为每一个Service创建一个监听端口,发向Cluster IP的请求被Iptables规则重定向到kube-proxy监听的端口上,kube-proxy根据LB算法选择一个提供服务的Pod并和其建立链接,以将请求转发到Pod上。 该模式下,kube-proxy充当了一个四层负责均衡器的角色。由于kube-proxy运行在userspace中,在进行转发处理时会增加内核和用户空间之间的数据拷贝,虽然比较稳定,但是效率比较低。

在这里插入图片描述

iptables 模式

iptables模式下,kube-proxy为service后端的每个Pod创建对应的iptables规则,直接将发向Cluster IP的请求重定向到一个Pod IP。 该模式下kube-proxy不承担四层负责均衡器的角色,只负责创建iptables规则。该模式的优点是较userspace模式效率更高,但不能提供灵活的LB策略,当后端Pod不可用时也无法进行重试。

在这里插入图片描述

ipvs 模式

ipvs模式和iptables类似,kube-proxy监控Pod的变化并创建相应的ipvs规则。ipvs相对iptables转发效率更高。除此以外,ipvs支持更多的LB算法。

在这里插入图片描述

# 此模式必须安装ipvs内核模块,否则会降级为iptables
# 开启ipvs
[root@k8s-master ~]# kubectl edit configmap kube-proxy -n kube-system  # 修改mode: "ipvs"
configmap/kube-proxy edited


[root@k8s-master ~]# kubectl get pod -n kube-system -w | grep kube-proxy
kube-proxy-5khd8                     1/1     Running   7 (23m ago)   6d17h
kube-proxy-slgjr                     1/1     Running   7 (23m ago)   6d17h
kube-proxy-wbvk4                     1/1     Running   7 (23m ago)   6d17h


[root@k8s-master ~]# kubectl get pod -n kube-system --show-labels | grep kube-proxy
kube-proxy-5khd8                     1/1     Running   7 (26m ago)   6d17h   controller-revision-hash=5794bbcc88,k8s-app=kube-proxy,pod-template-generation=1
kube-proxy-slgjr                     1/1     Running   7 (27m ago)   6d17h   controller-revision-hash=5794bbcc88,k8s-app=kube-proxy,pod-template-generation=1
kube-proxy-wbvk4                     1/1     Running   7 (26m ago)   6d17h   controller-revision-hash=5794bbcc88,k8s-app=kube-proxy,pod-template-generation=1
[root@k8s-master ~]# 

# 删除kube-proxy 里的标签:k8s-app=kube-proxy
[root@k8s-master ~]# kubectl delete pod -l k8s-app=kube-proxy -n kube-system
pod "kube-proxy-5khd8" deleted
pod "kube-proxy-slgjr" deleted
pod "kube-proxy-wbvk4" deleted
[root@k8s-master ~]#

[root@k8s-master ~]# ipvsadm -Ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  10.96.0.1:443 rr
  -> 10.10.10.148:6443            Masq    1      0          0         
TCP  10.96.0.10:53 rr
  -> 10.244.0.16:53               Masq    1      0          0         
  -> 10.244.0.17:53               Masq    1      0          0         
TCP  10.96.0.10:9153 rr
  -> 10.244.0.16:9153             Masq    1      0          0         
  -> 10.244.0.17:9153             Masq    1      0          0         
TCP  10.106.59.48:443 rr
  -> 10.244.2.93:4443             Masq    1      0          0         
UDP  10.96.0.10:53 rr
  -> 10.244.0.16:53               Masq    1      0          0         
  -> 10.244.0.17:53               Masq    1      0          0         
[root@k8s-master ~]# 

在这里插入图片描述

6.2 Service类型

Service的资源清单文件:

apiVersion: v1  # 资源版本
kind: Service  #  资源类型
metadata: # 元数据
  name: service-name # 资源名称
  namespace: dev # 命名空间
spec: # 描述
  selector: # 标签选择器,用于确定当前service代理哪些pod
    app: nginx
  type: # Service类型,指定service的访问方式
  clusterIP:  # 虚拟服务的ip地址
  sessionAffinity: # session亲和性,支持ClientIP、None两个选项
  ports: # 端口信息
    - protocol: TCP 
      port: 3017  # service端口
      targetPort: 5003 # pod端口
      nodePort: 31122 # 主机端口
  • ClusterIP:默认值,它是Kubernetes系统自动分配的虚拟IP,只能在集群内部访问
  • NodePort:将Service通过指定的Node上的端口暴露给外部,通过此方法,就可以在集群外部访问服务
  • LoadBalancer:使用外接负载均衡器完成到服务的负载分发,注意此模式需要外部云环境支持
  • ExternalName: 把集群外部的服务引入集群内部,直接使用

6.3 Service使用

6.3.1 实验环境准备

在使用service之前,首先利用Deployment创建出3个pod,注意要为pod设置app=service-deployment的标签

创建deployment.yaml,内容如下:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: service-deployment
  namespace: dev
spec:
  replicas: 3
  selector:
    matchLabels:
      app: service-deployment
  template:
    metadata:
      labels:
        app: service-deployment
    spec:
      containers:
      - name: nginx-containers
        image: nginx:1.20.0
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
          protocol: "TCP"
[root@k8s-master deployment]# pwd
/root/inventory/deployment
[root@k8s-master deployment]# 
[root@k8s-master deployment]# kubectl apply -f service-deployment.yaml 
deployment.apps/service-deployment created


# 查看pod详情
[root@k8s-master deployment]# kubectl get pod -n dev --show-labels
NAME                                  READY   STATUS    RESTARTS   AGE   LABELS
service-deployment-788d874977-tgqfn   1/1     Running   0          20s   app=service-deployment,pod-template-hash=788d874977
service-deployment-788d874977-tpfkp   1/1     Running   0          20s   app=service-deployment,pod-template-hash=788d874977
service-deployment-788d874977-wz48l   1/1     Running   0          20s   app=service-deployment,pod-template-hash=788d874977
[root@k8s-master deployment]# 

[root@k8s-master ~]# kubectl get pod -n dev -o wide
NAME                                  READY   STATUS    RESTARTS   AGE    IP             NODE        ······
service-deployment-788d874977-tgqfn   1/1     Running   0          4m8s   10.244.2.94    k8s-node2   ······
service-deployment-788d874977-tpfkp   1/1     Running   0          4m8s   10.244.1.102   k8s-node1   ······
service-deployment-788d874977-wz48l   1/1     Running   0          4m8s   10.244.1.103   k8s-node1   ······
[root@k8s-master ~]# 


# 为了方便后面的测试,修改下三台nginx的index.html页面(三台修改的IP地址不一致)
# kubectl exec -it service-deployment-788d874977-tgqfn -n dev /bin/sh
# echo "10.244.2.94" > /usr/share/nginx/html/index.html

[root@k8s-master ~]# kubectl exec service-deployment-788d874977-tgqfn -itn dev -- /bin/bash
root@service-deployment-788d874977-tgqfn:/# echo '10.244.2.94' > /usr/share/nginx/html/index.html 
root@service-deployment-788d874977-tgqfn:/# exit
exit

# -c  指定容器名字 ; -it 交互模式 ; -n 指定名称空间 
[root@k8s-master ~]# kubectl exec service-deployment-788d874977-tpfkp -c nginx-containers -itn dev -- /bin/bash
root@service-deployment-788d874977-tpfkp:/# echo '10.244.1.102' > /usr/share/nginx/html/index.html 
root@service-deployment-788d874977-tpfkp:/# exit
exit
[root@k8s-master ~]# kubectl exec service-deployment-788d874977-wz48l -c nginx-containers -itn dev -- /bin/bash
root@service-deployment-788d874977-wz48l:/# echo '10.244.1.103' > /usr/share/nginx/html/index.html 
root@service-deployment-788d874977-wz48l:/# exit
exit
[root@k8s-master ~]# 



#修改完毕之后,访问测试
[root@k8s-master ~]# curl 10.244.2.94
10.244.2.94
[root@k8s-master ~]# curl 10.244.1.102
10.244.1.102
[root@k8s-master ~]# curl 10.244.1.103
10.244.1.103
[root@k8s-master ~]# 

6.3.2 ClusterIP类型的Service

创建service-clusterip.yaml文件

apiVersion: v1
kind: Service
metadata:
  name: service-cluster
  namespace: dev
spec:
  selector:
    app: service-deployment
  clusterIP: 10.98.132.219  # service的ip地址,如果不写,默认会生成一个
  type: ClusterIP
  ports:
  - port: 80  # Service端口    
    targetPort: 80  # pod端口
# 创建service
[root@k8s-master service]# pwd
/root/inventory/service
[root@k8s-master service]# kubectl apply -f service-clusterip.yaml 
service/service-cluster created

# 查看service
[root@k8s-master service]# kubectl get service -n dev -o wide
NAME              TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE   SELECTOR
service-cluster   ClusterIP   10.98.132.219   <none>        80/TCP    12s   app=service-deployment



# 查看service的详细信息
# 在这里有一个Endpoints列表,里面就是当前service可以负载到的服务入口
[root@k8s-master service]# kubectl describe service service-cluster -n dev
Name:              service-cluster
Namespace:         dev
Labels:            <none>
Annotations:       <none>
Selector:          app=service-deployment
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.98.132.219
IPs:               10.98.132.219
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.102:80,10.244.1.103:80,10.244.2.94:80
Session Affinity:  None
Events:            <none>
[root@k8s-master service]# 

# 查看ipvs的映射规则
[root@k8s-master ~]# ipvsadm -Ln
TCP  10.98.132.219:80 rr
  -> 10.244.1.102:80              Masq    1      0          0         
  -> 10.244.1.103:80              Masq    1      0          0         
  -> 10.244.2.94:80               Masq    1      0          0
  
  
# 访问10.98.132.219:80观察效果。负载均衡
[root@k8s-master ~]# curl 10.98.132.219
10.244.2.94
[root@k8s-master ~]# curl 10.98.132.219
10.244.1.103
[root@k8s-master ~]# curl 10.98.132.219
10.244.1.102
[root@k8s-master ~]# curl 10.98.132.219
10.244.2.94
[root@k8s-master ~]# curl 10.98.132.219
10.244.1.103
[root@k8s-master ~]# curl 10.98.132.219
10.244.1.102

[root@k8s-master ~]# kubectl get endpoints -n dev
NAME              ENDPOINTS                                        AGE
service-cluster   10.244.1.102:80,10.244.1.103:80,10.244.2.94:80   9m16s

Endpoint

Endpoint是kubernetes中的一个资源对象,存储在etcd中,用来记录一个service对应的所有pod的访问地址,它是根据service配置文件中selector描述产生的。

一个Service由一组Pod组成,这些Pod通过Endpoints暴露出来,Endpoints是实现实际服务的端点集合。换句话说,service和pod之间的联系是通过endpoints实现的。

在这里插入图片描述

负载分发策略

对Service的访问被分发到了后端的Pod上去,目前kubernetes提供了两种负载分发策略:

  • 如果不定义,默认使用kube-proxy的策略,比如随机、轮询

  • 基于客户端地址的会话保持模式,即来自同一个客户端发起的所有请求都会转发到固定的一个Pod上,此模式可以使在spec中添加 sessionAffinity:ClientIP 选项

# 查看ipvs的映射规则【rr 轮询】
[root@k8s-master ~]# ipvsadm -Ln
TCP  10.98.132.219:80 rr
  -> 10.244.1.102:80              Masq    1      0          0         
  -> 10.244.1.103:80              Masq    1      0          0         
  -> 10.244.2.94:80               Masq    1      0          0

# 循环访问测试
[root@k8s-master ~]# while true;do curl 10.98.132.219:80; sleep 5; done
10.244.2.94
10.244.1.103
10.244.1.102
10.244.2.94
10.244.1.103
10.244.1.102
10.244.2.94
10.244.1.103
10.244.1.102
10.244.2.94

# 修改分发策略----sessionAffinity: ClientIP

# 查看ipvs规则【persistent 代表持久】
[root@k8s-master ~]# ipvsadm -Ln | grep -A 3 '10.98.132.219'
TCP  10.98.132.219:80 rr
  -> 10.244.1.102:80              Masq    1      0          3         
  -> 10.244.1.103:80              Masq    1      0          3         
  -> 10.244.2.94:80               Masq    1      0          4         
[root@k8s-master ~]#

[root@k8s-master ~]# cd inventory/service/
[root@k8s-master service]# vim service-clusterip.yaml
apiVersion: v1
kind: Service
metadata:
  name: service-cluster
  namespace: dev
spec:
  sessionAffinity: ClientIP  # 添加
  clusterIP: 10.98.132.219
  selector:
    app: service-deployment
  type: ClusterIP
  ports:
  - port: 80
    targetPort: 80
[root@k8s-master service]# kubectl apply -f service-clusterip.yaml 
service/service-cluster configured
[root@k8s-master service]#

# 循环访问测试
[root@k8s-master ~]# while true;do curl 10.98.132.219:80; sleep 5; done
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103
10.244.1.103


root@k8s-master ~]# ipvsadm -Ln | grep -A 3 '10.98.132.219:80'
TCP  10.98.132.219:80 rr persistent 10800
  -> 10.244.1.102:80              Masq    1      0          0         
  -> 10.244.1.103:80              Masq    1      0          12   # 表示访问12次     
  -> 10.244.2.94:80               Masq    1      0          0         
[root@k8s-master ~]#

6.3.3 HeadLiness类型的Service

在某些场景中,开发人员可能不想使用Service提供的负载均衡功能,而希望自己来控制负载均衡策略,针对这种情况,kubernetes提供了HeadLiness Service,这类Service不会分配Cluster IP,如果想要访问service,只能通过service的域名进行查询。

创建service-headliness.yaml

apiVersion: v1
kind: Service
metadata:
  name: service-headliness
  namespace: dev
spec:
  selector:
    app: service-deployment
  clusterIP: None # 将clusterIP设置为None,即可创建headliness Service
  type: ClusterIP
  ports:
  - port: 80    # Service端口 
    targetPort: 80  # Pod 端口
# 创建 service
[root@k8s-master service]# pwd
/root/inventory/service
[root@k8s-master service]# kubectl apply -f service-headliness.yaml 
service/service-headliness created

# 获取service, 发现CLUSTER-IP未分配
[root@k8s-master ~]# kubectl get service service-headliness -n dev -o wide
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE   SELECTOR
service-headliness   ClusterIP   None         <none>        80/TCP    35s   app=service-deployment

# 查看service详情
[root@k8s-master ~]# kubectl describe service service-headliness -n dev
Name:              service-headliness
Namespace:         dev
Labels:            <none>
Annotations:       <none>
Selector:          app=service-deployment
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                None
IPs:               None
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.102:80,10.244.1.103:80,10.244.2.94:80
Session Affinity:  None
Events:            <none>

[root@k8s-master ~]# kubectl get pod -n dev
NAME                                  READY   STATUS    RESTARTS   AGE
service-deployment-788d874977-tgqfn   1/1     Running   0          58m
service-deployment-788d874977-tpfkp   1/1     Running   0          58m
service-deployment-788d874977-wz48l   1/1     Running   0          58m

# 查看域名的解析情况
[root@k8s-master ~]# kubectl exec service-deployment-788d874977-tgqfn -itn dev -- /bin/bash
root@service-deployment-788d874977-tgqfn:/# cat /etc/resolv.conf 
search dev.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5

# 需要安装dig命令,安装yum install -y bind-utils ; 查找dig命令由那个包提供 yum provides dig  
[root@k8s-master ~]# dig @10.96.0.10 service-headliness.dev.svc.cluster.local

; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.el7_9.15 <<>> @10.96.0.10 service-headliness.dev.svc.cluster.local
; (1 server found)
;; global options: +cmd
;; Got answer:
;; WARNING: .local is reserved for Multicast DNS
;; You are currently testing what happens when an mDNS query is leaked to DNS
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1422
;; flags: qr aa rd; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;service-headliness.dev.svc.cluster.local. IN A

;; ANSWER SECTION:
service-headliness.dev.svc.cluster.local. 30 IN	A 10.244.1.102
service-headliness.dev.svc.cluster.local. 30 IN	A 10.244.1.103
service-headliness.dev.svc.cluster.local. 30 IN	A 10.244.2.94

;; Query time: 10 msec
;; SERVER: 10.96.0.10#53(10.96.0.10)
;; WHEN: Mon Dec 18 15:59:23 CST 2023
;; MSG SIZE  rcvd: 237

[root@k8s-master ~]#

# 测试域名负载均衡
[root@k8s-master ~]# kubectl run nginx1 --image=nginx:1.20.0 -n dev
pod/nginx1 created
[root@k8s-master ~]# kubectl exec nginx1 -n dev -it -- /bin/bash
root@nginx1:/# curl service-headliness.dev.svc.cluster.local
10.244.1.103
root@nginx1:/# curl service-headliness.dev.svc.cluster.local
10.244.1.102
root@nginx1:/# curl service-headliness.dev.svc.cluster.local
10.244.1.103
root@nginx1:/# curl service-headliness.dev.svc.cluster.local
10.244.1.102
root@nginx1:/# curl service-headliness.dev.svc.cluster.local
10.244.1.102
root@nginx1:/# curl service-headliness.dev.svc.cluster.local
10.244.1.103
root@nginx1:/# curl service-headliness.dev.svc.cluster.local
10.244.1.103
root@nginx1:/# 
# 访问不到10.244.2.94是因为 k8s-node2

[root@k8s-master ~]# kubectl get pod -n dev -o wide
NAME                                  READY   STATUS    RESTARTS   AGE   IP             NODE        ······
nginx1                                1/1     Running   0          96s   10.244.1.110   k8s-node1   ······
service-deployment-788d874977-tgqfn   1/1     Running   0          85m   10.244.2.94    k8s-node2   ······
service-deployment-788d874977-tpfkp   1/1     Running   0          85m   10.244.1.102   k8s-node1   ······
service-deployment-788d874977-wz48l   1/1     Running   0          85m   10.244.1.103   k8s-node1   ······
[root@k8s-master ~]# 

6.3.4 NodePort类型的Service

在之前的样例中,创建的Service的ip地址只有集群内部才可以访问,如果希望将Service暴露给集群外部使用,那么就要使用到另外一种类型的Service,称为NodePort类型。NodePort的工作原理其实就是将service的端口映射到Node的一个端口上,然后就可以通过NodeIp:NodePort来访问service了。

在这里插入图片描述

创建service-nodeport.yaml

apiVersion: v1
kind: Service
metadata:
  name: service-nodeport
  namespace: dev
spec:
  clusterIP: 10.108.220.52   # service的ip地址,如果不写,默认会生成一个
  selector:
    app: service-deployment
  type: NodePort # service类型
  ports:
  - port: 80
    nodePort: 30002 # 指定绑定的node的端口(默认的取值范围是:30000-32767), 如果不指定,会默认分配
    targetPort: 80
# 创建service
[root@k8s-master service]# pwd
/root/inventory/service
[root@k8s-master service]# kubectl apply -f service-nodeport.yaml 
service/service-nodeport created
[root@k8s-master service]# 


# 查看service
[root@k8s-master ~]# kubectl get service service-nodeport -n dev -o wide
NAME               TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE   SELECTOR
service-nodeport   NodePort   10.108.220.52   <none>        80:30002/TCP   50s   app=service-deployment

# 接下来可以通过电脑主机的浏览器去访问集群中任意一个nodeip的30002端口,即可访问到pod
# 打开cmd
C:\Users\agan9>curl 10.10.10.148:30002
10.244.2.94

C:\Users\agan9>curl 10.10.10.148:30002
10.244.1.103

C:\Users\agan9>curl 10.10.10.148:30002
10.244.1.102

C:\Users\agan9>curl 10.10.10.148:30002
10.244.2.94

C:\Users\agan9>curl 10.10.10.148:30002
10.244.1.103

C:\Users\agan9>curl 10.10.10.148:30002
10.244.1.102

6.3.5 LoadBalancer类型的Service

LoadBalancer和NodePort很相似,目的都是向外部暴露一个端口,区别在于LoadBalancer会在集群的外部再来做一个负载均衡设备,而这个设备需要外部环境支持的,外部服务发送到这个设备上的请求,会被设备负载之后转发到集群中。

在这里插入图片描述

6.3.6 ExternalName类型的Service

ExternalName类型的Service用于引入集群外部的服务,它通过externalName属性指定外部一个服务的地址,然后在集群内部访问此service就可以访问到外部的服务了。

在这里插入图片描述

apiVersion: v1
kind: Service
metadata:
  name: service-externalname
  namespace: dev
spec:
  type: ExternalName # service类型
  externalName: www.baidu.com  #改成ip地址也可以
# 创建service
[root@k8s-master service]# pwd
/root/inventory/service
[root@k8s-master service]# kubectl apply -f service-externalname.yaml 
service/service-externalname created

[root@k8s-master ~]# kubectl get service service-externalname -n dev
NAME                   TYPE           CLUSTER-IP   EXTERNAL-IP     PORT(S)   AGE
service-externalname   ExternalName   <none>       www.baidu.com   <none>    15s
[root@k8s-master ~]# 


# 域名解析
[root@k8s-master ~]# dig @10.96.0.10 service-externalname.dev.svc.cluster.local

; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.el7_9.15 <<>> @10.96.0.10 service-externalname.dev.svc.cluster.local
; (1 server found)
;; global options: +cmd
;; Got answer:
;; WARNING: .local is reserved for Multicast DNS
;; You are currently testing what happens when an mDNS query is leaked to DNS
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11466
;; flags: qr aa rd; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;service-externalname.dev.svc.cluster.local. IN A

;; ANSWER SECTION:
service-externalname.dev.svc.cluster.local. 30 IN CNAME	www.baidu.com.
www.baidu.com.		30	IN	A	36.155.132.76
www.baidu.com.		30	IN	A	36.155.132.3

;; Query time: 26 msec
;; SERVER: 10.96.0.10#53(10.96.0.10)
;; WHEN: Mon Dec 18 21:17:40 CST 2023
;; MSG SIZE  rcvd: 198

[root@k8s-master ~]#

6.4 Ingress介绍

在前面课程中已经提到,Service对集群之外暴露服务的主要方式有两种:NotePort和LoadBalancer,但是这两种方式,都有一定的缺点:

  • NodePort方式的缺点是会占用很多集群机器的端口,那么当集群服务变多的时候,这个缺点就愈发明显
  • LB方式的缺点是每个service需要一个LB,浪费、麻烦,并且需要kubernetes之外设备的支持

基于这种现状,kubernetes提供了Ingress资源对象,Ingress只需要一个NodePort或者一个LB就可以满足暴露多个Service的需求。工作机制大致如下图表示:

在这里插入图片描述

实际上,Ingress相当于一个7层的负载均衡器,是kubernetes对反向代理的一个抽象,它的工作原理类似于Nginx,可以理解成在Ingress里建立诸多映射规则,Ingress Controller通过监听这些配置规则并转化成Nginx的反向代理配置 , 然后对外部提供服务。在这里有两个核心概念:

  • ingress:kubernetes中的一个对象,作用是定义请求如何转发到service的规则
  • ingress controller:具体实现反向代理及负载均衡的程序,对ingress定义的规则进行解析,根据配置的规则来实现请求转发,实现方式有很多,比如Nginx, Contour, Haproxy等等

Ingress(以Nginx为例)的工作原理如下:

  1. 用户编写Ingress规则,说明哪个域名对应kubernetes集群中的哪个Service
  2. Ingress控制器动态感知Ingress服务规则的变化,然后生成一段对应的Nginx反向代理配置
  3. Ingress控制器会将生成的Nginx配置写入到一个运行着的Nginx服务中,并动态更新
  4. 到此为止,其实真正在工作的就是一个Nginx了,内部配置了用户定义的请求转发规则

img

6.5 Ingress使用

6.5.1 环境准备

搭建ingress环境

官方的 deploy.yaml , 如果官方的镜像拉去不下来,就去docker官网找,在下面有写

apiVersion: v1
kind: Namespace
metadata:
  labels:
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  name: ingress-nginx
---
apiVersion: v1
automountServiceAccountToken: true
kind: ServiceAccount
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx
  namespace: ingress-nginx
---
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx
  namespace: ingress-nginx
rules:
- apiGroups:
  - ""
  resources:
  - namespaces
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - configmaps
  - pods
  - secrets
  - endpoints
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - services
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses/status
  verbs:
  - update
- apiGroups:
  - networking.k8s.io
  resources:
  - ingressclasses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - coordination.k8s.io
  resourceNames:
  - ingress-nginx-leader
  resources:
  - leases
  verbs:
  - get
  - update
- apiGroups:
  - coordination.k8s.io
  resources:
  - leases
  verbs:
  - create
- apiGroups:
  - ""
  resources:
  - events
  verbs:
  - create
  - patch
- apiGroups:
  - discovery.k8s.io
  resources:
  - endpointslices
  verbs:
  - list
  - watch
  - get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission
  namespace: ingress-nginx
rules:
- apiGroups:
  - ""
  resources:
  - secrets
  verbs:
  - get
  - create
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx
rules:
- apiGroups:
  - ""
  resources:
  - configmaps
  - endpoints
  - nodes
  - pods
  - secrets
  - namespaces
  verbs:
  - list
  - watch
- apiGroups:
  - coordination.k8s.io
  resources:
  - leases
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - services
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - events
  verbs:
  - create
  - patch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses/status
  verbs:
  - update
- apiGroups:
  - networking.k8s.io
  resources:
  - ingressclasses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - discovery.k8s.io
  resources:
  - endpointslices
  verbs:
  - list
  - watch
  - get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission
rules:
- apiGroups:
  - admissionregistration.k8s.io
  resources:
  - validatingwebhookconfigurations
  verbs:
  - get
  - update
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx
  namespace: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: ingress-nginx
subjects:
- kind: ServiceAccount
  name: ingress-nginx
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission
  namespace: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: ingress-nginx-admission
subjects:
- kind: ServiceAccount
  name: ingress-nginx-admission
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: ingress-nginx
subjects:
- kind: ServiceAccount
  name: ingress-nginx
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: ingress-nginx-admission
subjects:
- kind: ServiceAccount
  name: ingress-nginx-admission
  namespace: ingress-nginx
---
apiVersion: v1
data:
  allow-snippet-annotations: "false"
kind: ConfigMap
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-controller
  namespace: ingress-nginx
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - appProtocol: http
    name: http
    port: 80
    protocol: TCP
    targetPort: http
  - appProtocol: https
    name: https
    port: 443
    protocol: TCP
    targetPort: https
  selector:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  type: NodePort
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-controller-admission
  namespace: ingress-nginx
spec:
  ports:
  - appProtocol: https
    name: https-webhook
    port: 443
    targetPort: webhook
  selector:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  type: ClusterIP
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  minReadySeconds: 0
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app.kubernetes.io/component: controller
      app.kubernetes.io/instance: ingress-nginx
      app.kubernetes.io/name: ingress-nginx
  strategy:
    rollingUpdate:
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      labels:
        app.kubernetes.io/component: controller
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/part-of: ingress-nginx
        app.kubernetes.io/version: 1.9.4
    spec:
      containers:
      - args:
        - /nginx-ingress-controller
        - --election-id=ingress-nginx-leader
        - --controller-class=k8s.io/ingress-nginx
        - --ingress-class=nginx
        - --configmap=$(POD_NAMESPACE)/ingress-nginx-controller
        - --validating-webhook=:8443
        - --validating-webhook-certificate=/usr/local/certificates/cert
        - --validating-webhook-key=/usr/local/certificates/key
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: LD_PRELOAD
          value: /usr/local/lib/libmimalloc.so
        image: registry.k8s.io/ingress-nginx/controller:v1.9.4@sha256:5b161f051d017e55d358435f295f5e9a297e66158f136321d9b04520ec6c48a3
        imagePullPolicy: IfNotPresent
        lifecycle:
          preStop:
            exec:
              command:
              - /wait-shutdown
        livenessProbe:
          failureThreshold: 5
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        name: controller
        ports:
        - containerPort: 80
          name: http
          protocol: TCP
        - containerPort: 443
          name: https
          protocol: TCP
        - containerPort: 8443
          name: webhook
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        resources:
          requests:
            cpu: 100m
            memory: 90Mi
        securityContext:
          allowPrivilegeEscalation: true
          capabilities:
            add:
            - NET_BIND_SERVICE
            drop:
            - ALL
          runAsUser: 101
        volumeMounts:
        - mountPath: /usr/local/certificates/
          name: webhook-cert
          readOnly: true
      dnsPolicy: ClusterFirst
      nodeSelector:
        kubernetes.io/os: linux
      serviceAccountName: ingress-nginx
      terminationGracePeriodSeconds: 300
      volumes:
      - name: webhook-cert
        secret:
          secretName: ingress-nginx-admission
---
apiVersion: batch/v1
kind: Job
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission-create
  namespace: ingress-nginx
spec:
  template:
    metadata:
      labels:
        app.kubernetes.io/component: admission-webhook
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/part-of: ingress-nginx
        app.kubernetes.io/version: 1.9.4
      name: ingress-nginx-admission-create
    spec:
      containers:
      - args:
        - create
        - --host=ingress-nginx-controller-admission,ingress-nginx-controller-admission.$(POD_NAMESPACE).svc
        - --namespace=$(POD_NAMESPACE)
        - --secret-name=ingress-nginx-admission
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        image: registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20231011-8b53cabe0@sha256:a7943503b45d552785aa3b5e457f169a5661fb94d82b8a3373bcd9ebaf9aac80
        imagePullPolicy: IfNotPresent
        name: create
        securityContext:
          allowPrivilegeEscalation: false
      nodeSelector:
        kubernetes.io/os: linux
      restartPolicy: OnFailure
      securityContext:
        fsGroup: 2000
        runAsNonRoot: true
        runAsUser: 2000
      serviceAccountName: ingress-nginx-admission
---
apiVersion: batch/v1
kind: Job
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission-patch
  namespace: ingress-nginx
spec:
  template:
    metadata:
      labels:
        app.kubernetes.io/component: admission-webhook
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/part-of: ingress-nginx
        app.kubernetes.io/version: 1.9.4
      name: ingress-nginx-admission-patch
    spec:
      containers:
      - args:
        - patch
        - --webhook-name=ingress-nginx-admission
        - --namespace=$(POD_NAMESPACE)
        - --patch-mutating=false
        - --secret-name=ingress-nginx-admission
        - --patch-failure-policy=Fail
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        image: registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20231011-8b53cabe0@sha256:a7943503b45d552785aa3b5e457f169a5661fb94d82b8a3373bcd9ebaf9aac80
        imagePullPolicy: IfNotPresent
        name: patch
        securityContext:
          allowPrivilegeEscalation: false
      nodeSelector:
        kubernetes.io/os: linux
      restartPolicy: OnFailure
      securityContext:
        fsGroup: 2000
        runAsNonRoot: true
        runAsUser: 2000
      serviceAccountName: ingress-nginx-admission
---
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: nginx
spec:
  controller: k8s.io/ingress-nginx
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission
  namespace: ingress-nginx
spec:
  egress:
  - {}
  podSelector:
    matchLabels:
      app.kubernetes.io/component: admission-webhook
      app.kubernetes.io/instance: ingress-nginx
      app.kubernetes.io/name: ingress-nginx
  policyTypes:
  - Ingress
  - Egress
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.9.4
  name: ingress-nginx-admission
webhooks:
- admissionReviewVersions:
  - v1
  clientConfig:
    service:
      name: ingress-nginx-controller-admission
      namespace: ingress-nginx
      path: /networking/v1/ingresses
  failurePolicy: Fail
  matchPolicy: Equivalent
  name: validate.nginx.ingress.kubernetes.io
  rules:
  - apiGroups:
    - networking.k8s.io
    apiVersions:
    - v1
    operations:
    - CREATE
    - UPDATE
    resources:
    - ingresses
  sideEffects: None
# 如果deploy.yaml中的镜像拉取不下来,查找可用的ingress-nginx-controller和kube-webhook-certgen镜像
# 手动拉取镜像需要在每个节点都要执行
[root@k8s-master ~]# docker pull dyrnq/ingress-nginx-controller:v1.9.0
v1.9.0: Pulling from dyrnq/ingress-nginx-controller
8a49fdb3b6a5: Pull complete 
f55717a5fb17: Pull complete 
2ccd9f72f01a: Pull complete 
91f8bbc316f7: Pull complete 
5956894d6526: Pull complete 
4f4fb700ef54: Pull complete 
f77fee091fe7: Pull complete 
edb2563b3cf8: Pull complete 
473620f35c96: Pull complete 
1d5949a6578d: Pull complete 
68162cf2f96d: Pull complete 
dae023f980cd: Pull complete 
df9e521b91a5: Pull complete 
46fb48d2574a: Pull complete 
Digest: sha256:c15d1a617858d90fb8f8a2dd60b0676f2bb85c54e3ed11511794b86ec30c8c60
Status: Downloaded newer image for dyrnq/ingress-nginx-controller:v1.9.0

[root@k8s-master ~]# docker pull dyrnq/kube-webhook-certgen:v20230407
v20230407: Pulling from dyrnq/kube-webhook-certgen
10f855b03c8a: Pull complete 
fe5ca62666f0: Pull complete 
fff4e558ad3a: Pull complete 
fcb6f6d2c998: Pull complete 
e8c73c638ae9: Pull complete 
1e3d9b7d1452: Pull complete 
4aa0ea1413d3: Pull complete 
7c881f9ab25e: Pull complete 
5627a970d25e: Pull complete 
baeaa1a3b0bf: Pull complete 
Digest: sha256:543c40fd093964bc9ab509d3e791f9989963021f1e9e4c9c7b6700b02bfb227b
Status: Downloaded newer image for dyrnq/kube-webhook-certgen:v20230407
docker.io/dyrnq/kube-webhook-certgen:v20230407

# 查看本地镜像
[root@k8s-master ~]# docker image ls
REPOSITORY                       TAG         IMAGE ID       CREATED        SIZE
dyrnq/ingress-nginx-controller   v1.9.0      b559857d08cc   3 months ago   292MB
dyrnq/kube-webhook-certgen       v20230407   7e7451bb7042   8 months ago   47.2MB
[root@k8s-master ~]# 
# 创建文件夹
[root@k8s-master ~]# mkdir ingress-controller
[root@k8s-master ~]# cd ingress-controller/
# 获取ingress-nginx,本次案例使用的是1.9.4版本
[root@k8s-master ingress-controller]# wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.9.4/deploy/static/provider/baremetal/deploy.yaml
[root@k8s-master ingress-controller]# 

# 修改deploy.yaml
# 把官方镜像修改成 dyrnq/ingress-nginx-controller:v1.9.0 ; dyrnq/kube-webhook-certgen:v20230407
[root@k8s-master ingress-controller]# grep image deploy.yaml 
        image: registry.k8s.io/ingress-nginx/controller:v1.9.4@sha256:5b161f051d017e55d358435f295f5e9a297e66158f136321d9b04520ec6c48a3
        imagePullPolicy: IfNotPresent
        image: registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20231011-8b53cabe0@sha256:a7943503b45d552785aa3b5e457f169a5661fb94d82b8a3373bcd9ebaf9aac80
        imagePullPolicy: IfNotPresent
        image: registry.k8s.io/ingress-nginx/kube-webhook-certgen:v20231011-8b53cabe0@sha256:a7943503b45d552785aa3b5e457f169a5661fb94d82b8a3373bcd9ebaf9aac80
        imagePullPolicy: IfNotPresent
        
# 修改后的内容
[root@k8s-master ~]# grep image inventory/ingress-controller/deploy.yaml 
        image: dyrnq/ingress-nginx-controller:v1.9.0
        imagePullPolicy: IfNotPresent
        image: dyrnq/kube-webhook-certgen:v20230407
        imagePullPolicy: IfNotPresent
        image: dyrnq/kube-webhook-certgen:v20230407
        imagePullPolicy: IfNotPresent
[root@k8s-master ~]# 



# 创建ingress-nginx
[root@k8s-master ingress-controller]# kubectl apply -f 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
networkpolicy.networking.k8s.io/ingress-nginx-admission created
validatingwebhookconfiguration.admissionregistration.k8s.io/ingress-nginx-admission created
[root@k8s-master ingress-controller]# 

# 查看ingress-nginx的pod
[root@k8s-master ~]# kubectl get pod -n ingress-nginx 
NAME                                        READY   STATUS      RESTARTS   AGE
ingress-nginx-admission-create-mpws6        0/1     Completed   0          11m
ingress-nginx-admission-patch-vlc9n         0/1     Completed   0          11m
ingress-nginx-controller-6d468f9b88-d784c   1/1     Running     0          11m
[root@k8s-master ~]# 

# 查看service
[root@k8s-master ~]# kubectl get service -n ingress-nginx
NAME                                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
ingress-nginx-controller             NodePort    10.104.147.163   <none>        80:30433/TCP,443:31612/TCP   5m23s
ingress-nginx-controller-admission   ClusterIP   10.102.191.232   <none>        443/TCP                      5m23s
[root@k8s-master ~]# 

准备service和pod

为了后面的实验比较方便,创建如下图所示的模型

在这里插入图片描述

创建tomcat-nginx.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: dev
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx-pod
  template:
    metadata:
      labels:
        app: nginx-pod
    spec:
      containers:
      - name: nginx
        image: nginx:1.20.0
        ports:
        - containerPort: 80

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcat-deployment
  namespace: dev
spec:
  replicas: 3
  selector:
    matchLabels:
      app: tomcat-pod
  template:
    metadata:
      labels:
        app: tomcat-pod
    spec:
      containers:
      - name: tomcat
        image: tomcat:8.0-alpine
        ports:
        - containerPort: 8080

---

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  namespace: dev
spec:
  selector:
    app: nginx-pod
  clusterIP: None
  type: ClusterIP
  ports:
  - port: 80
    targetPort: 80

---

apiVersion: v1
kind: Service
metadata:
  name: tomcat-service
  namespace: dev
spec:
  selector:
    app: tomcat-pod
  clusterIP: None
  type: ClusterIP
  ports:
  - port: 8080
    targetPort: 8080
# 创建
[root@k8s-master ~]# cd inventory/ingress-controller/
[root@k8s-master ingress-controller]# kubectl apply -f tomcat-nginx.yaml 
deployment.apps/nginx-deployment created
deployment.apps/tomcat-deployment created
service/nginx-service created
service/tomcat-service created
[root@k8s-master ingress-controller]# 

# 查看Pod
[root@k8s-master ~]# kubectl get pod -n dev
NAME                                 READY   STATUS    RESTARTS       AGE
nginx-deployment-7cb69f4885-f92jr    1/1     Running   0              69s
nginx-deployment-7cb69f4885-s645w    1/1     Running   0              69s
nginx-deployment-7cb69f4885-zjq8z    1/1     Running   0              69s
tomcat-deployment-79cd69847d-cw8ls   1/1     Running   0              69s
tomcat-deployment-79cd69847d-j57r8   1/1     Running   0              69s
tomcat-deployment-79cd69847d-vrh5m   1/1     Running   0              69s


# 查看
[root@k8s-master ~]# kubectl get service -n dev
NAME             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
nginx-service    ClusterIP   None         <none>        80/TCP     101s
tomcat-service   ClusterIP   None         <none>        8080/TCP   101s
[root@k8s-master ~]# 

6.5.2 Http代理

创建ingress-http.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-http
  namespace: dev
spec:
  ingressClassName: nginx
  rules:
  - host: nginx.itagan.com
    http:
      paths:
      - pathType: Prefix
        path: /
        backend:
          service:
            name: nginx-service
            port:
              number: 80
  - host: tomcat.itagan.com
    http:
      paths:
      - pathType: Prefix
        path: /
        backend:
          service:
            name: tomcat-service
            port:
              number: 8080
# 创建
[root@k8s-master ingress-controller]# pwd
/root/inventory/ingress-controller
[root@k8s-master ingress-controller]# kubectl apply -f ingress-http.yaml 
ingress.networking.k8s.io/ingress-http created
[root@k8s-master ingress-controller]# 

# 查看
[root@k8s-master ~]# kubectl get ingress -n dev
NAME           CLASS    HOSTS                                ADDRESS   PORTS   AGE
ingress-http   <none>   nginx.itagan.com,tomcat.itagan.com             80      35s
[root@k8s-master ~]# 

# 查看详情
[root@k8s-master ~]# kubectl describe ingress ingress-http -n dev
Name:             ingress-http
Labels:           <none>
Namespace:        dev
Address:          
Ingress Class:    <none>
Default backend:  <default>
Rules:
  Host               Path  Backends
  ----               ----  --------
  nginx.itagan.com   
                     /   nginx-service:80 (10.244.1.146:80,10.244.1.147:80,10.244.2.127:80)
  tomcat.itagan.com  
                     /   tomcat-service:8080 (10.244.1.145:8080,10.244.2.128:8080,10.244.2.129:8080)
Annotations:         <none>
Events:              <none>
[root@k8s-master ~]# 

# 接下来,在本地电脑上配置host文件,解析上面的两个域名到10.10.10.148(k8s-master)上
# 然后,就可以分别访问 tomcat.itagan.com:30433  和  nginx.itagan.com:30433 查看效果了

6.5.3 Https代理

创建证书

# 生成证书
[root@k8s-master ingress-controller]# pwd
/root/inventory/ingress-controller
[root@k8s-master ingress-controller]# openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/C=CN/ST=BJ/L=BJ/O=nginx/CN=itagan.com"


# 创建密钥
[root@k8s-master ingress-controller]# kubectl create secret tls tls-secret --key tls.key --cert tls.crt
secret/tls-secret created
[root@k8s-master ingress-controller]# kubectl get secret
NAME         TYPE                DATA   AGE
tls-secret   kubernetes.io/tls   2      88s

[root@k8s-master ingress-controller]# kubectl describe secret tls-secret
Name:         tls-secret
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/tls

Data
====
tls.crt:  1245 bytes
tls.key:  1708 bytes
[root@k8s-master ingress-controller]# 

创建ingress-https.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-https
  namespace: dev
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - nginx.itagan.com
    - tomcat.itagan.com
    secretName: tls-secret
  rules:
  - host: nginx.itagan.com
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: nginx-service
            port:
              number: 80
  - host: tomcat.itagan.com
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: tomcat-service
            port:
              number: 8080
# 创建
[root@k8s-master ingress-controller]# pwd
/root/inventory/ingress-controller
[root@k8s-master ingress-controller]# kubectl apply -f ingress-https.yaml 
ingress.networking.k8s.io/ingress-https created


# 查看
[root@k8s-master ~]# kubectl get ingress -n dev
NAME            CLASS   HOSTS                                ADDRESS        PORTS     AGE
ingress-https   nginx   nginx.itagan.com,tomcat.itagan.com   10.10.10.149   80, 443   47s
[root@k8s-master ~]# 

# 查看详情
[root@k8s-master ~]#  kubectl describe ing ingress-https -n dev
Name:             ingress-https
Labels:           <none>
Namespace:        dev
Address:          10.10.10.149
Ingress Class:    nginx
Default backend:  <default>
TLS:
  tls-secret terminates nginx.itagan.com,tomcat.itagan.com
Rules:
  Host               Path  Backends
  ----               ----  --------
  nginx.itagan.com   
                     /   nginx-service:80 (10.244.1.156:80,10.244.1.158:80,10.244.2.144:80)
  tomcat.itagan.com  
                     /   tomcat-service:8080 (10.244.1.157:8080,10.244.2.145:8080,10.244.2.146:8080)
Annotations:         <none>
Events:
  Type    Reason  Age                From                      Message
  ----    ------  ----               ----                      -------
  Normal  Sync    55s (x2 over 66s)  nginx-ingress-controller  Scheduled for sync
[root@k8s-master ~]# 


# 下面可以通过浏览器访问 https://nginx.itagan.com:31612 和 https://tomcat.itagan.com:31612 来查看了

默认情况下,http与https不能共存,访问http时会自动跳转到https上,若想http与https共存,只需在ingress文件中配置以下内容:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-https
  namespace: dev
  annotations:                       # 添加
    nginx.ingress.kubernetes.io/ssl-redirect: "false"  # 添加
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - nginx.itagan.com
    - tomcat.itagan.com
    secretName: tls-secret
  rules:
  - host: nginx.itagan.com
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: nginx-service
            port:
              number: 80
  - host: tomcat.itagan.com
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: tomcat-service
            port:
              number: 8080

http方式:nginx.itagan.com:30433 / tomcat.itagan.com:30433

https方式:https://nginx.itagan.com:31612 / https://tomcat.itagan.com:31612

在这里插入图片描述

在访问的时候,如果用curl能成功访问,而在浏览器上却无法访问,则需要在master主机上执行以下命令:

iptables -P FORWARD ACCEPT

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/264961.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

多个bean获取同一个Service,获取的内存地址是同一块;引用bean地址存储在一个map中

public class UserService {public void test() {System.out.println("---test----");} } Testpublic void doesNotContain1(){// 创建Spring容器AnnotationConfigApplicationContext applicationContext new AnnotationConfigApplicationContext();// 向容器中注册…

3 pandas之dataframe

定义 DataFrame是一个二维数据结构&#xff0c;即数据以行和列的方式以表格形式对齐。 DataFrame特点&#xff1a; 存在不同类型的列大小可变带有标签的轴可对列和行进行算数运算 构造函数 pandas.DataFrame( data, index, columns, dtype, copy)参数解释&#xff1a; 序号…

【SpringBoot快速入门】(1)SpringBoot的开发步骤、工程构建方法以及工程的快速启动详细讲解

目录 SpringBoot简介1 SpringBoot快速入门1.1 开发步骤1.1.1 创建新模块1.1.2 创建 Controller1.1.3 启动服务器1.1.4 进行测试 2 对比3 官网构建工程3.1 进入SpringBoot官网3.2 选择依赖3.3 生成工程 4 SpringBoot工程快速启动4.1 问题导入4.2 打包4.3 启动 之前我们已经学习的…

浅谈Redis分布式锁(上)

作者简介&#xff1a;大家好&#xff0c;我是smart哥&#xff0c;前中兴通讯、美团架构师&#xff0c;现某互联网公司CTO 联系qq&#xff1a;184480602&#xff0c;加我进群&#xff0c;大家一起学习&#xff0c;一起进步&#xff0c;一起对抗互联网寒冬 不论面试还是实际工作中…

Netty 与 RPC(一)

Netty 与 RPC Netty 原理 Netty 是一个高性能、异步事件驱动的 NIO 框架&#xff0c;基于 JAVA NIO 提供的 API 实现。它提供了对TCP、UDP 和文件传输的支持&#xff0c;作为一个异步 NIO 框架&#xff0c;Netty 的所有 IO 操作都是异步非阻塞的&#xff0c;通过 Future-List…

算法练习Day19 (Leetcode/Python-二叉树)

108. Convert Sorted Array to Binary Search Tree Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. 思路&#xff1a; 一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的…

开启虚拟与现实的融合时代

数字人直播&#xff0c;作为一项新兴技术&#xff0c;正逐渐改变着我们的生活方式和沟通方式。它通过利用最先进的人工智能技术&#xff0c;使得虚拟形象得以与现实世界实时互动&#xff0c;为用户带来了全新的体验。本文将探讨数字人直播的意义、应用场景以及可能带来的影响。…

利用MultCloud在线复制传输不同网盘之间的数据:支持谷歌Drive、百度网盘等

本文介绍通过MultCloud平台&#xff0c;在国内实现谷歌Drive、OneDrive、百度网盘等不同云盘之间数据的传输、共享等操作的免费方法。 有的时候&#xff0c;我们希望对自己不同网盘之间的数据加以传输、共享&#xff1b;例如&#xff0c;我们可以将自己谷歌Drive中的数据&#…

Deep learning-based small object detection: A survey(2023)

文章目录 AbstractIntroductionContribution Generic SOD algorithms提高输入特征的分辨率&#xff08;Most Important&#xff09;Methods 尺度感知训练Methods 融合上下文信息Methods 数据增强Methods 其他策略Methods 关键的SOD任务小人脸检测Methods 小型行人检测Methods 航…

在线考试系统-软件与环境

一. 软件 1.Navicat、phpstudy、Idea、Vsode 参考 网盘链接 二.配置文件 1.NodeJS、JDK、Mysql 参考 网盘链接 注意点&#xff1a; 1.Mysql 切记需要环境变量配置 2.数据库密码要好记点的&#xff0c;别乱设 3.环境变量配置的路径要能找到 三.安装运行 1.下载网盘内的软件&am…

【ps】常见工具说明

1&#xff1a;污点修复工具 》内容识别 去除脸部珍珠 》创建纹理 2&#xff1a;修复画笔工具 按住ALT选择一处你想移动的地方 3&#xff1a;修补工具 》内容识别 选择一个区域 将区域内的东西移动到 另一处皮肤上

【Linux笔记】系统信息

&#x1f34e;个人博客&#xff1a;个人主页 &#x1f3c6;个人专栏&#xff1a;Linux学习 ⛳️ 功不唐捐&#xff0c;玉汝于成 目录 前言 命令 1. uname - 显示系统信息 2. hostname - 显示或设置系统主机名 3. top - 显示系统资源使用情况 4. df - 显示磁盘空间使用情…

Socket.D 基于消息的响应式应用层网络协议

首先根据 Socket.D 官网 的副标题&#xff0c;Socket.D 的自我定义是&#xff1a; 基于事件和语义消息流的网络应用协议。官网定义的特点是&#xff1a; 基于事件&#xff0c;每个消息都可事件路由所谓语义&#xff0c;通过元信息进行语义描述流关联性&#xff0c;有相关的消…

【前端】前后端通信方法与差异(未完待续)

系列文章 【Vue】vue增加导航标签 本文链接&#xff1a;https://blog.csdn.net/youcheng_ge/article/details/134965353 【Vue】Element开发笔记 本文链接&#xff1a;https://blog.csdn.net/youcheng_ge/article/details/133947977 【Vue】vue&#xff0c;在Windows IIS平台…

Ubuntu 常用命令之 netstat 命令用法介绍

&#x1f4d1;Linux/Ubuntu 常用命令归类整理 netstat 是一个非常有用的命令行工具&#xff0c;它可以帮助我们监控和诊断网络问题。在 Ubuntu 系统中&#xff0c;我们可以使用 netstat 命令来查看网络连接、路由表、接口统计等信息。 netstat 命令的参数有很多&#xff0c;以…

如何用CHAT做调研?

问CHAT&#xff1a;高校之间关于艺术教育专业调研情况 CHAT回复&#xff1a;对于高校之间的艺术教育专业调研&#xff0c;以下几个方面可能会涉及&#xff1a; 1. 课程设计和学分&#xff1a;可以调研不同高校艺术教育专业的课程设置&#xff0c;包括专业核心课程、相关选修课…

论文润色的注意事项有哪些 papergpt

大家好&#xff0c;今天来聊聊论文润色的注意事项有哪些&#xff0c;希望能给大家提供一点参考。 以下是针对论文重复率高的情况&#xff0c;提供一些修改建议和技巧&#xff0c;可以借助此类工具&#xff1a; 标题&#xff1a;论文润色的注意事项――确保论文质量与表达的关键…

Leetcode 406 根据身高重建队列

题意理解&#xff1a; people [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] 给定一个二维数组&#xff0c;&#xff08;h,k&#xff09;h表示此人身高&#xff0c;k表示前面有几个人比他高。 我们按照每个人的h,k两个维度的需求给每个人排在合适的位置。 如&#xff1a; [5,0][7,0]…

如何提升亚马逊、速卖通店铺自然排名?测评自养号的关键要素

一、自然排名的重要性 一条链接是否推广成功或者赚到钱&#xff0c;就看这条链接的自然排名有没有打上来! 无论是搜索流量的自然排名&#xff0c;还是关联流量的自然排名&#xff0c;或BSR排行榜&#xff0c;这些自然排名的入口就是我们要时刻盯紧的位置。 二、自然排名的位…

C语言之字符串

目录 字符串字面量 ​编辑 字符串字面量的长度 ◆具有静态生命周期 ◆对于同一个字符串字面量的处理方式依赖于编译器 字符串 字符数组的初始化赋值 空字符串 字符串的读取 在前面的学习中就会发现&#xff0c;仅仅能用一个字符表示的事物少之又少&#xff0c;对于地…