To expose a service externally in Kubernetes, you can use the kubectl expose command. Here’s how to do it:
-
Create a Deployment (if you haven't already):
kubectl create deployment hello-world --image=nginx --replicas=1 -
Expose the Deployment as a Service:
Use the following command to expose the deployment as a service of typeNodePort:kubectl expose deployment hello-world --name=hello-service --port=80 --target-port=80 --type=NodePort--port: The port that the service will expose to external clients.--target-port: The port on the container where the service will route the traffic.--type=NodePort: This makes the service accessible on a specific port on each node in the cluster.
-
Verify the Service:
You can check the details of the service using:kubectl get services hello-service
This will show you the service details, including the assigned NodePort, which you can use to access the service externally.
