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
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.
Using this in CI
A runner has no kubeconfig, no cached context, and no interactive auth. Every kubectl invocation in CI needs the context supplied explicitly, and most confusing CI failures here are the command running against the wrong cluster or no cluster at all.
# never rely on the ambient context on a runner
kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get pods
# confirm what you are actually connected to before mutating anything
kubectl config current-context
kubectl cluster-info
# fail fast instead of hanging on an unreachable API server
kubectl --request-timeout=30s get nodesKey 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.