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&