关于后端:Service-基础

明天开始来分享Service 的基础知识,后续咱们能够缓缓打磨,分享 Service 的进阶常识和原理

Service 基本概念

Service 是 K8S 最外围的概念了

咱们能够通过创立 Service ,为一组具备雷同性能的容器利用提供一个对立的入口地址,并且能够将申请散发到后端的各个容器利用上

咱们来看看实现的 Service 是什么样子的,咱们来手写一份

apiVersion: v1
kind: Service
metadata:
  name: service name
  namespace:
  labels:
  - name: label name
  annotations:
  - name: annotations name
spec:
  selector: []
  type:    string
  clusterIP: spec ip
  sessionAffinity: string
  ports:
  - name: ports name
    protocol: tcp/udp
    port: int
    targetPort: int
    nodePort: int
  status:
    loadBalancer:
      ingress:
        ip: string
        hostname: string
  

整一张表来解释一下下面某些字段的含意

属性字段 值类型 必须? 阐明
metadata.labels[] list no 自定义属性标签
metadata.annotations[] list no 自定义注解标签
spec.selector[] list yes 配置 label selector
抉择具备指定 label 标签的pod 作为治理范畴
spec.type string yes service 的类型
– ClusterIP

虚构服务的 ip,用于 K8S 外部 的pod 互相拜访
– NodePort
应用的是宿主机的端口,内部能够通过拜访 node 的 ip 和端口,就能够达到拜访外部服务的目标
– loadBalancer
应用外接的负载均衡器实现到服务的负载散发,须要在 loadBalancer 字段处指定内部负载均衡器的 ip 地址,并且同时须要定义 ClusterIP 和 NodePort
spec.ClusterIP string no 虚构服务的 ip 地址
如果 spec.type 指定的是 loadBalancer ,那么这个 ip 就须要写,其余的状况,能够不写,零碎默认调配
spec.sessionAffinity string no 是否反对 session
默认值是空,能够填咱们的 ClusterIP
性能是,将一个源 IP 地址的客户端拜访的申请,都转发到同一个后端 pod
spec.ports[].port int no 外部服务监听的端口
spec.ports[].targetPort int no 须要转发到 pod 的端口号
spec.ports[].nodePort int no 指定映射到物理机的端口号,这个时候须要 spec.type=NodePort
spec.status object no 属于内部均衡器,status 上面的都是 内部均衡器的配置了

Service 的名称定义

对于 service 的对象名称的定义也是须要遵循标准的

点我查看名称定义

例如截一个官网阐明的图

对于 service 的端口

定义 service 的时候,咱们能够定义 1 个端口,也能够定义 多个端口的

例如这样的是 service 的 1 个端口 ,官网的案例是外部服务监听 80 端口,会转发到 pod 的 9376 端口,用的是 tcp 协定

这样的是 2 个端口,属于 service 的多端口定义

例如咱们的服务开了多个端口,这些端口是不能定义抵触的,咱们必须要定义好每个端口的名称,端口号,以及协定,不能有歧义,如下:

上述的 1 个端口和多个端口,都是 服务监听的端口号,都是作为服务端的,须要客户端来拜访的

内部的 service

如果是咱们的 service 须要拜访内部的一个服务,须要和内部进行一个连贯,例如数据库服务,或者拜访内部的一个集群的时候,咱们须要如何写咱们的 service 呢?

咱们能够通过在 yaml 中 创立一个 无 Label Selector 的 Service 实现

咱们认真看一下,下面官网写的 1 个端口 和 多个端口的 yaml,都会应用 Label Selector 来指定一个 app,目标是为了运行起来之后可能关联到对应的 pod

例如这样

那么咱们来写一个 无 Label Selector 的服务吧

  • 无 Label Selector 的 Service
apiVersion: v1
kind: Service
metadata:
  name: xiaomotong-svc
spec:
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

写完这个 service 发现,他不晓得如何去找到 pod 的,那么咱们能够写一个 endpoints,名称须要和 下面这个service 的名称统一,这样 endpoints 指定的 pod ,就能够被 下面这个service 拜访到了

  • 写一个 Endpoints
apiVersion: v1
kind: Endpoints
metadata:
  name: xiaomotong-svc
subsets:
- addresses:
  - IP: 10.253.33.3
  ports:
  - port: 8080 

这样写,将 Endpoints 要和 下面的 service 就对应起来的, 感兴趣的 xdm 能够在本人的 k8s 集群下面玩一玩, 此处写的 subsets.addresses.IP 是一个可能运行的 pod ip

明天就到这里,学习所得,若有偏差,还请斧正

欢送点赞,关注,珍藏

敌人们,你的反对和激励,是我保持分享,提高质量的能源

好了,本次就到这里

技术是凋谢的,咱们的心态,更应是凋谢的。拥抱变动,背阴而生,致力向前行。

我是阿兵云原生,欢送点赞关注珍藏,下次见~

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理