2.2. kubectl and Manifests

In this lab, you see how kubectl finds your cluster, create a Pod in two different ways and explore the API.

Step 1: Inspect the Context

kubectl reads the connection details of your clusters from the kubeconfig (~/.kube/config). List the contexts it contains:

kubectl config get-contexts
CURRENT   NAME       CLUSTER    AUTHINFO         NAMESPACE
*         k3d-labs   k3d-labs   admin@k3d-labs

If you have worked with other clusters before, you see more contexts. The * marks the current one.

Explanation

A context combines a cluster (CLUSTER) with a user (AUTHINFO) that kubectl logs in with. k3d created the context k3d-labs in 2.1. The column NAMESPACE is empty, so kubectl works in the Namespace default, the namespace for your own resources. The add-ons from 2.1 run in kube-system.


Step 2: Create a Pod Imperatively

Tell kubectl directly to create a Pod named hello that runs the web server nginx:

kubectl run hello --image=nginx:1.29
pod/hello created

List the Pods:

kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
hello   1/1     Running   0          13s

If the status is ContainerCreating, the image is still downloading. Wait a moment and repeat the command.

Delete the Pod again, because Step 3 creates it from a manifest:

kubectl delete pod hello
pod "hello" deleted from default namespace

Explanation

This is the imperative way: you tell kubectl what to do, one command at a time. It’s quick for trying something out, but no file records what you created. To create the same Pod again, you have to remember the command.


Step 3: Create a Pod Declaratively

Create a directory for the files of this lab and change into it:

mkdir -p ~/labs/2.2
cd ~/labs/2.2

Create the file hello.yaml in ~/labs/2.2 with your editor or IDE and the following content:

apiVersion: v1
kind: Pod
metadata:
  name: hello
spec:
  containers:
    - name: nginx
      image: nginx:1.29

Apply the manifest:

kubectl apply -f hello.yaml
pod/hello created

Apply it a second time:

kubectl apply -f hello.yaml
pod/hello unchanged

Explanation

This is the declarative way: the manifest describes the state you want, and kubectl apply makes the cluster match it. The cluster already matches after the first apply, so the second one changes nothing.

Most manifests have the same four top-level fields:

FieldMeaning
apiVersionVersion of the API that defines the resource type
kindResource type
metadataIdentifies the resource, at least with a name
specDesired state, here one container from the image nginx:1.29

Keep the file: you can create the same Pod again at any time, and you can store it in Git like your source code.


Step 4: Explore the API

List the resource types your cluster knows:

kubectl api-resources
NAME                                SHORTNAMES   APIVERSION                        NAMESPACED   KIND
...
configmaps                          cm           v1                                true         ConfigMap
...
namespaces                          ns           v1                                false        Namespace
nodes                               no           v1                                false        Node
...
pods                                po           v1                                true         Pod
...
deployments                         deploy       apps/v1                           true         Deployment
...

Watch how kubectl talks to the API server. -v=6 logs every request it sends:

kubectl get pods -v=6
I1013 17:45:20.060780  777872 loader.go:408] Config loaded from file:  /home/ubuntu/.kube/config
...
I1013 17:45:20.070477  777872 round_trippers.go:632] "Response" verb="GET" url="https://0.0.0.0:39357/api/v1/namespaces/default/pods?limit=500" status="200 OK" milliseconds=4
NAME    READY   STATUS    RESTARTS   AGE
hello   1/1     Running   0          3m

Show the documentation of a resource type:

kubectl explain pod
KIND:       Pod
VERSION:    v1

DESCRIPTION:
    Pod is a collection of containers that can run on a host. This resource is
    created by clients and scheduled onto hosts.

FIELDS:
  apiVersion  <string>
  ...
  kind        <string>
  ...
  metadata    <ObjectMeta>
  ...
  spec        <PodSpec>
  ...
  status      <PodStatus>
  ...

Follow the fields down to the image of a container:

kubectl explain pod.spec.containers.image
KIND:       Pod
VERSION:    v1

FIELD: image <string>

DESCRIPTION:
    Container image name. More info:
    https://kubernetes.io/docs/concepts/containers/images This field is optional
    to allow higher level config management to default or override container
    images in workload controllers like Deployments and StatefulSets.

Explanation

kubectl api-resources lists about 70 resource types. pods and nodes appear a second time with the API version metrics.k8s.io/v1beta1, which is the CPU and memory usage collected by the metrics-server. The columns tell you how to use each resource type:

ColumnMeaning
NAMEName for kubectl, e.g. kubectl get pods
SHORTNAMESShorter alternative, e.g. kubectl get po
APIVERSIONValue for apiVersion in a manifest
NAMESPACEDtrue if the resource lives in a namespace
KINDValue for kind in a manifest

APIVERSION is the API group and its version: apps/v1 is version v1 of the group apps. Core types like Pod have no group, only v1. v1beta1 marks a beta version that may still change.

kubectl is a client of the REST API of Kubernetes: kubectl get pods sent a GET request to the API server at the address from your kubeconfig (the paths and the port differ on your machine). The URL is built from what kubectl api-resources lists: the API version v1, the namespace default and the resource type pods.

kubectl explain documents every field you can write in a manifest. Separate the fields with dots to go deeper.


Optional Tasks

Finished early? Try these tasks. The following labs don’t depend on them. Each task lists the commands you need. Open the solution if you get stuck.

Task 1: Spot the Difference

Compare your manifest hello.yaml with the Pod that Kubernetes stores.

CommandEffect
kubectl get <type> <name> -o yamlShows the complete resource as YAML
Solution

Show the stored Pod:

kubectl get pod hello -o yaml

Your manifest has 8 lines, the output has more than 100. Kubernetes added:

  • in metadata: information like a unique uid, the creationTimestamp and the annotation kubectl.kubernetes.io/last-applied-configuration, in which kubectl apply stores your manifest
  • in spec: default values for many fields you left out, e.g. restartPolicy: Always, and the nodeName the scheduler chose
  • a new section status: the current state of the Pod, e.g. phase: Running and its IP address

spec is the state you want, status is the state the cluster reports.

Task 2: Whack-a-Pod

Delete your Pod hello and the CoreDNS Pod in the namespace kube-system. Which one comes back?

CommandEffect
kubectl get pods -n <namespace> --watchLists the Pods and keeps running: every change prints a new line
kubectl delete pod <name> -n <namespace>Deletes a Pod in a namespace

Stop a running --watch with Ctrl+C.

Solution

Delete your Pod:

kubectl delete pod hello
pod "hello" deleted from default namespace

List the Pods:

kubectl get pods
No resources found in default namespace.

Your Pod is gone for good. Now watch the Pods in kube-system:

kubectl get pods -n kube-system --watch

Open a second terminal and delete the CoreDNS Pod. Use the name from your output, it starts with coredns-:

kubectl delete pod coredns-8db54c48d-nfxvd -n kube-system

Within seconds, the first terminal shows a new CoreDNS Pod with a different name.

Nobody watches over your Pod hello. The CoreDNS Pod belongs to a Deployment: a controller in the kube-controller-manager makes sure that one CoreDNS Pod runs at all times.

Create your Pod again from the manifest:

kubectl apply -f ~/labs/2.2/hello.yaml

Task 3: Manifest Generator

Let kubectl write a manifest for you instead of typing it.

CommandEffect
kubectl run <name> --image=<image> --dry-run=client -o yamlPrints the manifest of the Pod instead of creating it
Solution

Generate the manifest and save it to a file next to hello.yaml:

kubectl run hello2 --image=nginx:1.29 --dry-run=client -o yaml > ~/labs/2.2/hello2.yaml

Compare hello2.yaml with hello.yaml. The generated file contains a few more fields, e.g. the label run: hello2 and empty values like status: {}, and names the container hello2. It also orders and indents the fields differently. Both styles are valid YAML. Generating a manifest and adjusting it is often faster than writing it from scratch.


Clean Up

Delete the Pod, since the following labs don’t need it:

kubectl delete -f ~/labs/2.2/hello.yaml
pod "hello" deleted from default namespace