“Can I just access this pod on localhost?” Yes you can, and here’s two ways to do it.
Port-forward (quick local access)#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # Forward pod port to localhost
kubectl port-forward pod/my-pod 8080:80
# Forward service port to localhost
kubectl port-forward service/my-service 8080:80
# Forward deployment port
kubectl port-forward deployment/my-app 8080:80
# Specify namespace
kubectl port-forward -n my-namespace pod/my-pod 8080:80
# Listen on all interfaces (not just localhost)
kubectl port-forward --address 0.0.0.0 pod/my-pod 8080:80
|
Access: Open http://localhost:8080 in browser
Note: Port-forward terminates when you close the terminal. Use Ctrl+C to stop.
NodePort (persistent external access)#
Quick one-liner to expose deployment#
1
2
3
4
5
6
7
8
| # Expose deployment as NodePort service
kubectl expose deployment my-app --type=NodePort --port=80 --target-port=8080
# With specific NodePort
kubectl expose deployment my-app --type=NodePort --port=80 --target-port=8080 --name=my-service
# Expose pod
kubectl expose pod my-pod --type=NodePort --port=80
|
Or create service with YAML#
1
2
3
4
5
6
7
8
9
10
11
12
| apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: NodePort
selector:
app: my-app
ports:
- port: 80 # Service port
targetPort: 8080 # Container port
nodePort: 30080 # External port (30000-32767 range)
|
Or patch existing service#
1
2
3
4
5
| # Change service type to NodePort
kubectl patch service my-service -p '{"spec":{"type":"NodePort"}}'
# Set specific NodePort
kubectl patch service my-service -p '{"spec":{"ports":[{"port":80,"nodePort":30080}]}}'
|
Access NodePort service#
1
2
3
4
5
6
7
8
| # Get NodePort
kubectl get service my-service
# Access via node IP
curl http://<node-ip>:30080
# If running locally (minikube/kind)
curl http://localhost:30080
|
Quick comparison#
| Method | Use case | Persistence |
|---|
| port-forward | Quick debugging, local dev | Session-based |
| NodePort | Testing, temp external access | Persistent |
| LoadBalancer | Production external access | Persistent + managed |
Common use cases#
Debug service locally#
1
2
| kubectl port-forward service/api 3000:3000
# Access on http://localhost:3000
|
Access database temporarily#
1
2
| kubectl port-forward service/postgres 5432:5432
psql -h localhost -U postgres
|
Quick UI testing#
1
2
| kubectl port-forward deployment/frontend 8080:80
# Open http://localhost:8080
|
Multiple ports#
1
| kubectl port-forward pod/my-pod 8080:80 8443:443
|
Pro tip: Port-forward is great for development. Don’t use it in production - use Ingress or LoadBalancer instead.