How to create a Kubernetes Service
With the running application, we want to access one service. Let’s create a ClusterIP type of service. We can:
- Create a yaml manifest for the service and apply it, or
- Use the “kubectl expose” command creates a service without creating a yaml file.
Like all Kubernetes objects, services are defined in YAML or JSON. The YAML file consists of the following parts:
- apiVersion: v*
- kind: a service
- metadata.name: name of the service, which is the DNS name of the Service at the time of creation.
- spec.selector: the pods included in the Service. Here, any pod with the label app=user will be added to the service.
- spec.ports: list of port configurations, includes the following data:
- protocol: the network protocol to use with the port
- port: the port that incoming traffic goes to
- targetPort: the port on the pod that traffic should be sent to
Now, we will look into an example of YAML file:
- apiVersion: v2
- kind: Service
- metadata:
- name: service-backend
- spec:
- ports: port: 4000
- protocol: TCP
- targetPort: 333
- selector:
- run: deployment-backend
- type: ClusterIP
The service ‘service-backend’ will be created, and any pod in the cluster can access it on their port 333 via http://service-backend:4000, or at the cluster’s IP address using port 4000.
Kubernetes services can also be created using the ‘kubectl expose’ command, which does not require a YAML file. The same service can be created using the command:
kubectl expose deployment deployment-backend – – port=333- – target-port=4000 –name=service-backend
Once you’ve got the configuration complete, create the service in your cluster as below:
kubectl apply -f service.yaml
To check that your service is running, you can execute the following command:
kubectl get services
You can see your new service in the list of services returned by this command. You can now access your pods using the service.