How to Create Pods in Kubernetes

02.24.2022

Intro

Creating pods is an every day task when working wit Kubernetes. Kubernetes provides a simple way to defined pods using yaml and to deploy them with the kubectl command. In this article, we will learn how to create pods with Kubernetes.

The Quick Answer

If you are here for the quick answer, here it is. Otherwise, continue to Getting Started.

Save the following to a file pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: my-example-namespace
spec:
  containers:
  - name: memory-demo-ctr
    image: polinux/stress
    command: ["stress"]

Then use the following command.

kubectl apply -f pod.yaml --namespace= my-example-namespace

Getting Setup

We will be working with minikube for most tutorials. This creates a local kubernetes cluster that you can develop on.

Feel free to use another kubernetes cluster for these tutorials as well. There will be articles underneath our kubernetes tags on how to run clusters on multiple providers such as AWS, Google Cloud, and Azure.

Once you have minikube installed, start the cluster using the following command.

minikube start

Creating a Pod

To create a pod, we will first need a yaml file to store our pod information. Create a new file

touch pod.yaml

Now, let's add the first two lines

apiVersion: v1
kind: Pod

This states that we will use the apiVersion of version 1 and the kind of resource will be a pod.

Next, let's add some metadata. This tell kubernetes to name our pod and store it in a namespace. This helps for searching and managing our resources.

metadata:
  name: my-pod
  namespace: my-example-namespace

Finally, we define the spec which are the specifications for our pod. We will create a simple container using the polinux/stress image. Don't worry too much about stress, but it is a command that will allow us to test resource allocation. You can read more here: https://hub.docker.com/r/polinux/stress/. Just note that it runs and we can tell it to use a certain amount of resources such as memory or cpu.

spec:
  containers:
  - name: memory-demo-ctr
    image: polinux/stress
    command: ["stress"]

Notice that we have one container, but we could add more. Now, our file should look like the following.

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: my-example-namespace
spec:
  containers:
  - name: memory-demo-ctr
    image: polinux/stress
    command: ["stress"]

Now, to deploy this pod, we can use the following command, assuming your terminal is in the same directory as the file.

kubectl apply -f pod.yaml --namespace= my-example-namespace

You can view your pod information using the following

kubectl get pod my-pod --namespace=my-example-namespace