K8s port、targetPort和nodePort区别
在 Kubernetes 中,port
和 targetPort
是 Service 和 Pod 配置中的两个重要字段,用于定义网络流量的路由规则。以下是它们的详细解释和区别:
1. port
(Service 的端口)
- 定义:
port
是 Kubernetes Service 暴露的端口,用于接收集群内部或其他 Service 的请求。 - 作用:
- 其他 Pod 或 Service 通过
port
访问该 Service。 - 例如,如果 Service 的
port
是80
,其他 Pod 可以通过http://<service-name>.<namespace>.svc.cluster.local:80
访问该 Service。 - 示例
apiVersion: v1 kind: Service metadata:name: my-service spec:selector:app: my-appports:- protocol: TCPport: 80 # Service 暴露的端口targetPort: 8080 # Pod 的目标端口
- 其他 Pod 或 Service 通过
2. targetPort
(Pod 的目标端口)
- 定义:
targetPort
是 Service 将流量转发到的 Pod 的端口。 - 作用:
- 它指定 Pod 中实际监听流量的端口(即容器暴露的端口)。
- 如果未显式指定
targetPort
,Kubernetes 默认使用port
的值。
- 示例:
apiVersion: v1
kind: Service
metadata:name: my-service
spec:selector:app: my-appports:- protocol: TCPport: 80 # Service 暴露的端口targetPort: 8080 # Pod 的目标端口(容器监听的端口)
3. nodePort
nodePort
是 Service 的一种类型(NodePort
)的扩展字段,用于将 Service 暴露到集群外部(通过节点的 IP 和端口)。port
和targetPort
是 Service 内部路由的字段,而nodePort
是外部访问的入口。- 示例:
apiVersion: v1
kind: Service
metadata:name: my-service
spec:type: NodePortselector:app: my-appports:- port: 80 # Service 内部端口targetPort: 8080 # Pod 的目标端口nodePort: 30007 # 节点暴露的端口(外部通过 <node-ip>:30007 访问)
4. 实际应用场景
- 场景 1:Pod 监听非标准端口
- 如果 Pod 的容器监听
8080
端口,但希望 Service 对外暴露80
端口:
- 如果 Pod 的容器监听
ports:- port: 80targetPort: 8080
- 场景 2:多端口 Service
ports:- name: httpport: 80targetPort: 8080- name: httpsport: 443targetPort: 8443
- 场景 3:直接使用
targetPort
作为容器端口- 如果 Pod 的容器端口和 Service 的
port
相同,可以省略targetPort
:ports:- port: 80 # 默认 targetPort 也是 80
- 如果 Pod 的容器端口和 Service 的
总结
port
:Service 暴露的端口,用于接收集群内部的请求。targetPort
:Pod 中实际监听流量的端口(容器端口)。nodePort
:仅用于NodePort
类型的 Service,用于外部访问。
通过合理配置 port
和 targetPort
,可以实现灵活的网络流量路由,适应不同的应用场景。