Learn about Service in Kubernetes

As I said in the previous tutorial, after creating the Deployment for our application, this application will only be accessible inside the Nodes of the cluster. For the outside of the cluster to be accessible, we need to use the Service object by running the “expose” command.

For example, I have a Deployment object created with the following spec:

Now I will expose this Deployment with the “expose” command as follows:

with:

  • node-hello is the name of the Deployment in Kubernetes,
  • –type is a Deployment type that will be exposed. There are 4 types that we can expose, that is: ClusterIp (the application can only access within the cluster, this is the default type in case we do not pass the –type parameter in the above statement), NodePort (application can access from outside Node via Node’s IP address), LoadBalancer (application can access from outside the cluster through Cloud Provider Endpoint) and ExternalName (if you want to set a domain pointing to the application)
  • — port is the port that will be exposed to the outside
  • and –target-port is the port of the application inside the cluster.

My results after running the above command will be as follows:

Since I am using Kubernetes locally, if I request to http://localhost:8080/ on my machine at this time, you will see the following result:

Learn about Service in Kubernetes

So we have already successfully exposed the application!

You can get information about all the services in the Kubernetes cluster using the following command:

My result is as follows:

If you now run the command to describe our new service:

you will see the following result:

We can also create the Service object directly from the Pod.

In this case, the Service will use Label and Selector to select the Pod to expose. For example, I have a Pod named “huongdanjava-app” created by the spec as follows:

Learn about Service in Kubernetes

Then, I can define the following spec to create a new Service that exposes “huongdanjava-app” Pod to the outside:

The result after creating a new Service from this spec file:

Go to http://localhost:8080/, you also see the same results as when I exposed from the Deployment object.

We can delete any Service using the kubectl delete statement as follows:

My example is as follows:

Result:

Add Comment