Kubernetes学习笔记(三):Service与Ingress

一、Service详解

1、Service介绍

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

为了解决这个问题,Kubernetes提供了Service资源,Service会对提供同一个服务的多个Pod进行聚合,并且提供一个统一的入口地址。通过访问Service的入口地址就能访问到后面的Pod服务

Kubernetes学习笔记(三):Service与Ingress_第1张图片

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

Kubernetes学习笔记(三):Service与Ingress_第2张图片

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

userspace模式

userspace模式下,kube-proxy会为每一个Service创建一个监听端口,发向Cluster IP的请求被Iptables规则重定向到kube-proxy监听的端口上,kube-proxy根据LB算法选择一个提供服务的Pod并和其建立链接,以将请求转发到Pod上

该模式下,kube-proxy充当了一个四层负责均衡器的角色。由于kube-proxy运行在userspace中,在进行转发处理时会增加内核和用户空间之间的数据拷贝,虽然比较稳定,但是效率比较低

Kubernetes学习笔记(三):Service与Ingress_第3张图片

iptables模式

iptables模式下,kube-proxy为Service后端的每个Pod创建对应的iptables规则,直接将发向Cluster IP的请求重定向到一个Pod IP

该模式下kube-proxy不承担四层负责均衡器的角色,只负责创建iptables规则。该模式的优点是较userspace模式效率更高,但不能提供灵活的LB策略,当后端Pod不可用时也无法进行重试

Kubernetes学习笔记(三):Service与Ingress_第4张图片

ipvs模式

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

Kubernetes学习笔记(三):Service与Ingress_第5张图片
# 此模式必须安装ipvs内核模块,否则会降级为iptables
# 开启ipvs
[root@k8s-master ~]# kubectl edit cm kube-proxy -n kube-system
# 修改mode: "ipvs"
[root@k8s-master ~]# kubectl delete pod -l k8s-app=kube-proxy -n kube-system

[root@node1 ~]# ipvsadm -Ln
TCP  10.97.97.97:80 rr
  -> 10.244.1.22:80               Masq    1      0          0
  -> 10.244.2.15:80               Masq    1      0          0
  -> 10.244.2.16:80               Masq    1      0          0

2、Service类型

Service的资源清单文件:

kind: Service # 资源类型
apiVersion: v1 # 资源版本
metadata: # 元数据
  name: service # 资源名称
  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: 把集群外部的服务引入集群内部,直接使用

3、Service使用

1)、实验环境准备

在使用Service之前,首先利用Deployment创建出3个Pod,注意要为Pod设置app: nginx-pod的标签

创建deployment.yaml文件,内容如下:

apiVersion: apps/v1
kind: Deployment      
metadata:
  name: pc-deployment
  namespace: dev
spec: 
  replicas: 3
  selector:
    matchLabels:
      app: nginx-pod
  template:
    metadata:
      labels:
        app: nginx-pod
    spec:
      containers:
      - name: nginx
        image: nginx:1.17.1
        ports:
        - containerPort: 80
# 创建deployment
[root@k8s-master ~]# kubectl create -f deployment.yaml
deployment.apps/pc-deployment created

# 查看pod详情
[root@k8s-master ~]# kubectl get pod -n dev -o wide
NAME                             READY   STATUS    RESTARTS   AGE   IP            NODE        NOMINATED NODE   READINESS GATES
pc-deployment-7d7dd5499b-dx4zd   1/1     Running   0          9s    10.244.2.15   k8s-node2   <none>           <none>
pc-deployment-7d7dd5499b-vsk56   1/1     Running   0          9s    10.244.2.16   k8s-node2   <none>           <none>
pc-deployment-7d7dd5499b-x94dv   1/1     Running   0          9s    10.244.1.22   k8s-node1   <none>           <none>

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

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

[root@k8s-master ~]# curl 10.244.2.16
10.244.2.16

[root@k8s-master ~]# curl 10.244.1.22
10.244.1.22

2)、ClusterIP类型的Service

创建service-clusterip.yaml文件,内容如下:

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

# 查看service
[root@k8s-master ~]# kubectl get svc service-clusterip -n dev -o wide
NAME                TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE   SELECTOR
service-clusterip   ClusterIP   10.97.97.97   <none>        80/TCP    20s    app=nginx-pod

# 查看service的详细信息
# 在这里有一个Endpoints列表,里面就是当前service可以负载到的服务入口
[root@k8s-master ~]# kubectl describe svc service-clusterip -n dev
Name:              service-clusterip
Namespace:         dev
Labels:            <none>
Annotations:       <none>
Selector:          app=nginx-pod
Type:              ClusterIP
IP:                10.97.97.97
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.22:80,10.244.2.15:80,10.244.2.16:80
Session Affinity:  None
Events:            <none>

# 查看ipvs的映射规则
[root@k8s-master ~]# ipvsadm -Ln
TCP  10.97.97.97:80 rr
  -> 10.244.1.22:80               Masq    1      0          0
  -> 10.244.2.15:80               Masq    1      0          0
  -> 10.244.2.16:80               Masq    1      0          0

# 循环访问测试
[root@k8s-master ~]# while true;do curl 10.97.97.97:80; sleep 1; done;
10.244.1.22
10.244.2.15
10.244.2.16
10.244.1.22
10.244.2.15
10.244.2.16

Endpoints

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

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

只有处于Running状态,且readinessProbe检查通过的Pod,才会出现在Service的Endpoints列表里。并且,当某一个Pod出现问题时,Kubernetes会自动把它从Service里摘除掉

# 查看endpoints
[root@k8s-master ~]# kubectl get endpoints -n dev
NAME                ENDPOINTS                                      AGE
service-clusterip   10.244.1.22:80,10.244.2.15:80,10.244.2.16:80   5m10s
Kubernetes学习笔记(三):Service与Ingress_第6张图片

负载分发策略

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

  • 如果不定义,默认使用kube-proxy的策略,比如随机、轮询
  • 基于客户端地址的会话保持模式,即来自同一个客户端发起的所有请求都会转发到固定的一个Pod上,此模式可以使在spec中添加sessionAffinity:ClientIP选项
# 修改分发策略 sessionAffinity:ClientIP
# 查看ipvs规则【persistent 代表持久】
[root@k8s-master ~]# ipvsadm -Ln
TCP  10.97.97.97:80 rr persistent 10800
  -> 10.244.1.22:80               Masq    1      0          0
  -> 10.244.2.15:80               Masq    1      0          0
  -> 10.244.2.16:80               Masq    1      0          0

# 循环访问测试
[root@k8s-master ~]# while true;do curl 10.97.97.97:80; sleep 1; done;
10.244.1.22
10.244.1.22
10.244.1.22
  
# 删除service
[root@k8s-master ~]# kubectl delete -f service-clusterip.yaml
service "service-clusterip" deleted

3)、Headless类型的Service

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

创建service-headless.yaml文件,内容如下:

apiVersion: v1
kind: Service
metadata:
  name: service-headless
  namespace: dev
spec:
  selector:
    app: nginx-pod
  clusterIP: None # 将clusterIP设置为None,即可创建headless Service
  type: ClusterIP
  ports:
  - port: 80    
    targetPort: 80
# 创建service
[root@k8s-master ~]# kubectl create -f service-headless.yaml
service/service-headless created

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

# 查看service详情
[root@k8s-master ~]# kubectl describe svc service-headless -n dev
Name:              service-headless
Namespace:         dev
Labels:            <none>
Annotations:       <none>
Selector:          app=nginx-pod
Type:              ClusterIP
IP:                None
Port:              <unset>  80/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.22:80,10.244.2.15:80,10.244.2.16:80
Session Affinity:  None
Events:            <none>

[root@k8s-master ~]# kubectl get pod -n dev
NAME                             READY   STATUS    RESTARTS   AGE
pc-deployment-7d7dd5499b-dx4zd   1/1     Running   0          33m
pc-deployment-7d7dd5499b-vsk56   1/1     Running   0          33m
pc-deployment-7d7dd5499b-x94dv   1/1     Running   0          33m

# 查看域名的解析情况
[root@k8s-master ~]# kubectl exec -it pc-deployment-7d7dd5499b-dx4zd -n dev /bin/sh
# cat /etc/resolv.conf
nameserver 10.96.0.10
search dev.svc.cluster.local svc.cluster.local cluster.local lan

[root@k8s-master ~]# yum install -y bind-utils

# 默认是service name+dev.svc.cluster.local
[root@k8s-master ~]# dig @10.96.0.10 service-headless.dev.svc.cluster.local
service-headless.dev.svc.cluster.local. 30 IN A 10.244.2.16
service-headless.dev.svc.cluster.local. 30 IN A 10.244.2.15
service-headless.dev.svc.cluster.local. 30 IN A 10.244.1.22

4)、NodePort类型的Service

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

Kubernetes学习笔记(三):Service与Ingress_第7张图片

创建service-nodeport.yaml文件,内容如下:

apiVersion: v1
kind: Service
metadata:
  name: service-nodeport
  namespace: dev
spec:
  selector:
    app: nginx-pod
  type: NodePort # service类型
  ports:
  - port: 80
    nodePort: 30002 # 指定绑定的node的端口(默认的取值范围是:30000-32767),如果不指定,会默认分配
    targetPort: 80
# 创建service
[root@k8s-master ~]# kubectl create -f service-nodeport.yaml
service/service-nodeport created

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

# 接下来可以通过电脑主机的浏览器去访问集群中任意一个nodeip的30002端口,即可访问到pod

5)、LoadBalancer类型的Service

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

Kubernetes学习笔记(三):Service与Ingress_第8张图片

6)、ExternalName类型的Service

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

Kubernetes学习笔记(三):Service与Ingress_第9张图片

创建service-externalname.yaml文件,内容如下:

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

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

# 域名解析
[root@k8s-master ~]# dig @10.96.0.10 service-externalname.dev.svc.cluster.local
service-externalname.dev.svc.cluster.local. 30 IN CNAME www.baidu.com.
www.baidu.com.          30      IN      CNAME   www.a.shifen.com.
www.a.shifen.com.       30      IN      A       180.101.49.12
www.a.shifen.com.       30      IN      A       180.101.49.11

二、Ingress

1、Ingress介绍

Service对集群之外暴露服务的主要方式有两种:NotePort和LoadBalancer,但是这两种方式,都有一定的缺点:

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

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

Kubernetes学习笔记(三):Service与Ingress_第10张图片

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

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

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

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

一个Nginx Ingress Controller提供的服务,其实是一个可以根据Ingress对象和被代理后端Service的变化,来自动进行更新的Nginx负载均衡器

2、Ingress使用

1)、环境准备

1)搭建Ingress环境

[root@k8s-master ~]# mkdir ingress-controller
[root@k8s-master ~]# cd ingress-controller/

# 获取ingress-nginx,本次案例使用的是0.30版本
[root@k8s-master ingress-controller]# wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/mandatory.yaml
[root@k8s-master ingress-controller]# wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/provider/baremetal/service-nodeport.yaml

mandatory.yaml文件内容如下:

apiVersion: v1
kind: Namespace
metadata:
  name: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---

kind: ConfigMap
apiVersion: v1
metadata:
  name: nginx-configuration
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
kind: ConfigMap
apiVersion: v1
metadata:
  name: tcp-services
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
kind: ConfigMap
apiVersion: v1
metadata:
  name: udp-services
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: nginx-ingress-serviceaccount
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: nginx-ingress-clusterrole
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
rules:
  - apiGroups:
      - ""
    resources:
      - configmaps
      - endpoints
      - nodes
      - pods
      - secrets
    verbs:
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - nodes
    verbs:
      - get
  - apiGroups:
      - ""
    resources:
      - services
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - events
    verbs:
      - create
      - patch
  - apiGroups:
      - "extensions"
      - "networking.k8s.io"
    resources:
      - ingresses
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - "extensions"
      - "networking.k8s.io"
    resources:
      - ingresses/status
    verbs:
      - update

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
  name: nginx-ingress-role
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
rules:
  - apiGroups:
      - ""
    resources:
      - configmaps
      - pods
      - secrets
      - namespaces
    verbs:
      - get
  - apiGroups:
      - ""
    resources:
      - configmaps
    resourceNames:
      # Defaults to "-"
      # Here: "-"
      # This has to be adapted if you change either parameter
      # when launching the nginx-ingress-controller.
      - "ingress-controller-leader-nginx"
    verbs:
      - get
      - update
  - apiGroups:
      - ""
    resources:
      - configmaps
    verbs:
      - create
  - apiGroups:
      - ""
    resources:
      - endpoints
    verbs:
      - get

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: nginx-ingress-role-nisa-binding
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: nginx-ingress-role
subjects:
  - kind: ServiceAccount
    name: nginx-ingress-serviceaccount
    namespace: ingress-nginx

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: nginx-ingress-clusterrole-nisa-binding
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: nginx-ingress-clusterrole
subjects:
  - kind: ServiceAccount
    name: nginx-ingress-serviceaccount
    namespace: ingress-nginx

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-ingress-controller
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: ingress-nginx
      app.kubernetes.io/part-of: ingress-nginx
  template:
    metadata:
      labels:
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/part-of: ingress-nginx
      annotations:
        prometheus.io/port: "10254"
        prometheus.io/scrape: "true"
    spec:
      # wait up to five minutes for the drain of connections
      terminationGracePeriodSeconds: 300
      serviceAccountName: nginx-ingress-serviceaccount
      nodeSelector:
        kubernetes.io/os: linux
      containers:
        - name: nginx-ingress-controller
          image: quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0
          args:
            - /nginx-ingress-controller
            - --configmap=$(POD_NAMESPACE)/nginx-configuration
            - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
            - --udp-services-configmap=$(POD_NAMESPACE)/udp-services
            - --publish-service=$(POD_NAMESPACE)/ingress-nginx
            - --annotations-prefix=nginx.ingress.kubernetes.io
          securityContext:
            allowPrivilegeEscalation: true
            capabilities:
              drop:
                - ALL
              add:
                - NET_BIND_SERVICE
            # www-data -> 101
            runAsUser: 101
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
            - name: https
              containerPort: 443
              protocol: TCP
          livenessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            initialDelaySeconds: 10
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 10
          readinessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 10
          lifecycle:
            preStop:
              exec:
                command:
                  - /wait-shutdown

---

apiVersion: v1
kind: LimitRange
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
spec:
  limits:
  - min:
      memory: 90Mi
      cpu: 100m
    type: Container

service-nodeport.yaml文件内容如下:

apiVersion: v1
kind: Service
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
spec:
  type: NodePort
  ports:
    - name: http
      port: 80
      targetPort: 80
      protocol: TCP
    - name: https
      port: 443
      targetPort: 443
      protocol: TCP
  selector:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
# 修改mandatory.yaml文件中的仓库
# 修改quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0
# 为quay-mirror.qiniu.com/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0
# 创建ingress-nginx
[root@k8s-master ingress-controller]# kubectl apply -f ./
# 查看ingress-nginx
[root@k8s-master ingress-controller]# kubectl get pod -n ingress-nginx
NAME                                        READY   STATUS    RESTARTS   AGE
nginx-ingress-controller-5bb8fb4bb6-4x4kx   1/1     Running   0          28s
# 查看service
[root@k8s-master ingress-controller]# kubectl get svc -n ingress-nginx
NAME            TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
ingress-nginx   NodePort   10.101.45.148   <none>        80:30721/TCP,443:32240/TCP   40s

2)准备service和pod

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

Kubernetes学习笔记(三):Service与Ingress_第12张图片

创建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.17.1
        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.5-jre10-slim
        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 ~]# kubectl create -f tomcat-nginx.yaml
[root@k8s-master ~]# kubectl get svc -n dev
NAME             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
nginx-service    ClusterIP   None         <none>        80/TCP     112s
tomcat-service   ClusterIP   None         <none>        8080/TCP   112s

2)、Http代理

创建ingress-http.yaml文件,内容如下:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-http
  namespace: dev
spec:
  rules:
  - host: nginx.ppdai.com
    http:
      paths:
      - path: /
        backend:
          serviceName: nginx-service
          servicePort: 80
  - host: tomcat.ppdai.com
    http:
      paths:
      - path: /
        backend:
          serviceName: tomcat-service
          servicePort: 8080
# 创建
[root@k8s-master ~]# kubectl create -f ingress-http.yaml
# 查看
[root@k8s-master ~]# kubectl get ing ingress-http -n dev
NAME           CLASS    HOSTS                              ADDRESS         PORTS   AGE
ingress-http   <none>   nginx.ppdai.com,tomcat.ppdai.com   10.101.45.148   80      21s
# 查看详情
[root@k8s-master ~]# kubectl describe ing ingress-http  -n dev
Name:             ingress-http
Namespace:        dev
Address:          10.101.45.148
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host              Path  Backends
  ----              ----  --------
  nginx.ppdai.com   
                    /   nginx-service:80 (10.244.1.25:80,10.244.1.26:80,10.244.2.17:80)
  tomcat.ppdai.com  
                    /   tomcat-service:8080 (10.244.1.27:8080,10.244.2.18:8080,10.244.2.19:8080)
Annotations:        <none>
Events:
  Type    Reason  Age   From                      Message
  ----    ------  ----  ----                      -------
  Normal  CREATE  54s   nginx-ingress-controller  Ingress dev/ingress-http
  Normal  UPDATE  36s   nginx-ingress-controller  Ingress dev/ingress-http
  
# 接下来,在本地电脑上配置host文件,解析上面的两个域名到192.168.56.23(master)上
# 然后,就可以分别访问tomcat.ppdai.com:30721(ingress-nginx的http端口)和nginx.ppdai.com:30721查看效果

3)、Https代理

创建证书

# 生成证书
[root@k8s-master ~]# 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=ppdai.com"

# 创建密钥
[root@k8s-master ~]# kubectl create secret tls tls-secret --key tls.key --cert tls.crt
secret/tls-secret created

创建ingress-https.yaml文件,内容如下:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-https
  namespace: dev
spec:
  tls:
    - hosts:
      - nginx.ppdai.com
      - tomcat.ppdai.com
      secretName: tls-secret # 指定秘钥
  rules:
  - host: nginx.ppdai.com
    http:
      paths:
      - path: /
        backend:
          serviceName: nginx-service
          servicePort: 80
  - host: tomcat.ppdai.com
    http:
      paths:
      - path: /
        backend:
          serviceName: tomcat-service
          servicePort: 8080
# 创建
[root@k8s-master ~]# kubectl create -f ingress-https.yaml
ingress.extensions/ingress-https created
# 查看
[root@k8s-master ~]# kubectl get ing ingress-https -n dev
NAME            CLASS    HOSTS                              ADDRESS         PORTS     AGE
ingress-https   <none>   nginx.ppdai.com,tomcat.ppdai.com   10.101.45.148   80, 443   16s
# 查看详情
[root@k8s-master ~]# kubectl describe ing ingress-https -n dev
Name:             ingress-https
Namespace:        dev
Address:          10.101.45.148
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
TLS:
  tls-secret terminates nginx.ppdai.com,tomcat.ppdai.com
Rules:
  Host              Path  Backends
  ----              ----  --------
  nginx.ppdai.com   
                    /   nginx-service:80 (10.244.1.25:80,10.244.1.26:80,10.244.2.17:80)
  tomcat.ppdai.com  
                    /   tomcat-service:8080 (10.244.1.27:8080,10.244.2.18:8080,10.244.2.19:8080)
Annotations:        <none>
Events:
  Type    Reason  Age   From                      Message
  ----    ------  ----  ----                      -------
  Normal  CREATE  46s   nginx-ingress-controller  Ingress dev/ingress-https
  Normal  UPDATE  43s   nginx-ingress-controller  Ingress dev/ingress-https

# 下面可以通过浏览器访问https://nginx.ppdai.com:32240(ingress-nginx的https端口)和https://tomcat.ppdai.com:32240来查看

参考

Kubernetes(K8S) 入门进阶实战完整教程,黑马程序员K8S全套教程(基础+高级)

极客时间 《深入剖析Kubernetes》

你可能感兴趣的:(Kubernetes,Service,Ingress)