Pod可能因为各种原因发生故障而死掉,Deployment等Controller会通过动态创建和销毁Pod来保障应用整体的健壮性。
Pod是脆弱的,但应用是健壮的
。
每个Pod都有自己的IP地址,当controller用新的Pod替代发生故障的Pod时,新Pod会分配到新的IP地址,那这时客户端如何找到并访问这个服务呢??-----Service
一、创建Service
Kubernetes Service从逻辑上代表一组pod,具体哪些Pod由label挑选。
Service有自己的IP,这个IP是不变的。客户端只需要访问Service的IP,
Kubernetes则负责建立和维护Service与Pod的映射关系。无论后端Pod如何变化,对客户端不会有任何影响,因为Service没变。
# 编辑httpd_deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpd-deployment
spec:
selector:
matchLabels:
app: httpd # 通过标签选择被控制的pod
replicas: 3
template:
metadata:
labels:
app: httpd # 给pod打上标签,Service、Deployment 将会用这个 label 来挑选 Pod
spec:
containers:
- name: httpd
image: httpd
ports:
- containerPort: 80 # 转发到后端pod的端口号
Pod分配了各自的IP地址,但这些IP只能被Kubernetes Cluster中的容器与节点访问。
# 编辑httpd_service.yaml
apiVersion: v1
kind: Service
metadata:
name: httpd-service # 必填,service名称
spec:
selector:
app: httpd # 必填,在selector字段中指定了为哪一个标签的app进行负载均衡
ports: # 将 Service 的 8080 端口映射到 Pod 的 80 端口,使用 TCP 协议
- protocol: TCP
port: 8080 # service监听端口
targetPort: 80 # 转发到后端pod的端口号
httpd-service分配到一个CLUSTER-IP,可以通过该IP访问后端的httpd Pod。
除了我们创建的 httpd-svc,还有一个 Service kubernetes,Cluster 内部通过这个 Service 访问 kubernetes API Server。

kubectl describe service httpd-service
查看service与Pod的对应关系:

二、Service IP原理
Service的Cluster IP在哪里配置的?Cluster IP又是怎样与Pod IP映射的??---iptables
Service Cluster-ip是个虚拟的IP,是由kubernetes节点上iptables规则管理的。
通过
sudo iptables-save
命令打印当前节点的 iptables 规则,因输出较多,这里只截取与 httpd-service Cluster IP 10.98.165.152 相关的信息:
$ sudo iptables-save | grep '10.98.165.152'
-A KUBE-SERVICES ! -s 10.244.0.0/16 -d 10.98.165.152/32 -p tcp -m comment --comment