k8s之Service詳解-Service使用

路過的柚子廚發表於2021-08-12

實驗環境準備

 在使用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

使用配置檔案

[root@master ~]# vim deployment.yaml
[root@master ~]# kubectl create -f deployment.yaml 
deployment.apps/pc-deployment created
[root@master ~]# kubectl get pod -n dev -o wide
NAME                             READY   STATUS    RESTARTS   AGE   IP            NODE    NOMINATED NODE   READINESS GATES
pc-deployment-6696798b78-5d7rh   1/1     Running   0          4s    10.244.2.4    node2   <none>           <none>
pc-deployment-6696798b78-5jbcr   1/1     Running   0          4s    10.244.1.26   node1   <none>           <none>
pc-deployment-6696798b78-wbrfh   1/1     Running   0          4s    10.244.2.3    node2   <none>           <none>

通過pod的Ip加上容器埠80訪問nginx,發現可以訪問

[root@master ~]# curl 10.244.2.4:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>

為了方便後面的測試,修改下面三臺nginx的index.html頁面(三臺修改的Ip地址不一致)

#修改第一個pod
[root@master ~]# kubectl exec -it pc-deployment-6696798b78-5d7rh -n dev /bin/sh
# echo "10.244.2.4" > /usr/share/nginx/html/index.html
# exit

#測試訪問
[root@master ~]# curl 10.244.2.4:80
10.244.2.4

#修改第二個pod
[root@master ~]# kubectl exec -it pc-deployment-6696798b78-5jbcr -n dev /bin/sh
# echo "10.244.1.26" > /usr/share/nginx/html/index.html
# exit

#修改第三個pod
[root@master ~]# kubectl exec -it pc-deployment-6696798b78-wbrfh -n dev /bin/sh
# echo "10.244.2.3" > /usr/share/nginx/html/index.html
# exit

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埠

 使用配置檔案

[root@master ~]# vim service-clusterip.yaml
[root@master ~]# kubectl create -f service-clusterip.yaml 
service/service-clusterip created
[root@master ~]# kubectl get svc service-clusterip -n dev
NAME                TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
service-clusterip   ClusterIP   10.97.97.97   <none>        80/TCP    44s

#檢視service詳細資訊
[root@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.26:80,10.244.2.3:80,10.244.2.4:80
Session Affinity:  None
Events:            <none>

#檢視ipvs對映規則
[root@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.97.97.97:80 rr
  -> 10.244.1.27:80               Masq    1      0          0         
  -> 10.244.2.5:80                Masq    1      0          0         
  -> 10.244.2.6:80                Masq    1      0          0  

EndPoint

Endpoint是k8s中的一個資源物件,儲存在etcd中,用來記錄一個service對應的所有pod的訪問地址,它是根據service配置檔案中的selector描述產生的

一個service由一組pod組成,這些pod通過endpoints暴露出來,endpoints是實現實際服務的端點集合。換句話說,service和pod之間的聯絡是通過endpoints實現的。

[root@master ~]# kubectl get endpoints -n dev -o wide
NAME                ENDPOINTS                                    AGE
service-clusterip   10.244.1.26:80,10.244.2.3:80,10.244.2.4:80   18m

負載分發策略

對service的訪問被分發到了後端的pod上去,目前k8s提供了兩種負載分發策略:

  • 如果不定義,預設使用kube-proxy的策略,比如隨機,輪詢
  • 基於客戶端地址的會話保持模式,即來自同一個客戶端發起的所有請求都會轉發到一個固定的pod上,此模式可以使在spec中新增sessionAffinity:ClientIP選項
#檢視ipvs對映規則
[root@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.97.97.97:80 rr
  -> 10.244.1.27:80               Masq    1      0          0         
  -> 10.244.2.5:80                Masq    1      0          0         
  -> 10.244.2.6:80                Masq    1      0          0  

#迴圈訪問測試
[root@master ~]# while true;do curl 10.97.97.97:80;sleep 5;done;
10.244.1.26
10.244.2.3
10.244.2.4
10.244.1.26
10.244.2.3
10.244.2.4
10.244.1.26
10.244.2.3
10.244.2.4

修改分發策略為sessionAffinity:ClientIP

#刪除原來的service
[root@master ~]# kubectl delete -f service-clusterip.yaml 
service "service-clusterip" deleted

#更改service-clusterip.yaml
[root@master ~]# vim service-clusterip.yaml 
apiVersion: v1
kind: Service
metadata:
  name: service-clusterip
  namespace: dev
spec:
  sessionAffinity: ClientIP
  selector:
    app: nginx-pod
  clusterIP: 10.97.97.97  #service的Ip地址,如果不寫,會預設生成一個
  type: ClusterIP
  ports:
  - port: 80  #service埠
    targetPort: 80  #pod埠

#重建service
[root@master ~]# kubectl create -f service-clusterip.yaml
service/service-clusterip created

#檢視svc,可以發現新增了一項SessionAffinity
[root@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.27:80,10.244.2.5:80,10.244.2.6:80
Session Affinity: ClientIP
Events: <none>

重新檢視ipvs對映規則【persistent代表持久】,發現新增了persistent 10800秒,代表持續180分鐘

[root@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.97.97.97:80 rr persistent 10800
  -> 10.244.1.27:80               Masq    1      0          0         
  -> 10.244.2.5:80                Masq    1      0          0         
  -> 10.244.2.6:80                Masq    1      0          0  

再次進行迴圈訪問測試,發現這次只訪問一個pod

[root@master ~]# while true;do curl 10.97.97.97:80;sleep 5;done;
10.244.2.4
10.244.2.4
10.244.2.4
10.244.2.4
10.244.2.4
10.244.2.4

HeadLiness型別的Service

在某些場景中,開發人員可能不想使用Service提供的負載均衡功能,而希望自己來控制負載均衡策略,針對這種情況,k8s提供了HeadLiness Service,這類Service不會分配ClusterIP,如果想要訪問Service,只能通過service的域名進行查詢。

建立service-headliness.yaml

apiVersion: v1
kind: Service
metadata:
  name: service-headliness
  namespace: dev
spec:
  selector:
    app: nginx-pod
  clusterIP: None  #將clusterIP設定為None,即可建立headliness Service
  type: ClusterIP
  ports:
  - port: 80
    targetPort: 80

使用配置檔案

[root@master ~]# vim service-headliness.yaml
[root@master ~]# kubectl create -f service-headliness.yaml 
service/service-headliness created
[root@master ~]# kubectl get svc service-headliness -n dev
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service-headliness   ClusterIP   None         <none>        80/TCP    31s
[root@master ~]# kubectl describe svc service-headliness -n dev
Name: service-headliness
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.27:80,10.244.2.5:80,10.244.2.6:80
Session Affinity: None
Events: <none>

檢視域名解析情況

[root@master ~]# kubectl exec -it pc-deployment-6696798b78-5d7rh -n dev /bin/sh
# cat /etc/resolv.conf
nameserver 10.96.0.10
search dev.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
# exit

#通過域名進行查詢
[root@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.5 <<>> @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: 40115
;; 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.2.6
service-headliness.dev.svc.cluster.local. 30 IN    A 10.244.1.27
service-headliness.dev.svc.cluster.local. 30 IN    A 10.244.2.5

;; Query time: 334 msec
;; SERVER: 10.96.0.10#53(10.96.0.10)
;; WHEN: 四 8月 12 11:26:01 CST 2021
;; MSG SIZE  rcvd: 237

NodePort型別的Service

在之前的樣例中,建立的Service的IP地址只有叢集內部可以訪問,如果希望Service暴露給叢集外部使用,那麼就要使用到另外一種型別的Service,稱為NodePort型別。NodePor的工作原理其實就是將service的埠對映到Node的一個埠上,然後就可以通過NodeIp:NodePort來訪問service了。

建立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

使用配置檔案

[root@master ~]# vim service-nodeport.yaml
[root@master ~]# kubectl create -f service-nodeport.yaml 
service/service-nodeport created
[root@master ~]# kubectl get svc service-nodeport -n dev
NAME               TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
service-nodeport   NodePort   10.103.29.82   <none>        80:30002/TCP   14s

通過電腦的瀏覽器對node進行訪問,訪問地址:master的主機ip加上30002埠

發現能夠成功訪問了

LoadBalancer型別的Service

LoadBalancer和NodePort很相似,目的都是向外部暴露一個埠,區別在於LoadBalancer會在叢集的外部再來做一個負載均衡裝置,而這個裝置需要外部環境支援的,外部服務傳送到這個裝置上的請求,會被裝置負載之後轉發到叢集中。

 

ExternalName型別的Service

ExternalName型別的Service用於引入叢集外部的服務,它通過externalName屬性指定外部一個服務的地址,然後在叢集內部訪問此Service就可以訪問到外部的服務了

建立service-externalname.yaml,內容如下

apiVersion: v1
kind: Service
metadata:
  name: service-externalname
  namespace: dev
spec:
  type: ExternalName  #service型別
  externalName: www.baidu.com  #改成ip地址也可以

使用配置檔案

[root@master ~]# vim service-externalname.yaml
[root@master ~]# kubectl create -f service-externalname.yaml 
service/service-externalname created
[root@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@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.5 <<>> @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: 27636
;; flags: qr aa rd; QUERY: 1, ANSWER: 4, 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    CNAME    www.a.shifen.com.
www.a.shifen.com.    30    IN    A    39.156.66.14
www.a.shifen.com.    30    IN    A    39.156.66.18

;; Query time: 31 msec
;; SERVER: 10.96.0.10#53(10.96.0.10)
;; WHEN: 四 8月 12 11:58:31 CST 2021
;; MSG SIZE  rcvd: 247

 

相關文章