In the previous article, we discussed the ClusterIP service type. In this one, we’ll briefly cover the NodePort service type, which allows us to expose a service as an entry point to the public network.
Kubernetes Manifests Example
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 2
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: nginx:1.25-alpine # Using Nginx as an example
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: my-service-nodeport
spec:
selector:
app: my-app
ports:
- port: 80 # Service port (inside cluster)
targetPort: 80 # Pod container port
nodePort: 30080 # Fixed NodePort (must be in 30000–32767 range)
type: NodePort
As we can see from the above K8s manifests
- Exposes the service on a static port (range 30000 – 32767) on every nodes’ IP
- Accessible via http://<NodeIP>:<NodePort>
- Basic, but not great for production (no DNS, limited load balancing)
You can run the following commands to try this out locally using kind.
Firstly, we need to configure the cluster to map your host port to the node’s (actually the container’s) port.
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
extraPortMappings:
- containerPort: 30080 # Container Internal Port(NodePort)
hostPort: 30080 # Host Port Mapping
protocol: TCP
Run this command to create a cluster using the configuration above
kind create cluster --name my-cluster --config kind-config.yaml
Creating cluster "my-cluster" ...
✓ Ensuring node image (kindest/node:v1.34.0) 🖼
✓ Preparing nodes 📦
✓ Writing configuration 📜
✓ Starting control-plane 🕹️
✓ Installing CNI 🔌
✓ Installing StorageClass 💾
Set kubectl context to "kind-my-cluster"
You can now use your cluster with:
kubectl cluster-info --context kind-my-cluster
Have a question, bug, or feature request? Let us know! https://kind.sigs.k8s.io/#community 🙂
Run the following command to apply the K8s manifests from the beginning of this article
kubectl --context kind-my-cluster apply -f deployment-service-nodeport.yaml
Run the following command to take a look at the services
kubectl --context kind-my-cluster get svc
Run the following command to access the pod via NodePort
curl http://127.0.0.1:30080
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>