ClusterIP、NodePort 和 LoadBalancer 是 Kubernetes 中的服务类型,它们定义了服务暴露于网络的方式。它们决定了服务是否只能在集群内、从外部或通过外部负载平衡器访问。
本示例将演示如何创建每种类型的服务以及与每种服务相关的行为。我们将使用一个简单的 Nginx pod 作为应用程序。
【代码清单】
# nginx-deployment.apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
---
# clusterip-service.apiVersion: v1
kind: Service
metadata:
name: nginx-clusterip
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP
---
# nodeport-service.apiVersion: v1
kind: Service
metadata:
name: nginx-nodeport
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
nodePort: 30001
type: NodePort
---
# loadbalancer-service.apiVersion: v1
kind: Service
metadata:
name: nginx-loadbalancer
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
【执行结果】
应用这些配置后:ClusterIP服务(nginx-clusterip)将只能在Kubernetes集群内访问。NodePort服务(nginx-nodeport)将通过<NodeIP>:30001访问,允许使用节点的IP地址进行外部访问。LoadBalancer服务(nginx-loadbalancer)将提供一个外部IP地址(取决于云提供商),可用于访问服务。
该命令将显示分配给每个服务的 IP 地址和端口。
ClusterIP 是默认服务类型,用于群集中的内部通信。NodePort 在群集中的所有节点上打开一个特定端口,并将流量从该端口转发到服务。LoadBalancer 与 AWS 或 GCP 等云提供商提供的外部负载平衡器集成。这种服务类型会自动创建一个外部 IP 地址并设置必要的路由,以便将流量转发到服务。必须了解的是,使用 NodePort 或 LoadBalancer 可能会将您的应用程序暴露在互联网上,如果安全防护不当,可能会带来安全风险。
【小知识】
ClusterIP 服务类型通常与 Ingress 资源结合使用,以管理对服务的外部访问,而无需单独暴露每个服务。Ingress 控制器可根据请求的主机名或路径将流量路由到不同的服务,比单独使用 NodePort 或 LoadBalancer 更具灵活性。