NodePort Service in Kubernetes: What It Is and How It Works
NodePort service in Kubernetes exposes a pod on a static port on each node's IP address, allowing external traffic to access the service. It acts like a doorway on every node that forwards requests to the service inside the cluster.How It Works
Imagine your Kubernetes cluster as a building with many rooms (pods) inside. Each room has a service that you want to reach from outside the building. A NodePort service opens a fixed door on every floor (node) of the building. Anyone outside can knock on that door (the node's IP and port) and get connected to the right room inside.
Technically, Kubernetes assigns a port number from a predefined range (usually 30000-32767) on every node. When traffic comes to this port on any node, Kubernetes forwards it to the service, which then routes it to the correct pod. This way, you can access your application without needing a load balancer or complex network setup.
Example
This example shows a simple NodePort service exposing a pod running an HTTP server on port 80. The service listens on port 30080 on each node.
apiVersion: v1 kind: Service metadata: name: example-nodeport spec: type: NodePort selector: app: example-app ports: - port: 80 targetPort: 80 nodePort: 30080
When to Use
Use a NodePort service when you want to expose your application outside the Kubernetes cluster without a cloud provider's load balancer. It is useful for development, testing, or small setups where you can access nodes directly.
For example, if you run Kubernetes on your local machines or on bare metal servers, NodePort lets you reach your app by using the IP address of any node and the assigned port. However, for production environments with many users, a load balancer or ingress controller is usually better.
Key Points
- NodePort exposes a service on a static port on all cluster nodes.
- It forwards traffic from the node port to the service's target pods.
- Port range is usually 30000-32767 but can be configured.
- Allows external access without a cloud load balancer.
- Best for simple or development environments.