1 概述
Service在很多情况下只是一个概念,真正起作用的其实是kube-proxy服务进程。
每个Node节点上都运行着一个kube-proxy服务进程,当创建Service的时候会通过api-server向etcd写入创建的service的信息,而kube-proxy会基于监听的机制发现这种Service的变动,然后他会将最新的Service的信息转换成对应的访问规则。
2 常见类型类型
名称 | 说明 |
ClusterIp | 用于内部调用。 |
NodePort | 指定端口可通过外部调用。 |
LoadBalancer | 借助工具,实现负载均衡。 |
ExternalName | 将外部端口映射到内部。比如短信接口。 |
3 三种IP
名称 | 说明 |
Node IP | node节点的网卡IP,ifconfig获得的ens33那个。 |
Pod IP | k8s创建pod后给与虚拟IP,可以通过kubectl get node -o wide命令查看。 |
Cluster IP |
4 三种端口
名称 | 说明 |
targetPort | 容器 ip |
port | pod IP |
nodePort | 物理机IP |
5 Service示例ClusterIp
5.1 deployment资源清单
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
volumes:
- name: html
emptyDir: {}
containers:
- name: nginx
image: nginx:1.20
ports:
- name: ng
containerPort: 80 #注意:这里的containerPort
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
5.2 service资源清单
apiVersion: v1
kind: Service
metadata:
name: cluster-ip-service
labels:
role: test #这个标签只是用于区分Service本身的。
spec:
selector: #label selector 一定要和pod的标签匹配
app: nginx
# clusterIP: 10.97.97.97 # service的ip地址,如果不写,默认会生成一个
type: ClusterIP #默认就是ClusterIp,可以不写
ports:
- name: svc-demo
port: 8080
protocol: TCP
targetPort: ng #80 # 目标端口必须是关联的Pod容器暴露的端口,使用pod中的端口名称更好
表示,创建一个Service,他的8080端口映射到具有标签app: nginx的Pod的ng端口上。
通过apply命令执行后,可以查看相关信息。
5.3 Service详情查看
kubectl get service
5.4 查看代理端口
kubectl get endpoints
5.5 测试
6 Service示例NodePort
6.1 deployment资源清单
使用.5.1
6.2 资源清单
apiVersion: v1
kind: Service
metadata:
name: node-port-service
labels:
role: test #这个标签只是用于区分Service本身的。
spec:
selector: #label selector 一定要和pod的标签匹配
app: nginx
type: NodePort #这个地方需要修改成NodePort
# clusterIP: 10.97.97.97 # service的ip地址,如果不写,默认会生成一个
ports:
- name: svc-demo
port: 8080
# nodePort: 30001 #不指定的话会随机生成一个nodePort
protocol: TCP
targetPort: ng #80 # 目标端口必须是关联的Pod容器暴露的端口,使用pod中的端口名称更好
6.3 查询service
kubectl get service -o wide
响应
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
node-port-service NodePort 10.106.205.110 <none> 8080:31122/TCP 2m57s app=nginx
其中ports中8080是cluster-ip的端口,cluster-ip在有kube-proxy的服务器上都可以使用。31122是服务器上注册的端口,可以通过该端口访问服务。
6.4 说明
不建议使用。端口比较少,且一种端口只能对应一种服务。
7 Service示例LoadBalancer
7.1 说明
- 使用LoadBalancer模式一般是由云服务商提供支撑,也就是如果在云服务商使用K8S,云服务商会提供相关功能。
- 如果自己部署的话,需要用到MetalLB负载均衡器。参考地址:Kubernetes 负载均衡器 - 晓风残月的博客
7.2 资源清单
apiVersion: v1
kind: Service
metadata:
name: loadbalancer-service
spec:
selector:
app: nginx
type: LoadBalancer
ports:
- name: svc-demo
port: 80
protocol: TCP
targetPort: ng
7.3 查询测试
7.4 说明
- 这个没弄成,不知道是哪里出问题了。内部访问可以,但浏览器访问不行。