如何访问pod --- service(7)

一、通过service访问pod

  我们不应该期望 Kubernetes Pod 是健壮的,而是要假设 Pod 中的容器很可能因为各种原因发生故障而死掉。Deployment 等 controller 会通过动态创建和销毁 Pod 来保证应用整体的健壮性。换句话说,Pod 是脆弱的,但应用是健壮的

  每个 Pod 都有自己的 IP 地址。当 controller 用新 Pod 替代发生故障的 Pod 时,新 Pod 会分配到新的 IP 地址。这样就产生了一个问题:

  如果一组 Pod 对外提供服务(比如 HTTP),它们的 IP 很有可能发生变化,那么客户端如何找到并访问这个服务呢?

  Kubernetes 给出的解决方案是 Service

1、创建service

  Kubernetes Service 从逻辑上代表了一组 Pod,具体是哪些 Pod 则是由 label 来挑选。Service 有自己的 IP,而且这个 IP 是不变的。客户端只需要访问 Service 的 IP,Kubernetes 则负责建立和维护 Service 与 Pod 的映射关系。无论后端 Pod 如何变化,对客户端不会有任何影响,因为 Service 没有变。

  创建下面的这个 Deployment:(查看支持的apiversion使用命令:kubectl api-versions)

[root@ren7 yaml]# cat httpd1.yaml 
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: httpd-deployment
spec:
  replicas: 3
  template:
    metadata:
      labels:
        name: httpd
        run: httpd
    spec:
      containers:
      - name: httpd-app
        image: reg.yunwei.com/learn/httpd:latest
        ports:
        - containerPort: 80

2、部署并查看pod

  启动了三个 Pod,运行 httpd 镜像,label 是 run: httpd,Service 将会用这个 label 来挑选 Pod。

[root@ren7 yaml]# kubectl apply -f httpd1.yaml 
deployment.extensions/httpd-deployment created
[root@ren7 yaml]# kubectl get pod -o wide
NAME                                READY   STATUS    RESTARTS   AGE   IP              NODE           NOMINATED NODE   READINESS GATES
httpd-deployment-6d86d899b5-4drq5   1/1     Running   0          14s   172.20.33.83    192.168.11.6   <none>           <none>
httpd-deployment-6d86d899b5-rvx8z   1/1     Running   0          14s   172.20.72.171   192.168.11.5   <none>           <none>
httpd-deployment-6d86d899b5-v5wmz   1/1     Running   0          14s   172.20.33.84    192.168.11.6   <none>           <none>

3、集群内部测试连通性

  Pod 分配了各自的 IP,这些 IP 只能被 Kubernetes Cluster 中的容器和节点访问。

扫描二维码关注公众号,回复: 7608936 查看本文章
[root@ren7 yaml]# curl 172.20.33.84
<html><body><h1>It works!</h1></body></html>
[root@ren7 yaml]# curl 172.20.33.83
<html><body><h1>It works!</h1></body></html>
[root@ren7 yaml]# curl 172.20.72.171
<html><body><h1>It works!</h1></body></html>

4、接下来创建service,其配置文件如下:

[root@ren7 yaml]# cat httpd-svc.yaml 
apiVersion: v1
kind: Service
metadata:
  name: httpd-svc
spec:
  ports: 
    - port: 8080
      targetPort: 80
      protocol: TCP
  selector:
    run: httpd

  ① v1 是 Service 的 apiVersion。

  ② 指明当前资源的类型为 Service。

  ③ Service 的名字为 httpd-svc。

  ④ selector 指明挑选那些 label 为 run: httpd 的 Pod 作为 Service 的后端。

  ⑤ 将 Service 的 8080 端口映射到 Pod 的 80 端口,使用 TCP 协议。

5、执行 kubectl apply 创建 Service httpd-svc

[root@ren7 yaml]# kubectl apply -f httpd-svc.yaml 
service/httpd-svc created
[root@ren7 yaml]# kubectl get service
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
httpd-svc    ClusterIP   10.68.226.108   <none>        8080/TCP   12s
kubernetes   ClusterIP   10.68.0.1       <none>        443/TCP    2d1h

  httpd-svc 分配到一个 CLUSTER-IP 10.68.226.108。可以通过该 IP 访问后端的 httpd Pod。

[root@ren7 yaml]# curl 10.68.226.108
curl: (7) Failed connect to 10.68.226.108:80; 拒绝连接
[root@ren7 yaml]# curl 10.68.226.108:8080
<html><body><h1>It works!</h1></body></html>

  根据前面的端口映射,这里要使用 8080 端口。另外,除了我们创建的 httpd-svc,还有一个 Service kubernetes,Cluster 内部通过这个 Service 访问 kubernetes API Server。

  通过 kubectl describe 可以查看 httpd-svc 与 Pod 的对应关系。

[root@ren7 yaml]# kubectl describe service httpd-svc
Name:              httpd-svc
Namespace:         default
Labels:            <none>
Annotations:       kubectl.kubernetes.io/last-applied-configuration:
                     {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"name":"httpd-svc","namespace":"default"},"spec":{"ports":[{"port":8080,"...
Selector:          run=httpd
Type:              ClusterIP
IP:                10.68.226.108
Port:              <unset>  8080/TCP
TargetPort:        80/TCP
Endpoints:         172.20.33.83:80,172.20.33.84:80,172.20.72.171:80
Session Affinity:  None
Events:            <none>
[root@ren7 yaml]# kubectl get pod -o wide
NAME                                READY   STATUS    RESTARTS   AGE   IP              NODE           NOMINATED NODE   READINESS GATES
httpd-deployment-6d86d899b5-4drq5   1/1     Running   0          15m   172.20.33.83    192.168.11.6   <none>           <none>
httpd-deployment-6d86d899b5-rvx8z   1/1     Running   0          15m   172.20.72.171   192.168.11.5   <none>           <none>
httpd-deployment-6d86d899b5-v5wmz   1/1     Running   0          15m   172.20.33.84    192.168.11.6   <none>           <none>
  Endpoints 罗列了三个 Pod 的 IP 和端口。

二、Service IP 原理

  我们知道 Pod 的 IP 是在容器中配置的,那么 Service 的 Cluster IP 又是配置在哪里的呢?CLUSTER-IP 又是如何映射到 Pod IP 的呢?

  答案是 iptables

  Service Cluster IP 是一个虚拟 IP,是由 Kubernetes 节点上的 iptables 规则管理的。

  查看 SVC

[root@ren7 yaml]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
httpd-svc    ClusterIP   10.68.226.108   <none>        8080/TCP   10m
kubernetes   ClusterIP   10.68.0.1       <none>        443/TCP    2d1h

  可以通过 iptables-save 命令打印出当前节点的 iptables 规则,因为输出较多,这里只截取与 httpd-svc Cluster IP 10.68.226.108相关的信息:

[root@ren7 yaml]# iptables-save |grep 10.68.226.108
-A KUBE-SERVICES -d 10.68.226.108/32 -p tcp -m comment --comment "default/httpd-svc: cluster IP" -m tcp --dport 8080 -j KUBE-SVC-RL3JAE4GN7VOGDGP

  这条规则的含义是:如果 Cluster 内的 Pod要访问 httpd-svc,跳转到规则 KUBE-SVC-RL3JAE4GN7VOGDGP

  KUBE-SVC-RL3JAE4GN7VOGDGP 规则如下:

[root@ren7 yaml]# iptables-save |grep KUBE-SVC-RL3JAE4GN7VOGDGP
:KUBE-SVC-RL3JAE4GN7VOGDGP - [0:0]
-A KUBE-SERVICES -d 10.68.226.108/32 -p tcp -m comment --comment "default/httpd-svc: cluster IP" -m tcp --dport 8080 -j KUBE-SVC-RL3JAE4GN7VOGDGP
-A KUBE-SVC-RL3JAE4GN7VOGDGP -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-AYADGRA7HLSB6YHK
-A KUBE-SVC-RL3JAE4GN7VOGDGP -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-3IGLIDMQNZTXMCRT
-A KUBE-SVC-RL3JAE4GN7VOGDGP -j KUBE-SEP-XLZBWWZ3VO73ZBZY

  (1)1/3 的概率跳转到规则 KUBE-SEP-AYADGRA7HLSB6YHK

  (2)1/3 的概率(剩下 2/3 的一半)跳转到规则 KUBE-SEP-3IGLIDMQNZTXMCRT

  (3)1/3 的概率跳转到规则 KUBE-SEP-XLZBWWZ3VO73ZBZY

上面三个跳转的规则如下:

[root@ren7 yaml]# iptables-save |grep KUBE-SVC-RL3JAE4GN7VOGDGP
:KUBE-SVC-RL3JAE4GN7VOGDGP - [0:0]
-A KUBE-SERVICES -d 10.68.226.108/32 -p tcp -m comment --comment "default/httpd-svc: cluster IP" -m tcp --dport 8080 -j KUBE-SVC-RL3JAE4GN7VOGDGP
-A KUBE-SVC-RL3JAE4GN7VOGDGP -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-AYADGRA7HLSB6YHK
-A KUBE-SVC-RL3JAE4GN7VOGDGP -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-3IGLIDMQNZTXMCRT
-A KUBE-SVC-RL3JAE4GN7VOGDGP -j KUBE-SEP-XLZBWWZ3VO73ZBZY

[root@ren7 yaml]# iptables
-save |grep KUBE-SEP-AYADGRA7HLSB6YHK :KUBE-SEP-AYADGRA7HLSB6YHK - [0:0] -A KUBE-SEP-AYADGRA7HLSB6YHK -s 172.20.33.83/32 -j KUBE-MARK-MASQ -A KUBE-SEP-AYADGRA7HLSB6YHK -p tcp -m tcp -j DNAT --to-destination 172.20.33.83:80 -A KUBE-SVC-RL3JAE4GN7VOGDGP -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-AYADGRA7HLSB6YHK
[root@ren7 yaml]# iptables
-save |grep KUBE-SEP-3IGLIDMQNZTXMCRT :KUBE-SEP-3IGLIDMQNZTXMCRT - [0:0] -A KUBE-SEP-3IGLIDMQNZTXMCRT -s 172.20.33.84/32 -j KUBE-MARK-MASQ -A KUBE-SEP-3IGLIDMQNZTXMCRT -p tcp -m tcp -j DNAT --to-destination 172.20.33.84:80 -A KUBE-SVC-RL3JAE4GN7VOGDGP -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-3IGLIDMQNZTXMCRT

  即将请求分别转发到后端的三个 Pod。通过上面的分析,我们得到如下结论:

  iptables 将访问 Service 的流量转发到后端 Pod,而且使用类似轮询的负载均衡策略。

  另外需要补充一点:Cluster 的每一个节点都配置了相同的 iptables 规则,这样就确保了整个 Cluster 都能够通过 Service 的 Cluster IP 访问 Service。

三、DNS 访问 Service

  在 Cluster 中,除了可以通过 Cluster IP 访问 Service,Kubernetes 还提供了更为方便的 DNS 访问。

1、查看coredns

  kubeadm 部署时会默认安装 coredns 组件。

[root@ren7 yaml]# kubectl get deployment --namespace=kube-system
NAME                      READY   UP-TO-DATE   AVAILABLE   AGE
calico-kube-controllers   1/1     1            1           2d1h
coredns                   2/2     2            2           2d1h
heapster                  1/1     1            1           28h
kubernetes-dashboard      1/1     1            1           2d1h
monitoring-grafana        1/1     1            1           28h
monitoring-influxdb       1/1     1            1           28h

  coredns 是一个 DNS 服务器。每当有新的 Service 被创建,coredns 会添加该 Service 的 DNS 记录。Cluster 中的 Pod 可以通过 <SERVICE_NAME>.<NAMESPACE_NAME> 访问 Service。

2、dns访问

  比如可以用 httpd-svc.default 访问 Service httpd-svc。

[root@ren7 yaml]# kubectl run busybox --rm -it --image=reg.yunwei.com/learn/busybox:latest /bin/sh
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
If you don't see a command prompt, try pressing enter.
/ # 
/ # wget httpd-svc:8080
Connecting to httpd-svc:8080 (10.68.226.108:8080)
saving to 'index.html'
index.html           100% |*************************|    45  0:00:00 ETA
'index.html' saved
/ # 
/ # ls
bin         etc         index.html  root        tmp         var
dev         home        proc        sys         usr
/ # 
/ # cat index.html 
<html><body><h1>It works!</h1></body></html>
/ # 

  注意:wget httpd-svc:8080  后面的这个 port 必须是service的 port 不是nodeport

  由于这个 Pod 与 httpd-svc 同属于 default namespace,可以省略 default 直接用 httpd-svc 访问 Service。

3、查看namespace

  如果要访问其他 namespace 中的 Service,就必须带上 namesapce 了。kubectl get namespace 查看已有的 namespace。

[root@ren7 yaml]# kubectl get ns
NAME              STATUS   AGE
default           Active   2d1h
kube-node-lease   Active   2d1h
kube-public       Active   2d1h
kube-system       Active   2d1h

4、在 kube-public 中部署 Service httpd2-svc

  配置如下:

[root@ren7 yaml]# cat httpd2.yaml 
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: httpd2
  namespace: kube-public
spec:
  replicas: 2
  template:
    metadata:
      labels:
        name: httpd2
        run: httpd2
    spec:
      containers:
      - name: httpd-app2
        image: reg.yunwei.com/learn/httpd:latest
        ports:
        - containerPort: 80

---
apiVersion: v1
kind: Service
metadata:
  name: httpd-svc2
  namespace: kube-public
spec:
  ports: 
    - port: 8080
      targetPort: 80
      protocol: TCP
  selector:
    run: httpd2

5、创建资源

  通过 namespace: kube-public 指定资源所属的 namespace。多个资源可以在一个 YAML 文件中定义,用 --- 分割。执行 kubectl apply 创建资源:

[root@ren7 yaml]# kubectl apply -f httpd2.yaml 
deployment.extensions/httpd2 created
service/httpd-svc2 created

6、查看 kube-public 的 Service

[root@ren7 yaml]# kubectl get service -n kube-public
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
httpd-svc2   ClusterIP   10.68.175.116   <none>        8080/TCP   83s

7、在 busybox Pod 中访问 httpd2-svc

[root@ren7 yaml]# kubectl run busybox --rm -it --image=reg.yunwei.com/learn/busybox:latest /bin/sh
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
If you don't see a command prompt, try pressing enter.
/ # 
/ # wget httpd-svc2:8080
wget: bad address 'httpd-svc2:8080'
/ # wget httpd-svc2.kube-public:8080
Connecting to httpd-svc2.kube-public:8080 (10.68.175.116:8080)
saving to 'index.html'
index.html           100% |*************************|    45  0:00:00 ETA
'index.html' saved
/ # exit

  因为属于不同的 namespace,必须使用 httpd2-svc.kube-public 才能访问到。

四、外网访问service

  除了 Cluster 内部可以访问 Service,很多情况我们也希望应用的 Service 能够暴露给 Cluster 外部。Kubernetes 提供了多种类型的 Service,默认是 ClusterIP。

(1)ClusterIP 

  Service 通过 Cluster 内部的 IP 对外提供服务,只有 Cluster 内的节点和 Pod 可访问,这是默认的 Service 类型,前面实验中的 Service 都是 ClusterIP。

(2)NodePort 

  Service 通过 Cluster 节点的静态端口对外提供服务。Cluster 外部可以通过 <NodeIP>:<NodePort> 访问 Service。

(3)LoadBalancer 

  Service 利用 cloud provider 特有的 load balancer 对外提供服务,cloud provider 负责将 load balancer 的流量导向 Service。目前支持的 cloud provider 有 GCP、AWS、Azur 等。

第一步:实践 NodePort,Service httpd-svc 的配置文件修改如下:

[root@ren7 yaml]# cat httpd-svc3.yaml 
apiVersion: v1
kind: Service
metadata:
  name: httpd-svc3
spec:
  ports: 
    - port: 8080
      targetPort: 80
      protocol: TCP
  selector:
    run: httpd
  type: NodePort

  添加 type: NodePort,重新创建 httpd-svc。

第二步:创建service

[root@ren7 yaml]# kubectl apply -f httpd-svc3.yaml 
service/httpd-svc3 created
[root@ren7 yaml]# kubectl get service httpd-svc3
NAME         TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
httpd-svc3   NodePort   10.68.163.18   <none>        8080:33309/TCP   31s

  Kubernetes 依然会为 httpd-svc 分配一个 ClusterIP,不同的是:

  EXTERNAL-IP 为 nodes,表示可通过 Cluster 每个节点自身的 IP 访问 Service。

  PORT(S) 为 8080:33309。8080 是 ClusterIP 监听的端口(每个节点都有该端口),31785 则是节点上监听的端口。Kubernetes 会从 30000-32767 中分配一个可用的端口,每个节点都会监听此端口并将请求转发给 Service。

[root@ren7 yaml]# ss -tnl |grep 33309
LISTEN     0      128         :::33309                   :::*                  
[root@ren7 yaml]# netstat -anp |grep 33309
tcp6       0      0 :::33309                :::*                    LISTEN      6769/kube-proxy     

第三步:测试nodeport是否正常工作

[root@ren7 yaml]# curl 192.168.11.7:33309
<html><body><h1>It works!</h1></body></html>
[root@ren7 yaml]# curl 192.168.11.6:33309
<html><body><h1>It works!</h1></body></html>
[root@ren7 yaml]# curl 192.168.11.5:33309
<html><body><h1>It works!</h1></body></html>

  通过三个节点 IP + 32312 端口都能够访问 httpd-svc。

第四步:指定特定端口

  NodePort 默认是的随机选择,不过我们可以用 nodePort 指定某个特定端口。

[root@ren7 yaml]# cat httpd-svc3.yaml 
apiVersion: v1
kind: Service
metadata:
  name: httpd-svc3
spec:
  ports: 
    - port: 8080
      targetPort: 80
      protocol: TCP
      nodePort: 30000
  selector:
    run: httpd
  type: NodePort

  现在配置文件中就有三个 Port 了:

    (1)nodePort 是节点上监听的端口。

    (2)port 是 ClusterIP 上监听的端口。

    (3)targetPort 是 Pod 监听的端口。

  最终,Node 和 ClusterIP 在各自端口上接收到的请求都会通过 iptables 转发到 Pod 的 targetPort。

第五步:应用新的 nodePort 并验证:

[root@ren7 yaml]# kubectl apply -f httpd-svc3.yaml 
service/httpd-svc3 configured
[root@ren7 yaml]# kubectl get service httpd-svc3
NAME         TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
httpd-svc3   NodePort   10.68.163.18   <none>        8080:30000/TCP   11m
[root@ren7 yaml]# curl 192.168.11.7:30000
<html><body><h1>It works!</h1></body></html>
[root@ren7 yaml]# curl 192.168.11.6:30000
<html><body><h1>It works!</h1></body></html>
[root@ren7 yaml]# curl 192.168.11.5:30000
<html><body><h1>It works!</h1></body></html>

  nodePort: 30000 已经生效了。

  接下来我们深入探讨一个问题:Kubernetes 是如何将 <NodeIP>:<NodePort> 映射到 Pod 的呢?

  与 ClusterIP 一样,也是借助了 iptables。与 ClusterIP 相比,每个节点的 iptables 中都增加了下面两条规则:

第一步:查看svc端口

[root@ren7 yaml]# kubectl get svc
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
httpd-svc3   NodePort    10.68.163.18   <none>        8080:30000/TCP   14m
kubernetes   ClusterIP   10.68.0.1      <none>        443/TCP          2d2h

第二步:查看iptables规则

[root@ren7 yaml]# iptables-save |grep 30000
-A KUBE-NODEPORTS -p tcp -m comment --comment "default/httpd-svc3:" -m tcp --dport 30000 -j KUBE-MARK-MASQ
-A KUBE-NODEPORTS -p tcp -m comment --comment "default/httpd-svc3:" -m tcp --dport 30000 -j KUBE-SVC-6SKBCKMF764RHZ7U

  规则的含义是:访问当前节点 30000 端口的请求会应用规则 KUBE-SVC-6SKBCKMF764RHZ7U

第三步:相应规则 KUBE-SVC-6SKBCKMF764RHZ7U

[root@ren7 yaml]# iptables-save |grep KUBE-SVC-6SKBCKMF764RHZ7U
:KUBE-SVC-6SKBCKMF764RHZ7U - [0:0]
-A KUBE-NODEPORTS -p tcp -m comment --comment "default/httpd-svc3:" -m tcp --dport 30000 -j KUBE-SVC-6SKBCKMF764RHZ7U
-A KUBE-SERVICES -d 10.68.163.18/32 -p tcp -m comment --comment "default/httpd-svc3: cluster IP" -m tcp --dport 8080 -j KUBE-SVC-6SKBCKMF764RHZ7U
-A KUBE-SVC-6SKBCKMF764RHZ7U -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-IA4M5QE5UNCELJTW
-A KUBE-SVC-6SKBCKMF764RHZ7U -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-QQZFT4W6XUFVDYVI
-A KUBE-SVC-6SKBCKMF764RHZ7U -j KUBE-SEP-X3WAX2WQQAW2CUIE

  其作用就是负载均衡到每一个 Pod。

猜你喜欢

转载自www.cnblogs.com/renyz/p/11741046.html