Kubernetes服务可以在服务定义中有一个targetPort和port:

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 9376

端口和targetPort有什么区别?


当前回答

目标器端口说明

# pod file
apiVersion: v1
kind: Pod
metadata: 
  name: pod_name
  labels: 
     name: pod_ref
spec: 
  containers:
  - name: docker-container
    image: python:3:11
    ports: 
    - containerPort: 5000 # this is the target port which we need to access (target) from service file

---
apiVersion: v1
kind: Service
metadata: 
   name: service_config
   labels: 
     name: service_config_ref
spec:
   type: NodePort
   selector:
     name: pod_ref  # same as pod metadata match labels 
     ports:
      - targetPort: 5000 # this is where the pod is listening 
        port: 80 # this is where this service (this file) is going to listen. 
                 # If you call the port 80, it will reach the service, then the service will forward the port to port:5000


其他回答

这个答案是参考Kubernetes的文档以及其他答案:

https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/:

targetPort:容器接收流量的端口,

port:是抽象的服务端口,它可以是其他pod用来访问服务的任何端口

https://kubernetes.io/docs/concepts/services-networking/service/:

Pods中的端口定义有名称,您可以在服务的targetPort属性中引用这些名称。即使服务中有使用单一配置名称的pod的混合物,通过不同的端口号使用相同的网络协议,这种方法也有效。

targetport: pod中容器侦听的一个或多个端口。

nodeport:主要用于接受使用者请求。(例如:从消费者到运行在容器中的web服务器的HTTP请求)

Nodeport在所有接口上的所有节点上侦听,即0.0.0.0:Nodeport。发送到nodeport的使用者服务请求被路由到容器的targetport,以便容器能够满足该请求。

port: kubernetes pod网络中使用的端口,主要用于在pod之间交换请求。在这里,来自另一个pod的请求也被路由到腐蚀pod的容器targetport。

Summary:所有请求最终都到达targetport。如果请求来自k8s网络外部,则使用Nodeport;如果来自k8s网络内部,则使用port。

服务是一种抽象,用于将流量重定向到底层pod。 因此:

端口:80——>标识服务正在侦听的端口 targetPort: 8080——>标识部署底层pod的目标端口

对my_service:80的调用将把流量重定向到8080上的底层pod(根据给定的示例)。

我认为形象是最好的描述。

它帮助我从服务的角度考虑问题。

nodePort:节点上外部流量进入的端口 port:该服务的端口 targetPort pod上转发流量的目标端口

流量从nodePort进入,转发到服务上的port,然后路由到pod上的targetPort。

值得强调的是,nodePort用于外部流量。集群中其他可能需要访问服务的pod将只使用port,而不是nodePort,因为它只在内部访问服务。

另外值得注意的是,如果没有设置targetPort,它将默认为与port相同的值。例如,80:80服务端口80针对集装箱端口80。