K8s by Example: Services (NodePort)

NodePort exposes the Service on a port across all cluster nodes. Accessible from outside the cluster via node-ip:node-port. Port range: 30000-32767 (configurable).

service-nodeport.yaml

Set type: NodePort to expose on all nodes. You can specify nodePort or let Kubernetes assign one.

apiVersion: v1
kind: Service
metadata:
  name: my-app
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30080
  selector:
    app: my-app
terminal

NodePort is rarely used in production. It requires opening firewall ports and lacks load balancing across nodes.

$ kubectl get svc my-app
NAME     TYPE       CLUSTER-IP    PORT(S)        AGE
my-app   NodePort   10.96.0.100   80:30080/TCP   5m

$ kubectl get nodes -o wide
NAME     STATUS   EXTERNAL-IP
node-1   Ready    192.168.1.10
node-2   Ready    192.168.1.11

$ curl http://192.168.1.10:30080
Hello from my-app!
terminal

NodePort is useful for local development with minikube or kind. Use port-forward for quick access without NodePort.

$ minikube service my-app --url
http://192.168.49.2:30080

$ kubectl port-forward svc/my-app 8080:80
Forwarding from 127.0.0.1:8080 -> 8080

$ curl http://localhost:8080

Index | GitHub | Use arrow keys to navigate |