kubernetes系统学习----掌握Service(三)

420 阅读1分钟

一、Service的详细作用
负载均衡,外网访问,DNS服务的搭建,Ingress7层路由机制

yaml格式的Service定义文件的完整内容如下:

apiVersion: v1                      //Requiredkind: Service                       //Requiredmetadata:                           //Required  name: string                    //Required  namespace: string               //Required  labels:    - name: string  annotations:    - name: stringspec:                                //Required  selector: []                     //Required  type: string                     //Required  clusterIP: string  sessionAffinity: string  ports:  - name: string  - protocol: string  - port: int  - targetPort: init  - nodePort: intstatus:    loadBalancer:    ingress:      ip: string      hostname: string  

创建服务

kubectl create -f servicexx.yaml

获得Pod的IP地址:

kubectl get pods -l app=webapp -o yaml |grep podIP

kubernetes提供了两种负载分发策略:RoundRobin和SessionAffinity


RoundRobin:轮询模式,轮询将请求转发到后端各个pod上

SessionAffinity:基于客户端IP地址进行会话保持的模式

可以通过service.spec.sessionAffinity=ClientIP来启用SessionAffinity策略


服务的自动添加,我们可以用

kubectl scale rc xxxxx --replicas = 2



3、集群外部访问Pod或者Service

有两种方式:

1)将容器应用的端口号映射到物理机

通过设置容器级别的hostPort,将容器应用的端口号映射到物理机上

pod-hostport.yaml

apiVersion: v1kind: Podmetadata:   name: webapp  labels:  app: webappspec:  containers:- name: webapp  image: tomcat  ports: - containerPort: 8080   hostPort: 8081    

通过命令创建

kubectl create -f pod-hostport.yaml

通过物理机的IP地址和8081端口号访问Pod的内部服务:

curl 192.168.18.3:8081

2)将service的端口号映射到物理机

1、通过设置nodePort映射到物理机,同时设置Service的类型为NodePort:

apiVersion: v1kind: Servicemetadata:  name: webappspec:  type: NodePort  ports: - port : 8080   targetPort: 8080   nodePort: 8081 selector:   app: webapp

创建Service

kubectl create -f xxxx.yaml

通过物理机的IP地址和nodePort 8081端口号访问服务:

curl 192.168.18.3:8081

更多技术文章请关注公众号:架构师Plus,
扫码添加

在这里插入图片描述