第六章 通过Service访问Pod(上)

不应该直接使用Pod的ID地址作为对外提供服务的接口,应为一旦Pod重启,IP地址就变化了,解决方案是使用Service。

6.1 创建Service

  K8s service从逻辑上代表了一组Pod,具体是哪些Pod则由label来挑选的。

     service有自己的IP,而且这个IP是不变的,客户端只需要访问Service的IP,K8s负责建立和维护service和Pod的映射关系。无论Pod如何变化,对客户端无影响。

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: httpd
spec:
  replicas: 3
  template:
    metadata:
      labels:
        run: httpd                     # 定义label给service用
    spec:
      containers:
      - name: httpd
        image: httpd
        ports:
        - containerPort: 80             # 容器对外暴露的端口

部署之后,可以直接通过IP地址(IP地址是随机的)访问Pod

kubeusr@GalaxyKubernetesMaster:~$ kubectl get pods -o wide
NAME                     READY     STATUS              RESTARTS   AGE       IP             NODE
httpd-749bf8c6f4-d86vf   1/1       Running             0          5m        10.244.1.209   galaxykubernetes02
httpd-749bf8c6f4-lwp5g   1/1       Running             0          5m        10.244.2.113   galaxykubernetes03
httpd-749bf8c6f4-pldb4   0/1       ContainerCreating   0          5m        <none>         galaxykubernetes01
kubeusr@GalaxyKubernetesMaster:~$ curl 10.244.1.209:80
<html><body><h1>It works!</h1></body></html>

 接下来定义service,并部署,

apiVersion: v1
kind: Service
metadata:
  name: httpd-svc              # service 名字
spec:
  selector:
    run: httpd                 # selector指明挑选 label为run:httpd 的Pod作为Service的后端。
  ports:
  - protocol: TCP                 
    port: 8080                 #  service的端口;     service的8080端口映射到Pod的80端口
    targetPort: 80             #  pod的端口

 如下,httpd-svc分配到一个CLUSTER-IP 10.101.103.107可以通过该IP访问后端的httpd Pod

kubeusr@GalaxyKubernetesMaster:~$ kubectl get service
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
httpd-svc    ClusterIP   10.101.103.107   <none>        8080/TCP   6s
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    127d
kubeusr@GalaxyKubernetesMaster:~$ curl 10.101.103.107:8080
<html><body><h1>It works!</h1></body></html>

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

kubeusr@GalaxyKubernetesMaster:~$ 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,"protocol":"TC...
Selector:          run=httpd
Type:              ClusterIP
IP:                10.101.103.107
Port:              <unset>  8080/TCP
TargetPort:        80/TCP
Endpoints:         10.244.1.209:80,10.244.2.113:80              # 罗列了三个Pod的id地址和端口。
Session Affinity:  None
Events:            <none>

 

  

  

  

  

posted @ 2018-12-29 10:47  刘大飞  阅读(529)  评论(0编辑  收藏  举报