服务发现 —— Service(主要用于服务内的网络共享)

负责东西流量(同层级/内部服务网络通信)的通信

一、Service 的定义

apiVersion: v1
kind: Service  # 资源类型为 Service
metadata:
  name: nginx-svc  # Service 名字
  labels:
    app: nginx-svc   # Service 自己本身的标签
spec:
  selector:   # 选中当前 service 匹配哪些 pod,对哪些 pod 的东西流量进行代理(配置后会自动生成 endpoint)
    app: nginx  # 所有匹配到这些标签的 pod 都可以通过该 service 进行访问
  ports:  # 端口映射
  - name: http   # service 端口配置名称
    protocol: TCP     # 端口绑定的协议,支持 TCP、UDP、SCTP,默认为 TCP
    port: 80     # service 自己的端口,在使用内网 ip 访问时使用
    targetPort: 9527   # 转发到目标 pod 的端口,
  - name: https
    port: 443
    protocol: TCP
    targetPort: 443
  type: NodePort # 随机启动一个端口(30000 ~ 32767),映射到ports中的端口,该端口是直接绑定在node上的,且集群中的每一个node都会绑定这个端口。
                 # 也可以用于将服务暴露给外部访问,但是这种方式实际生产环境不推荐,效率较低,而且Service 是四层负载。

一)常用类型

1、NodePort

会在所有安装了 kube-proxy 的节点都绑定一个端口,此端口可以代理至对应的 Pod,集群外部可以使用任意节点 ip + NodePort 的端口号访问到集群中对应 Pod 中的服务。
当类型设置为 NodePort 后,可以在 ports 配置中增加 nodePort 配置指定端口,需要在下方的端口范围内,如果不指定会随机指定端口
端口范围:30000~32767
端口范围配置在 /usr/lib/systemd/system/kube-apiserver.service 文件中

2、ClusterIP

只能在集群内部使用,不配置类型的话默认就是 ClusterIP,对于微服务可以绝大多数满足

3、ExternalName

返回定义的 CNAME 别名,可以配置为域名

4、LoadBalancer

使用云服务商(阿里云、腾讯云等)提供的负载均衡器服务

NodePort 和 LoadBalancer 均可实现外网暴露,但是不建议,因为效率不高

二)命令操作

# 创建 service
kubectl create -f nginx-svc.yaml
# 查看 service 信息,通过 service 的 cluster ip 进行访问
kubectl get svc 
# 查看 pod 信息,通过 pod 的 ip 进行访问
kubectl get po -owide
# 查看 service 详细信息(含 endpoint 关联的ip和端口)
kubectl describe svc nginx-svc
# 创建其他 pod 通过 service name 进行访问(推荐)
kubectl exec -it busybox -- sh
curl http://nginx-svc
# 默认在当前 namespace 中访问,如果需要跨 namespace 访问 pod,则在 service name 后面加上 .<namespace> 即可
curl http://nginx-svc.default

三)Endpoint

Service、Endpoint、Pod之间的关系
过程:外部请求 通过 api-server 根据ip 找到 Servie ,Service 再找到 endpoing,通过 iptables 的转发 找到目标服务器,通过目标服务器找到对应的容器,进入容器再执行。

图片描述

二、代理 k8s 外部服务

实现方式:

  1. 编写 service 配置文件时,不指定 selector 属性,就不会自动创建 endpoint
  2. 自己创建 endpoint

endpoint 配置:

apiVersion: v1
kind: Endpoints
metadata:
  labels:
    app: wolfcode-svc-external     # 与 service 一致!!!!!!!!!!!!
  name: wolfcode-svc-external      # 与 service 一致!!!!!!!!!!!!!
  namespace: default # 与 service 一致
subsets:
- addresses:
  - ip: <target ip> # 目标 ip 地址
  ports: # 与 service 一致
  - name: http    # **必须与 service 中 ports name 一致!!!!!!!!!!!!!!**
    port: 80
    protocol: TCP
图片描述

使用场景

  • 各环境访问名称统一
  • 访问 k8s 集群外的其他服务
  • 项目迁移

三、反向代理外部域名

apiVersion: v1
kind: Service
metadata:
  labels:
    app: wolfcode-external-domain
  name: wolfcode-external-domain
spec:
  type: ExternalName
  externalName: www.wolfcode.cn
posted @ 2023-10-14 16:50  yifanSJ  阅读(20)  评论(0编辑  收藏  举报