本文解释kubernetes中涉及到的各种proxy。
参考文档:https://kubernetes.io/docs/concepts/cluster-administration/proxies/
proxy
在使用kubernetes时可能会遇到如下几种proxy。
1.kubectl proxy
- runs on a user’s desktop or in a pod
- proxies from a localhost address to the Kubernetes apiserver
- client to proxy uses HTTP
- proxy to apiserver uses HTTPS
- locates apiserver
- adds authentication headers
以上是官方文档原文内容,个人认为不准确且有误导性。第一条说kubectl proxy运行在用户桌面或者是一个pod中,实际是可根据情况运行在任何合适的位置。第二条,说的是kubectl proxy将localhost地址代理到kubernetes apiserver。实际是在运行kubectl proxy命令时通过设置address选项,可以指定任何本机可用的网口,如果不指定的话默认值才是localhost。
kubectl proxy有很多选项,详细参考这里。简单的运行命令如下:
$ kubectl proxy --address=xxx.xxx.xxx.xxx --port=8080 &
本质上kubectl proxy为访问kubernetes apiserver的REST api充当反向代理角色,这里反向代理的作用与通常意义上的反向代理作用相同,比如提供统一入口进行访问控制、监控、管理,在代理中管理后端,在代理中进行认证等。当然可以不经过kubectl proxy反向代理直接访问kubernetes apiserver的REST api,但是需要手动管理kubernetes apiserver的地址、手动获取token、手动将token加请到请求的头部,相对来说要繁琐而已。
2.apiserver proxy
- is a bastion built into the apiserver
- connects a user outside of the cluster to cluster IPs which otherwise might not be reachable
- runs in the apiserver processes
- client to proxy uses HTTPS (or http if apiserver so configured)
- proxy to target may use HTTP or HTTPS as chosen by proxy using available information
- can be used to reach a Node, Pod, or Service
- does load balancing when used to reach a Service
apiserver作为用户与kubernetes集群交互的接口,负责响应用户请求,与此同时,它本身也是一个访问集群内部资源的代理。例如,集群内有一个名为service_name的服务,端口号是port_name,这个服务本身具备集群IP,但是众所周知集群IP是一个虚拟IP,对于集群以外的世界来说,这个IP无法被识别。那么如何从外部世界访问这个服务呢?一种方法就是通过本节所介绍的apiserver proxy,当然前提条件是外界能够访问到apierver ,如果不能的话可以按第一节所介绍的kubectl proxy为apiserver设置反向代理,使它能够被外部世界访问。手动构建如下格式请求:
https:: http://apiserver address/api/v1/namespaces/namespace_name/services/service_name:[port_name]/proxy
在上例中,通过服务名称、服务端口号称、服务所属的名称空间,通过apiserver的代理实现对服务的访问,至于访问最终是如何路由到真正运行中的容器实例由kubernetes系统内部的机制实现。
3.kube proxy
- runs on each node
- proxies UDP and TCP
- does not understand HTTP
- provides load balancing
- is just used to reach services
kube proxy运行在集群中的每一个节点上,专门用于访问service的路由。当在集群内部访问某个service时,就是由它将集群IP映射成pod IP,或者说将流量转发到运行中的pod实例上,如果存在多个pod实例,kube proxy同时也会负责负载均衡。
4.位于apiserver之前的proxy或者负载均衡器
- existence and implementation varies from cluster to cluster (e.g. nginx)
- sits between all clients and one or more apiservers
- acts as load balancer if there are several apiservers.
这里与第一节中的kubectl proxy的概念一致,就是位于apiserver之前,专门用于访问apiserver的代理或者负载均衡器。kubectl proxy其中的一种实现方式,也可以通过其它技术实现如nginx等以提供更多的功能,如果有多个apiserver,在提供代理的同时也提供多个apiserver之间的负载均衡。
5.处理外部的云负载均衡器
- are provided by some cloud providers (e.g. AWS ELB, Google Cloud Load Balancer)
- are created automatically when the Kubernetes service has type LoadBalancer
- use UDP/TCP only
- implementation varies by cloud provider.
由云服务商提供的负载均衡器,在创建service时,如果指定其类型为LoadBalancer,则对服务的代理、负载均衡将会绕过默认的kube proxy,而是由设定的外部云服务商提供的负载均衡器负责。