Understanding Kubernetes Ports: Port, NodePort, TargetPort, and ContainerPort
This article explains the four Kubernetes port types—Port, NodePort, TargetPort, and ContainerPort—their distinct roles in service exposure, internal pod communication, and how they are configured using YAML manifests.
This article explains the four Kubernetes port types—Port, NodePort, TargetPort, and ContainerPort—and their distinct roles in service exposure and pod communication.
Port is the service port (clusterIP:port) that internal cluster clients use to reach a service.
NodePort is a port on the node that exposes the service externally, allowing traffic from outside the cluster.
TargetPort is the pod port that receives traffic forwarded by kube-proxy from the service; it maps to the container's port.
ContainerPort is the port defined inside the container; TargetPort maps to this port.
In summary, Port and NodePort are service‑level ports (Port for internal access, NodePort for external access). Traffic arriving at either port passes through kube-proxy to the pod’s TargetPort and finally to the container’s ContainerPort.
Below is a sample configuration that defines a Pod with a container port and a Service of type NodePort exposing it:
apiVersion: v1
kind: Pod
metadata:
name: nginx
namespace: dev
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.20.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80 # 容器端口
---
apiVersion: apps/v1
kind: Service
metadata:
name: nginx
spec:
type: NodePort # 有配置 NodePort,外部可访问 k8s 中的服务
ports:
- name: nginx
port: 80 # 服务的访问端口
protocol: TCP
targetPort: 80 # pod 端口,映射到容器端口
nodePort: 30080 # NodePort,通过 nodePort 类型的 service 暴露给集群外部访问
selector:
app: nginx----------------------end---------------------
Recommended reading: additional articles on Kubernetes best practices, namespace management, resource files, and deployment strategies.
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.