kubectl expose: Usage, Options & Common CI Errors
Generate a Service in front of a workload in one command.
kubectl expose creates a Service that load-balances to the pods of a workload, deriving the selector from the target. It is a quick imperative way to make a Deployment reachable in a preview or test cluster.
What it does
kubectl expose deploy/web --port=80 --target-port=8080 creates a Service whose selector matches the Deployment's pod labels, mapping the Service port to the container's target-port. --type sets ClusterIP (default), NodePort, or LoadBalancer. It is the imperative twin of writing a Service manifest.
Common usage
kubectl expose deploy/web --port=80 --target-port=8080
kubectl expose deploy/web --type=LoadBalancer --port=80
kubectl expose pod/my-pod --port=6379 --name=redis
kubectl expose deploy/web --port=80 --dry-run=client -o yamlCommon errors in CI
The silent failure is a Service with no endpoints: if the workload has no labels (or expose picks a selector that matches nothing), the Service exists but kubectl get endpoints svc/web is empty, and every request hits a connection refused. Verify endpoints after exposing. "error: couldn't find port via --port flag" means the source has no obvious port to copy - pass --port explicitly. And a target-port mismatch (Service points at 80 but the container listens on 8080) gives connection failures even with healthy pods.