书籍来源:cloudman《每天5分钟玩转Kubernetes》
一边学习一边整理老师的课程内容及试验笔记,并与大家分享,侵权即删,谢谢支持!
Kubernetes Service从逻辑上代表了一组Pod,具体是哪些Pod则是由label来挑选的。Service有自己的IP,而且这个IP是不变的。客户端只需要访问Service的IP,Kubernetes则负责建立和维护Service与Pod的映射关系。无论后端Pod如何变化,对客户端不会有任何影响,因为Service没有变。
来看个例子,创建下面的这个Deployment,如下所示。
[root@k8s-master ~]# cat httpd.yml apiVersion: apps/v1kind: Deploymentmetadata: name: httpdspec: replicas: 3 selector: matchLabels: app: httpd template: metadata: labels: app: httpd spec: containers: - name: httpd image: httpd ports: - containerPort: 80[root@k8s-master ~]#
我们启动了三个Pod,运行httpd镜像,label是app: httpd,Service将会用这个label来挑选Pod,如图所示。
Pod分配了各自的IP,这些IP只能被Kubernetes Cluster中的容器和 节点访问,如图所示。
接下来创建Service,其配置文件如下所示。
[root@localhost ~]# cat httpd-svc.yml apiVersion: apps/v1kind: Deploymentmetadata: name: httpdspec: replicas: 3 selector: matchLabels: run: httpd template: metadata: labels: run: httpd spec: containers: - name: httpd image: httpd ports: - containerPort: 80---apiVersion: v1kind: Servicemetadata: name: httpd-svcspec: selector: run: httpd ports: - protocol: TCP port: 8080 targetPort: 80[root@localhost ~]#
① v1是Service的apiVersion。
② 指明当前资源的类型为Service。
③ Service的名字为httpd-svc。
④ selector指明挑选那些label为run: httpd的Pod作为Service的后端。
⑤ 将Service的8080端口映射到Pod的80端口,使用TCP协议。
执行kubectl apply创建Service httpd-svc,如图所示。
httpd-svc分配到一个CLUSTER-IP 10.106.95.163。可以通过该IP访问后端的httpd Pod,如图所示。
根据前面的端口映射,这里要使用8080端口。另外,除了我们创建的httpd-svc,还有一个Service kubernetes,Cluster内部通过这个 Service访问Kubernetes API Server。
通过kubectl describe可以查看httpd-svc与Pod的对应关系,如图所示。
Endpoints罗列了三个Pod的IP和端口。我们知道Pod的IP是在容器中配置的,那么Service的Cluster IP又是配置在哪里的呢?CLUSTER-IP又是如何映射到Pod IP的呢?
答案是iptables。
版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除