kubectl port-forward: Command Reference for CI/CD
Tunnel localhost straight into a pod or service for a smoke test.
kubectl port-forward opens a tunnel from a local port to a port inside a pod or service, with no ingress required. In CI it smoke-tests a freshly deployed service. This reference covers the flags and the readiness race that causes flaky connection-refused failures.
Common flags and usage
- port-forward svc/<name> LOCAL:REMOTE: forward to a service
- port-forward pod/<name> LOCAL:REMOTE: forward to a pod
- port-forward deploy/<name> LOCAL:REMOTE: forward to the newest pod
- --address: change the bind interface (default 127.0.0.1)
- Runs in the foreground; background it with & in CI
Example
shell
kubectl wait --for=condition=Ready pod -l app=web --timeout=120s
kubectl port-forward svc/web 8080:80 &
PF_PID=$!
trap 'kill $PF_PID' EXIT
until curl -sf http://localhost:8080/health; do sleep 1; done
# ... run smoke tests against localhost:8080 ...In CI
port-forward prints "Forwarding from..." before the pod is actually Ready, so an immediate curl hits connection refused. Gate on kubectl wait first, then poll the local port. Background the process and kill it in a trap so the step never hangs; the tunnel does not auto-reconnect if the pod restarts.
Key takeaways
- Wait for readiness before forwarding; the tunnel opens before pods are up.
- Poll the local port until it answers rather than curling immediately.
- Background it and kill in a trap so CI never hangs on the tunnel.
Related guides
kubectl Cheat Sheet: Commands for Everyday KubernetesA kubectl cheat sheet - get, describe, logs, apply, rollout, debug, and context commands for daily Kubernetes…
kubectl wait: Command Reference for CI/CDReference for kubectl wait: block on a condition (Ready, Available, complete, delete) with a timeout, the rig…
kubectl exec: Command Reference for CI/CDReference for kubectl exec: run a command inside a running container, the -- separator, container selection,…
kubectl get: Command Reference for CI/CDReference for kubectl get: list resources, output formats, label and field selectors, jsonpath extraction, an…