This tutorial aims to guide you on how to set up a Service in Kubernetes. A Service in Kubernetes is an abstract way to expose an application running on a set of Pods as a network service. This abstraction decouples the dependency between consumers and producers of the services.
By the end of this tutorial, you will:
Before you proceed, ensure that you have the following:
A Kubernetes Service is an abstraction which defines a logical set of Pods and a policy by which to access them. Services enable a loose coupling between dependent Pods.
To create a Service, you need to define it in a YAML file. Below is a simple example of a Service definition:
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 9376
Here is a breakdown of the above example:
apiVersion: v1 : This defines the version of Kubernetes API you're usingkind: Service : This means you're creating a Servicemetadata: : This section is for data about the Service like its namename: my-service : The name of your Servicespec: : This is where you'll specify the behavior of your Serviceselector: : This defines how the Service finds its Podsapp: MyApp : This selects any Pods with the label "app=MyApp"ports: : This is where you'll specify the ports the Service will listen onprotocol: TCP : The network protocol this Service will use. Kubernetes supports TCP, UDP, and SCTP.port: 80 : The port number the Service will listen ontargetPort: 9376 : The port number on the Pod that the Service will forward connections toTo apply the Service, run the following command:
kubectl apply -f service.yaml
This will create a Service that routes traffic to Pods labeled "app=MyApp" on port 9376.
In this tutorial, you learned about Kubernetes Services and how to set them up. You learned about their basic structure and how to write a Service definition in YAML. You then learned how to apply this definition to create a Service.
To continue learning about Kubernetes, you might want to explore Ingress, which is how Kubernetes manages external access to services in a cluster.
Solutions:
apiVersion: v1
kind: Service
metadata:
  name: test-service
spec:
  selector:
    app: TestApp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
To change the port, simply replace port: 80 with port: 1234.
For the third exercise, your YAML should look like this:
apiVersion: v1
kind: Service
metadata:
  name: test-service-2
spec:
  selector:
    app: TestApp2
  ports:
  - protocol: UDP
    port: 80
    targetPort: 8080
Remember to apply the YAML file with kubectl apply -f filename.yaml in each case.