Kubernetes Service Cheatsheet

Overview

Kubernetes services are used to expose your pods outside of the cluster. Remembering how to write the structure of a service manifest can be difficult, and beyond the structure, just remembering which apiVersion to use can even more challenging.

In this post, you will learn how to structure a service manifest, as well as how to dynamically generate one on the fly using the kubectl create command.

Service Manifest

A typical Kubernetes configuration manifest is written and stored as a YAML file. The structure of a service manifest will look similar to the following example.

apiVersion: v1
kind: Service
metadata:
  name: hello-world-service
spec:
  type: LoadBalancer
  selector:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
  ports:
    - name: http
      port: 80
      protocol: TCP
      targetPort: http

Generating LoadBalancer Service

To generate a load balancer type service using kubectl, use the following command. The --dry-run flag stops kubectl from sending the request to the Kubernetes api-controller, and the -o yaml flag instruct kubectl to output the results in YAML.

kubectl create service loadbalancer my-service --tcp=80:3000 --dry-run -o yaml

The example above will generate a configuration for a service with the following attributes:

  • LoadBalancer type
  • Named hello-world-service
  • Service port 80
  • Targeting backend port 3000

The output of the command will look similar to the following:

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: my-service
  name: my-service
spec:
  ports:
  - name: 80-3000
    port: 80
    protocol: TCP
    targetPort: 3000
  selector:
    app: my-service
  type: LoadBalancer
status:
  loadBalancer: {}

A little cleanup will be necessary before the configuration file should be used. There are a number of fields that should not be stored as configurations for your Kubernetes cluster.

apiVersion: v1
kind: Service
metadata:
  labels:
    app: my-service
  name: my-service
spec:
  ports:
  - name: 80-3000
    port: 80
    protocol: TCP
    targetPort: 3000
  selector:
    app: my-service
  type: LoadBalancer

Generating a NodePort Service

Generating a NodePort service is the same as a LoadBalancer server, with the only difference being nodeport is used instead of loadbalancer in the command.

kubectl create service nodeport my-service --tcp=80:3000 --dry-run -o yaml

Generating a ClusterIP Service Config

As with the load balancer type and the nodeport type, a ClusterIP type is generated with the following command.

kubectl create service clusterip my-service --tcp=80:3000 --dry-run -o yaml