What are Services in Kubernetes?
Services are resources in Kubernetes (like pods, deployments, etc.) that provide a single point of access from the outside world, into your pod(s) which run your application. That single point of access stays the same, no matter if your pods are moved to another node, changed or deleted entirely. Each service has an IP address and a port that never change, and the client always knows where to find the pods due to the flat nat-less network.
Create a Service
Let’s create a simple service in Kubernetes using our Linux Academy cloud servers. When creating a service, you specify a selector, which tells the service which pods to associate with it. So let’s first create a pod that the service can attach to. Perform this command to create the pod:
kubectl run nginx --image=nginx --restart=Never --port=80
Now that we have our pod created, we can create a service for it. Here is the YAML (nginx-svc.yaml) for a “NodePort” type service that will expose port 30080 on the node and direct the traffic to port 80 on the container:
apiVersion: v1kind: Servicemetadata:name: nginx-nodeportspec:type: NodePortports:- protocol: TCPport: 80targetPort: 80nodePort: 30080selector:run: nginx
We can now create our service by running the following command:
kubectl create -f nginx-svc.yaml
Now that we have created a service, let’s view the service by running the following command:
kubectl get svc
With every service, an endpoint is created to cache the IP addresses of the pods in that service. We can see our endpoints with the following command:
kubectl get ep
You’ll notice that the endpoint listed is the IP address of the pod and the container port 80 that we specified when we created the service. We can look at the IP address of the pod by performing the following command:
kubectl get po -o wide
Now that we’ve verified that all of our API objects have been created, including the pod, service, and endpoint, let’s try to communicate with the service as if we were a client trying to reach this application. We can do this by using curl to connect to the node port. Use the following command to do this:
curl localhost:30080You should receive the following response, which is the nginx welcome page:Congratulations!You have successfully created a service in Kubernetes!
More on Kubernetes
- Kubernetes Cheat Sheet
- Building a Three-Node Kubernetes Cluster | Quick Guide
- Running Prometheus on Kubernetes
- Getting Started with Kubernetes Using Minikube
Would you like to continue learning about the many other objects in Kubernetes and how they can benefit your application? Check out the Cloud Native Certified Kubernetes Administrator Course on Linux Academy