>_ IzzyLab

Hands-on task

This task is step 7 of the course “Kubernetes: first steps”

A Service for the website

easy~10 min

Deployment web is already running — two pods serving the shop's website. But reaching the pods directly is awkward: there are several of them, and their addresses change when they restart. That's what a Service is for in Kubernetes.

Create a Service web on port 80 that leads to this Deployment's pods. Then open the website through it: the home page has a code word — write it to /root/code.txt.

What you'll practise:
  • kubernetes
  • service
  • kubectl expose
  • port-forward
  • curl

Topic breakdown

Every pod has its own IP address, but you can't rely on it: the pod is recreated — the address is different. And with several replicas, it's unclear which one to go to.

A Service solves both problems. It's a permanent address and name inside the cluster with a group of pods behind it. The Service decides which pods belong to the group by labels: for example, all pods labeled app=api. The Service spreads requests across them. The pod addresses it currently leads to are shown by kubectl get endpoints <name>.

A Service has two ports: port — the one the Service itself listens on, and targetPort — where in the pod it passes the request.

Other pods in the cluster reach a Service simply by name: http://api. From outside the cluster you can forward a port to it with kubectl port-forward. Example for a Service api with port 8000:

kubectl get services                         # list services
kubectl port-forward svc/api 9000:8000 &     # localhost:9000 → service api:8000
curl localhost:9000
kill %1                                      # stop the forwarding

What's checked

  1. Service web listens on port 80
  2. The website opens through Service web
  3. /root/code.txt contains the code word from the website

What it looks like