Article Directory
Reference video : https://ke.qq.com/user/index/index.html#/plan/cid=1709963&term_id=102815140
1. Concept
1.1.Service存在的意义
1. Prevent Pod from losing connection (service discovery)
2. Define a set of Pod access strategies (load balancing)
1.2.三种常用类型
(1) ClusterIP (used inside the cluster)
By default, assign a stable IP address, namely VIP, which can only be accessed within the cluster
(2) NodePort (exposed application)
Enable a port on each node to expose the service, which can be accessed outside the cluster through NodeIP: NodePort
(3) LoadBalancer (externally exposed application, suitable for public cloud)
Similar to NodePort, a port is enabled on each node to expose services. In addition, K8s requests the load balancer of the underlying cloud platform to add each [Node IP]:[NodePort] as a backend
Two, Service proxy mode
Service is implemented by kube-proxy
Implement load balancing rules in two ways, namely iptables and IPVS
2.1.iptables模式
View rules
iptables-save |grep <Service Name>
Implementation process
接受流量->概率分配请求->根据分配请求转发到实际Pod
2.2.IPVS模式【推荐使用】
2.2.1.修改代理模式为ipvs
Load ip_vs related kernel modules
modprobe ip_vs
modprobe ip_vs_rr
modprobe ip_vs_wrr
modprobe ip_vs_sh
Set the mode to ipvs
kubectl edit configmaps kube-proxy -nkube-system
Delete the Pod of kube-proxy to make the configuration file effective
kubectl delete pod kube-proxy-9lvgh -nkube-system
Check the Pod log to see that it has been changed to ipvs mode
ipvsadm -Ln #查看规则
Three, example
3.1.tomcat-service.yaml
apiVersion: v1
kind: Service
metadata:
name: tomcat-service
spec:
type: NodePort
ports:
- port: 8080
name: service-port
nodePort: 31005
- port: 8005
name: shutdown-port
selector:
tier: frontend
kubectl apply -f tomcat-service.yaml
3.2.解释
A Service named tomcat-service is defined, the service ports are 8080 and 8005, and the NodePort is used to provide services to the outside world. All Pod examples with the label "tier=frontend" belong to it.
3.3.验证
kubectl get svc
Tomcat-service assigns a ClusterIP of 10.1.9.124, the service's virtual ports are 8080 and 8005, 8080 specifies the nodePort port as 31005, and 8005 is not specified, K8S will randomly assign a port to it.
3.3.1.集群内通过ClusterIP+虚端口可以访问服务
3.3.2.集群外通过NodeIP+nodePort端口可以访问Service服务
kubectl get endpoints
10.244.1.15 is the IP address of the Pod, and port 8080 is the port exposed by the container, which can be accessed through PodIP+port number
kubectl get svc tomcat-service -o yaml
You can see more detailed information about Service, such as name, namespace, clusterIP, virtual port
The port port is the port of ClusterIP, which is used for access within the cluster;
targetPort is the port number exposed by the container that provides the service. If the targetPort is not specified in the yaml file, the default targetPort is the same as the port