8、通过 Service 访问 Pod、Service IP 原理、DNS 访问 Service、外网访问 Service

Pod 是脆弱的,但应用是健壮的。
每个 Pod 都有自己的 IP 地址。当 controller 用新 Pod 替代发生故障的 Pod 时,新 Pod 会分配到新的 IP 地址。这样就产生了一个问题:
如果一组 Pod 对外提供服务(比如 HTTP),它们的 IP 很有可能发生变化,那么客户端如何找到并访问这个服务呢?
Kubernetes 给出的解决方案是 Service。


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

来看个例子,创建下面的这个 Deployment:

[root@master ~]# vim httpd.yml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: httpd
spec:
  replicas: 3
  selector:
     matchLabels:
        run: httpd
  template:
    metadata:
      labels:
        run: httpd
    spec:
      containers:
      - name: httpd
        image: httpd
        ports:
        - containerPort: 80

 label 是 run: httpd,Service 将会用这个 label 来挑选 Pod。

启动了三个 Pod,运行 httpd 镜像

[root@master ~]# kubectl apply -f httpd.yml 
deployment.apps/httpd created
root@master ~]# kubectl get pod -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP             NODE    NOMINATED NODE   READINESS GATES
httpd-7fbd549b67-gx7j8   1/1     Running   0          11s   10.244.1.187   node1   <none>           <none>
httpd-7fbd549b67-vkfjr   1/1     Running   0          11s   10.244.2.211   node2   <none>           <none>
httpd-7fbd549b67-x9hd4   1/1     Running   0          11s   10.244.1.188   node1   <none>           <none>

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

[root@master ~]# curl 10.244.1.187
<html><body><h1>It works!</h1></body></html>
[root@master ~]# curl 10.244.2.211
<html><body><h1>It works!</h1></body></html>
[root@master ~]# curl 10.244.1.188
<html><body><h1>It works!</h1></body></html>
[root@master ~]# 

接下来创建 Service,其配置文件如下:

[root@master ~]# vim httpd-svc.yml 

apiVersion: v1
kind: Service
metadata:
  run: httpd-svc
spec:
  selector:
    run: httpd
  ports:
  - protocol: TCP
    port: 8080
    targetPort: 80

① v1 是 Service 的 apiVersion。
② 指明当前资源的类型为 Service。
③ Service 的名字为 httpd-svc。
④ selector 指明挑选那些 label 为 run: httpd 的 Pod 作为 Service 的后端。
⑤ 将 Service 的 8080 端口映射到 Pod 的 80 端口,使用 TCP 协议。

[root@master ~]# kubectl apply  -f httpd-svc.yml 
service/httpd-svc created
[root@master ~]# kubectl get service
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
httpd-svc    ClusterIP   10.1.189.69   <none>        8080/TCP   3s
kubernetes   ClusterIP   10.1.0.1       <none>        443/TCP    4d3h
[root@master ~]# curl 10.1.189.69: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@master ~]# kubectl describe service httpd-svc
Name:              httpd-svc
Namespace:         default
Labels:            <none>
Annotations:       <none>
Selector:          name=httpd
Type:              ClusterIP
IP Families:       <none>
IP:                10.1.189.69
IPs:               10.1.189.69
Port:              <unset>  8080/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.187:80,10.244.2.211:80,10.244.2.211:80
Session Affinity:  None
Events:            <none>
[root@master ~]# 

Endpoints 罗列了三个 Pod 的 IP 和端口。我们知道 Pod 的 IP 是在容器中配置的,那么 Service 的 Cluster IP 又是配置在哪里的呢?CLUSTER-IP 又是如何映射到 Pod IP 的呢?

答案是 iptables

注意一个情况:为啥我配置的Service不能用,这里我自己瞎弄发现  service拒绝连接

root@master ~]# curl 10.1.189.69:8080
curl: (7) Failed connect to 10.1.189.69:8080; 拒绝连接

selector 指 label 都为 run: httpd 的 Pod 作为 Service 的后端才能用

还有这个selector 指 label 都为 name: httpd 的 Pod 作为 Service 的后端才能用

Service IP 原理

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

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

-A KUBE-SERVICES ! -s 10.244.0.0/16 -d 10.1.189.69/32 -p tcp -m comment --comment "default/httpd-svc cluster IP" -m tcp --dport 8080 -j KUBE-MARK-MASQ
-A KUBE-SERVICES -d 10.1.189.69/32 -p tcp -m comment --comment "default/httpd-svc cluster IP" -m tcp --dport 8080 -j KUBE-SVC-IYRDZZKXS5EOQ6Q6

这两条规则的含义是:

  1. 如果 Cluster 内的 Pod(源地址来自 10.244.0.0/16)要访问 httpd-svc,则允许。

  2. 其他源地址访问 httpd-svc,跳转到规则 KUBE-SVC-IYRDZZKXS5EOQ6Q6

KUBE-SVC-IYRDZZKXS5EOQ6Q6 规则如下:

-A KUBE-SVC-IYRDZZKXS5EOQ6Q6 -m comment --comment "default/httpd-svc" -m statistic --mode random --probability 0.33333333349 -j KUBE-SEP-4OTFVC4PSPALWTSI
-A KUBE-SVC-IYRDZZKXS5EOQ6Q6 -m comment --comment "default/httpd-svc" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-4ZYPSPZKMIWVXQ7T
-A KUBE-SVC-IYRDZZKXS5EOQ6Q6 -m comment --comment "default/httpd-svc" -j KUBE-SEP-OHZ4PUVOZRBXMVEY
  1. 1/3 的概率跳转到规则 KUBE-SEP-4OTFVC4PSPALWTSI

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

  3. 1/3 的概率跳转到规则 KUBE-SEP-OHZ4PUVOZRBXMVEY

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

-A KUBE-SEP-4OTFVC4PSPALWTSI -s 10.244.1.197/32 -m comment --comment "default/httpd-svc" -j KUBE-MARK-MASQ
-A KUBE-SEP-4OTFVC4PSPALWTSI -p tcp -m comment --comment "default/httpd-svc" -m tcp -j DNAT --to-destination 10.244.1.197:80
-A KUBE-SEP-4ZYPSPZKMIWVXQ7T -s 10.244.1.198/32 -m comment --comment "default/httpd-svc" -j KUBE-MARK-MASQ
-A KUBE-SEP-4ZYPSPZKMIWVXQ7T -p tcp -m comment --comment "default/httpd-svc" -m tcp -j DNAT --to-destination 10.244.1.198:80
-A KUBE-SEP-OHZ4PUVOZRBXMVEY -s 10.244.2.216/32 -m comment --comment "default/httpd-svc" -j KUBE-MARK-MASQ
-A KUBE-SEP-OHZ4PUVOZRBXMVEY -p tcp -m comment --comment "default/httpd-svc" -m tcp -j DNAT --to-destination 10.244.2.216:80

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

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

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

除了直接通过 Cluster IP 访问到 Service,DNS 是更加便捷的方式

DNS 访问 Service

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

kubeadm 部署时会默认安装 dns 组件

[root@master ~]# kubectl get deployment --namespace=kube-system
NAME      READY   UP-TO-DATE   AVAILABLE   AGE
coredns   2/2     2            2           7d1h

有的默认装的是kube-dns组件

å¾ç

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

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

[root@master ~]# kubectl run busybox --rm -ti --image=busybox /bin/sh
If you don't see a command prompt, try pressing enter.
/ # wget httpd-svc.default:8080
Connecting to httpd-svc.default:8080 (10.1.189.69:8080)
saving to 'index.html'
index.html           100% |************************************|    45  0:00:00 ETA
'index.html' saved

如上所示,我们在一个临时的 busybox Pod 中验证了 DNS 的有效性。另外,由于这个 Pod 与 httpd-svc 同属于 default namespace,可以省略 default 直接用 httpd-svc 访问 Service。

[root@master ~]# kubectl run busybox --rm -ti --image=busybox /bin/sh
If you don't see a command prompt, try pressing enter.
/ # wget httpd-svc:8080
Connecting to httpd-svc:8080 (10.1.189.69:8080)
saving to 'index.html'
index.html           100% |************************************|    45  0:00:00 ETA
'index.html' saved

用 nslookup 查看 httpd-svc 的 DNS 的信息。报错

[root@master grub2]# kubectl run busybox --rm -ti --image=busybox /bin/sh
If you don't see a command prompt, try pressing enter.
/ # nslookup httpd-svc
Server:		10.1.0.10
Address:	10.1.0.10:53

** server can't find httpd-svc.default.svc.cluster.local: NXDOMAIN

*** Can't find httpd-svc.svc.cluster.local: No answer
*** Can't find httpd-svc.cluster.local: No answer
*** Can't find httpd-svc.default.svc.cluster.local: No answer
*** Can't find httpd-svc.svc.cluster.local: No answer
*** Can't find httpd-svc.cluster.local: No answer

发现解析不了:

发现都说是busybox镜像的问题,从1.28.4以后的镜像都存在这问题。把镜像换成1.28.3试试?修改yaml版本号:

[root@master grub2]# vim busybox.deploy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: busybox-deployment
spec:
  replicas: 1
  selector:
     matchLabels:
        name: busybox
  template:
    metadata:
      labels:
        name: busybox
    spec:
      restartPolicy: Always
      containers:
      - name: busybox
        command:
        - sleep
        - "3600"
        image: busybox:1.28.3
[root@master grub2]# kubectl apply -f busybox.deploy.yaml 
deployment.apps/busybox-deployment created
[root@master grub2]# kubectl get pod
NAME                                  READY   STATUS    RESTARTS   AGE
busybox-deployment-57695f7547-p2dxd   1/1     Running   0          30s
httpd-7fbd549b67-5d2lf                1/1     Running   0          2d22h
httpd-7fbd549b67-f9b9n                1/1     Running   0          2d22h
httpd-7fbd549b67-hrv46                1/1     Running   0          2d22h

[root@master grub2]# kubectl exec -ti busybox-deployment-57695f7547-p2dxd sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
/ # nslookup httpd-svc
Server:    10.1.0.10
Address 1: 10.1.0.10 kube-dns.kube-system.svc.cluster.local

Name:      httpd-svc
Address 1: 10.1.189.69 httpd-svc.default.svc.cluster.local
/ # exit

确实可以成功解析域名了。

DNS 服务器是 kube-dns.kube-system.svc.cluster.local,这实际上就是 kube-dns 组件,它本身是部署在 kube-system namespace 中的一个 Service。

httpd-svc.default.svc.cluster.local 是 httpd-svc 的完整域名。

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

[root@master grub2]# kubectl get namespace
NAME              STATUS   AGE
default           Active   7d2h
kube-node-lease   Active   7d2h
kube-public       Active   7d2h
kube-system       Active   7d2h

在 kube-public 中部署 Service httpd2-svc,配置如下

[root@master ~]# vim httpd2.yml 

apiVersion: apps/v1
kind: Deployment
metadata:
  name: httpd2
  namespace: kube-public
spec:
  replicas: 3
  selector:
     matchLabels:
        name: httpd2

  template:
    metadata:
      labels:
        name: httpd2
    spec:
      containers:
      - name: httpd2
        image: httpd
        ports:
        - containerPort: 80

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

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

[root@master ~]# kubectl apply -f httpd2.yml 
deployment.apps/httpd2 created
service/httpd2-svc created

查看 kube-public 的 Service:

[root@master ~]# kubectl get service --namespace=kube-public
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
httpd2-svc   ClusterIP   10.1.205.127   <none>        8080/TCP   40s

 在 busybox Pod 中访问 httpd2-svc

[root@master ~]# kubectl exec -ti busybox-deployment-57695f7547-p2dxd sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
/ # wget httpd2-svc:8080
wget: bad address 'httpd2-svc:8080'
/ # wget httpd2-svc.kube-public:8080
Connecting to httpd2-svc.kube-public:8080 (10.1.130.235:8080)
index.html           100% |***********************************|    45   0:00:00 ETA
/ # 

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

 Kubernetes 集群内部可以通过 Cluster IP 和 DNS 访问 Service

外网访问 Service

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

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

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

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

下面我们来实践 NodePort,Service httpd-svc 的配置文件修改如下:

[root@master ~]# vim httpd-svc.yml 
apiVersion: v1
kind: Service
metadata:
  name: httpd-svc
spec:
  type: NodePort
  selector:
    name: httpd
  ports:
  - protocol: TCP
    port: 8080
    targetPort: 80

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

[root@master ~]# kubectl apply -f httpd-svc.yml 
service/httpd-svc configured
[root@master ~]# kubectl get service httpd-svc
NAME        TYPE       CLUSTER-IP    EXTERNAL-IP   PORT(S)          AGE
httpd-svc   NodePort   10.1.189.69   <none>        8080:30956/TCP   2d23h

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

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

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

[root@master ~]# netstat -an | grep 30956
tcp        0      0 0.0.0.0:30956           0.0.0.0:*               LISTEN     

下面测试 NodePort 是否正常工作。

[root@master ~]# curl 10.70.36.250:30956
<html><body><h1>It works!</h1></body></html>
[root@master ~]# curl 10.70.36.251:30956
<html><body><h1>It works!</h1></body></html>
[root@master ~]# curl 10.70.36.252:30956
<html><body><h1>It works!</h1></body></html>

解释:
Kubernetes 是如何将 <NodeIP>:<NodePort> 映射到 Pod 的呢?

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

-A KUBE-NODEPORTS -p tcp -m comment --comment "default/httpd-svc" -m tcp --dport 30956 -j KUBE-MARK-MASQ
-A KUBE-NODEPORTS -p tcp -m comment --comment "default/httpd-svc" -m tcp --dport 30956 -j KUBE-SVC-IYRDZZKXS5EOQ6Q6

规则的含义是:访问当前节点 30956 端口的请求会应用规则 KUBE-SVC-IYRDZZKXS5EOQ6Q6,内容为:

-A KUBE-SVC-IYRDZZKXS5EOQ6Q6 -m comment --comment "default/httpd-svc" -m statistic --mode random --probability 0.33333333349 -j KUBE-SEP-4OTFVC4PSPALWTSI
-A KUBE-SVC-IYRDZZKXS5EOQ6Q6 -m comment --comment "default/httpd-svc" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-4ZYPSPZKMIWVXQ7T
-A KUBE-SVC-IYRDZZKXS5EOQ6Q6 -m comment --comment "default/httpd-svc" -j KUBE-SEP-OHZ4PUVOZRBXMVEY

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

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

[root@master ~]# vim httpd-svc.yml 

apiVersion: v1
kind: Service
metadata:
  name: httpd-svc
spec:
  type: NodePort
  selector:
    name: httpd
  ports:
  - protocol: TCP
    nodePort: 30000
    port: 8080
    targetPort: 80

现在配置文件中就有三个 Port 了:
nodePort 是节点上监听的端口。
port 是 ClusterIP 上监听的端口。
targetPort 是 Pod 监听的端口。

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

应用新的 nodePort 并验证:

[root@master ~]# kubectl apply -f httpd-svc.yml 
service/httpd-svc configured
[root@master ~]# kubectl get service httpd-svc
NAME        TYPE       CLUSTER-IP    EXTERNAL-IP   PORT(S)          AGE
httpd-svc   NodePort   10.1.189.69   <none>        8080:30000/TCP   3d
[root@master ~]# curl 10.70.36.250:30000
<html><body><h1>It works!</h1></body></html>
[root@master ~]# curl 10.70.36.251:30000
<html><body><h1>It works!</h1></body></html>
[root@master ~]# curl 10.70.36.252:30000
<html><body><h1>It works!</h1></body></html>

 

nodePort: 30000 已经生效了。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值