Exposing Kubernetes Pods Using Services

Introduction

Kubernetes Services are a great way to combine Kubernetes networking with the dynamic and often automated nature of Kubernetes applications. In this lab, you will use Services to expose existing Kubernetes Pods. This will allow you to practice your skills with Kubernetes Services.

Solution

Log in to the server using the credentials provided:

ssh cloud_user@<PUBLIC_IP_ADDRESS>

Expose the Pods from the User-db Deployment as an Internal Service

  1. Examine the properties of the user-db deployment by using kubectl get deployment user-db -o yaml.

  2. In the deployment properties, find the spec and look for the Pod template, paying particular attention to the labels, especially the label app: user-db.

  3. Take note of which port(s) are exposed.

  4. Start creating a Service that will expose its Pods to other components within the cluster by using vi user-db-svc.yml.

  5. Define the Service by using:

    apiVersion: v1 
    kind: Service 
    metadata: 
      name: user-db-svc 
    spec: 
      type: ClusterIP 
      selector: 
        app: user-db 
      ports: 
      - protocol: TCP 
        port: 80 
        targetPort: 80
    
  6. Save and exit the file by hitting the ESC key and using :wq.

  7. Finish creating the Service by using kubectl create -f user-db-svc.yml.

  8. Test the Service to make sure it works by using kubectl exec busybox -- curl user-db-svc. It may not work right away, so you may need to wait a few minutes and try again, but you should be able to see the Nginx welcome page.

Expose the Pods from the Web-frontend Deployment as an External Service

  1. Now, examine the properties of the frontend deployment by using kubectl get deployment web-frontend -o yaml.

  2. Check the labels applied to the Pod template. You should see the label app=web-frontend.

  3. Take note of which port(s) are exposed.

  4. Start creating a Service that will expose its Pods on port 30080 of each cluster node by using vi web-frontend-svc.yml.

  5. Define the Service by using:

    apiVersion: v1 
    kind: Service 
    metadata: 
      name: web-frontend-svc 
    spec: 
      type: NodePort 
      selector: 
        app: web-frontend 
      ports: 
      - protocol: TCP 
        port: 80 
        targetPort: 80 
        nodePort: 30080
    
    1. Save and exit the file by hitting the ESC key and using :wq.
  6. Finish creating the Service by using kubectl create -f web-frontend-svc.yml.

  7. Test the Service from outside the cluster (such as in a browser) by navigating to http://<PUBLIC_IP_ADDRESS>:30080.