kubectl expose command¶
The kubectl expose command is used to create a [[Service]] resource for a workload, such as a [[Deployment]], Pod, or ReplicationController^[400-devops__06-Kubernetes__k8s-learning__05.service__service.md].
Usage¶
To expose a deployment, the basic syntax requires specifying the resource type and name. You can map the service port to a target port on the containers using the --port and --target-port flags^[400-devops__06-Kubernetes__k8s-learning__05.service__service.md].
Creating a ClusterIP Service¶
By default, executing kubectl expose generates a Service of type ClusterIP^[400-devops__06-Kubernetes__k8s-learning__05.service__service.md]. For example, the following command exposes port 8000 on the service and forwards traffic to port 80 on the selected pods:
[kubectl](<./kubectl.md>) expose deploy nginx-deployment --port=8000 --target-port=80
This command creates a service that receives a stable ClusterIP (e.g., 10.96.87.175) accessible from within the cluster^[400-devops__06-Kubernetes__k8s-learning__05.service__service.md].
Creating a NodePort Service¶
To expose the service externally, the --type flag can be set to NodePort^[400-devops__06-Kubernetes__k8s-learning__05.service__service.md]. This allocates a specific port on the cluster nodes (e.g., 30427) that routes to the service port.
[kubectl](<./kubectl.md>) expose deploy nginx-deployment --port=8000 --target-port=80 --type=NodePort
Behavior¶
Load Balancing¶
The Service created by kubectl expose automatically acts as a load balancer for the underlying pods^[400-devops__06-Kubernetes__k8s-learning__05.service__service.md]. Traffic directed at the Service IP is distributed across the backing endpoints, which can be verified by repeatedly querying the service IP and observing different responses.
In-Cluster Discovery¶
Once created, the service is accessible to other pods within the cluster using standard DNS discovery^[400-devops__06-Kubernetes__k8s-learning__05.service__service.md]. Clients can connect using either the short service name or the fully qualified domain name (FQDN):
* Short name: nginx-deployment-service:8080
* FQDN: nginx-deployment-service.default.svc:8080
Related Concepts¶
- [[Service]]
- Kubernetes
- [[Deployment]]
Sources¶
400-devops__06-Kubernetes__k8s-learning__05.service__service.md