Service: kubectl expose

Another way to create a service is by using kubectl expose command.

kubectl expose <resource-type> <resource-name> --port=<port> --target-port=<target-port> --type=<type>
  • <resource-type>: Type of Kubernetes resource (pod, deployment, replicaset, etc.).

  • <resource-name>: Name of the resource to expose.

  • --port: The external port to expose.

  • --target-port: The port on the container to forward traffic to.

  • --type: Type of service (ClusterIP, NodePort, LoadBalancer, or ExternalName).

  • --name: Name of newly created service.

Expose as ClusterIP Service

First lets create a simple deployment object using nginx image with name my-server.

➜ kubectl create deployment my-server --image=nginx
deployment.apps/my-server created
➜ kubectl get deployments.apps                                      
NAME        READY   UP-TO-DATE   AVAILABLE   AGE
my-server   1/1     1            0           10s
postgres    1/1     1            1           25h
simple-go   3/3     3            3           25h

Then lets create a service with type ClusterIP using kubectl exec command. Since ClusterIP is the default type we don't need to specify the --type argument.

As we can see above the command will create a service name my-server that exposes deployment named my-server. We also can get the details in yaml format using command kubectl get service my-server -o yaml.

Expose as NodePort Service

Lets delete our previous service and then expose our deployment again as NodePort service. We need to delete the previous service because the expose command by default will name the service same as deployment name.

Because NodePort is not the default service type, we need to explicitly specify the service type using --type in expose command.

Now it exposed as NodePort and you can try to access it using the minikube IP and the service PORT. But if you use minikube on Mac using docker driver like me you will need minikube service to expose it.

Expose as LoadBalancer Service

No lets create another service but with type LoadBalancer. This time we explicitly specify the service name using --name argument.

This command below will create a service with type LoadBalancer and name my-server-lb.

Run minikube tunnel on the other terminal and test it using curl.

Expose Pod Directly

We can also directly expose a pod but this is not recommended in production.

For example lets expose the my-server pod.

The command above will create a ClusterIP service that expose the pod my-server-78b5bb4ccc-7cbxf.

This is not recommended because as we can see below this service is tied to a specific pod. So if that pod is replaced or upgraded, the service will not work.

References

Last updated