Kubernetes has a lot of features and deployment options for running containers. One of these is the service. In this blog post, we’ll discuss what Services are, what they can be used for, and how to create them.
A Kubernetes service groups a set of pods together and makes them accessible through the DNS name of the service. This is useful because pods can be created and destroyed constantly, and without a service to make these pods accessible as a network service, you would need to implement a network discovery service to make calls between pods.
Luckily, Kubernetes makes it really easy to define a service. All you need is some way to select the pods that belong to your service.
Like everything else in Kubernetes, services can be configured using a YAML manifest:
apiVersion: v1
kind: Service
metadata:
name: user-service
spec:
selector:
app: user
ports:
- protocol: TCP
port: 80
targetPort: 9376
The YAML file consists of the following parts:
Once you’ve got the configuration complete, create the service in your cluster by doing the following:
kubectl apply -f service.yaml
To check that your service is running, you can execute the following command:
kubectl get services
You should see your new service in the list of services returned by this command. You can now access your pods using the service. In this example, the traffic for the user service might look like this in your cluster:
Of course, the whole purpose of creating a service is to make it possible to access a network service without having to know the pods it is running on. If you’re running Kubernetes 1.11 or higher, your cluster will automatically have CoreDNS installed, which will allow you to access your service by using the service’s name. Otherwise, you’ll have to install CoreDNS or kube-dns as an addon.
At this point, your service is all set, and you’ll be able to access in other parts of your application!
There are four types of services that are defined by how they expose the service outside the cluster. The service type is set by using one of the following values for spec.type:
Services make it really easy to create network services in Kubernetes. Each service can be backed with as many pods as needed without having to make your code aware of how each service is backed.
However, it can be hard to monitor Kubernetes with traditional tools. If you are looking for a monitoring solution, consider Blue Matador. Blue Matador automatically checks for over 25 Kubernetes events out-of-the-box. We also monitor over 20 AWS services in conjunction with Kubernetes, providing full coverage for your entire production environment with no alert configuration or tuning required. Learn more Kubernetes best practices at our Learn Kubernetes page.