k8s 三种 Service

本文简单介绍 k8s 的三种 Service: ClusterIP、NodePort、LoadBalancer。

ClusterIP

ClusterIP 通过集群内部 IP 地址暴露服务,但该地址仅在集群内部可见,无法被集群外部的客户端访问。ClusterIP 是 Service 的默认类型,内部 IP 建议由 k8s 动态指定一个,也支持手动指定。示例:

1
2
3
4
5
6
7
8
9
10
11
apiVersion: v1
kind: Service
metadata:
name: nginx-pod-service
spec:
type: ClusterIP
ports:
- port: 8080
targetPort: 80
selector:
app: nginx

创建 ClusterIP 后,查看内部 IP,并进行访问:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
root@cloud:~# kubectl get svc -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6d2h <none>
nginx-pod-service ClusterIP 10.100.23.74 <none> 8080/TCP 6s app=nginx
root@cloud:~# curl 10.100.23.74:8080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

NodePort

NodePort 是 ClusterIP 的增强类型,它在 ClusterIP 的基础之上,在每个节点上使用一个相同的端口号将外部流量引入到该 Service 上来。示例:

1
2
3
4
5
6
7
8
9
10
11
12
apiVersion: v1
kind: Service
metadata:
name: nginx-pod-service
spec:
type: NodePort
ports:
- port: 8080
targetPort: 80
nodePort: 30080
selector:
app: nginx

创建后,在集群外可以通过节点IP:30080访问该服务。

LoadBalancer

LoadBalancer 是 NodePort 的增强类型,为节点上的 NodePort 提供一个外部负载均衡器,需要公有云支持。示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: v1
kind: Service
metadata:
name: nginx-pod-service
spec:
type: LoadBalancer
ports:
- port: 8080
targetPort: 80
nodePort: 30080
loadBalancerIP: 1.2.3.4
selector:
app: nginx

创建后,在集群外可以通过1.2.3.4:30080访问该服务。

Author

王亮

Posted on

2022-06-05

Licensed under