Services

Services


Kubernetes Services provide a way to expose an application running as a set of Pods. They provide an abstract way for clients to access applications without needing to be aware of the application's Pods.
Service Routing
Clients make requests to a Service, which routes traffic to its Pods in a load-balanced fashion.
Endpoints
Endpoints are the backend entities to which Services route traffic. For a Service that routes traffic to multiple Pods, each Pod will have an endpoint associated with the Service.
Tip: One way to determine which Pod(s) a Service is routing traffic to is to look at that service's Endpoints.
  • Create a deployment.
vi deployment-svc-example.yml kubectl create -f deployment-svc-example.yml
apiVersion: apps/v1 kind: Deployment metadata: name: deployment-svc-example spec: replicas: 3 selector: matchLabels: app: svc-example template: metadata: labels: app: svc-example spec: containers: - name: nginx image: nginx:1.19.1 ports: - containerPort: 80
  • Create a ClusterIP Service to expose the deployment's Pods within the cluster network.
vi svc-clusterip.yml kubectl create -f svc-clusterip.yml
apiVersion: v1 kind: Service metadata: name: svc-clusterip spec: type: ClusterIP selector: app: svc-example ports: - protocol: TCP port: 80 targetPort: 80
  • Get a list of the Service's endpoints.
kubectl get endpoints svc-clusterip
  • Create a busybox Pod to test your service.
vi pod-svc-test.yml kubectl create -f pod-svc-test.yml
apiVersion: v1 kind: Pod metadata: name: pod-svc-test spec: containers: - name: busybox image: radial/busyboxplus:curl command: ['sh', '-c', 'while true; do sleep 10; done']
  • Run a command within the busybox Pod to make a request to the service.
kubectl exec pod-svc-test -- curl svc-clusterip:80
You should see the Nginx welcome page, which is being served by one of the backend Pods created earlier using a Deployment.
  • Create a NodePort Service to expose the Pods externally.
vi svc-nodeport.yml kubectl create -f svc-nodeport.yml
apiVersion: v1 kind: Service metadata: name: svc-nodeport spec: type: NodePort selector: app: svc-example ports: - protocol: TCP port: 80 targetPort: 80 nodePort: 30080
Test the service by making a request from your browser to http://<Control Plane Node Public IP>:30080. You should see the Nginx welcome page.