Kubernetes Deployment Cheatsheet

Kubernetes configurations are typically written in YAML files, and the specific syntax can often be difficult to remember. Even worse, having to remember which apiVersion to use for each resource can be difficult to remember.

In this post, I will provide a few methods of quickly creating and applying new deployments YAML manifests.

Deployment YAML Template

The following is an example of a basic deployment YAML manifest. It creates a deployment named hello-world-deployment, which sets a replicaSet state of 3 containers for the hello-world-app.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-world-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hello-world-app
  template:
    metadata:
      labels:
        app: hello-world-app
    spec:
      containers:
      - image: gcr.io/my-project/hello-world-app
        name: hello-world-app
        ports:
        - containerPort: 80

As basic as the example above is, it can be tricky to remember the structure of a deployment manifest on the fly.

Using Kubectl to Generate a Deployment Manifest

We can generate a new deployment manifest using the kubectl run command. The following example will create a new deployment manifest for your Kubernetes cluster.

kubectl create deployment hello-world-deployment --image=hello-world-app:1.0.0 --dry-run -o yaml

The two most important parts of the command are --dry-run and -o yaml. The first flag prevents kubectl from sending the request to the Kuberentes api-controller, and the second flag instruct the output to be formatted in YAML.

Once executed the following will be outputted to your screen, which you can pipe to a file if desired.

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: hello-world-deployment
  name: hello-world-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hello-world-deployment
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: hello-world-deployment
    spec:
      containers:
      - image: hello-world-app
        name: hello-world-app
        resources: {}
status: {}

While the output will provide a good starting point, it will require a little cleanup. By removing the unnecessary fields from the manifest file we are left with the following.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-world-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hello-world-deployment
  strategy: {}
  template:
    metadata:
      labels:
        app: hello-world-deployment
    spec:
      containers:
      - image: hello-world-app
        name: hello-world-app

Applying your Deployment onto a Kubernetes Cluster

To create the deployment on your Kubernetes cluster you will need to run the kubectl apply command.

kubectl apply -f hello-world-deployment.yml