Creating Services with kubectl expose
The kubectl expose command creates Services imperatively without writing YAML files. It is a fast way to expose deployments, pods, or replica sets during development and debugging.
Exposing a Deployment
# Create a ClusterIP service (default)
kubectl expose deployment nginx-app --port=80 --target-port=8080
# Create a NodePort service
kubectl expose deployment nginx-app --type=NodePort --port=80 --target-port=8080
# Create a LoadBalancer service
kubectl expose deployment nginx-app --type=LoadBalancer --port=443 --target-port=8443
Specifying a Service Name
kubectl expose deployment backend --port=80 --target-port=3000 --name=backend-svc
Exposing a Pod Directly
kubectl expose pod my-pod --port=80 --target-port=5000 --name=pod-service
Verifying Service and Endpoints
After creating a Service, verify it is correctly routing to your pods:
# Check the service
kubectl get svc backend-svc
# View endpoints (the pod IPs backing the service)
kubectl get endpoints backend-svc
# Detailed information
kubectl describe svc backend-svc
Endpoints are automatically managed by Kubernetes. When pods matching the Service selector are added or removed, the endpoint list updates automatically.
Generating YAML from kubectl expose
Use the --dry-run flag to generate YAML without creating the resource:
kubectl expose deployment nginx-app \
--port=80 \
--target-port=8080 \
--type=ClusterIP \
--dry-run=client -o yaml > service.yaml
This is helpful when you want a starting template to customize before applying.