Declarative vs Imperative way of creating Kubernetes objects

There are 2 ways to create an object in a Kubernetes cluster, either imperative or declarative. Let’s see a few simple examples to understand these two ways.


The imperative way is basically to create Kubernetes objects using direct kubectl commands

Let’s try creating a pod, deployment, and services using the imperative way

Create a Pod

kubectl run nginx --image=nginx

Create a deployment

kubectl create deployment --image=nginx nginx

Create a Service

kubectl expose pod redis --port=6489 --name service --dry-run=client -o yaml

We can even generate definition files using commands (This would help you better in certification exam)

kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deployment.yaml

Then we can add needed information in the definition files to create the object


Creating Kubernetes object using definition files (YAML). Let us try to make a pod using a declarative way

Create a YAML file with pod definition:

apiVersion: v1
kind: Pod
  name: nginx
  - name: nginx
    image: nginx
    - containerPort: 80

Remember, You don’t need to remember this definition and syntax for creating a YAML file. You can just” -> Seach for pod -> Get the pod definition YAML file and create the object

kubectl create -f <pod_definition.yaml>
kubectl apply -f <pod_definition.yaml>

This is similar to all other Kubernetes objects like Service, deployment, pod, etc. It is necessary to learn both ways and use them accordingly. Checkout


Check here for more Kubernetes certification tips

Similar Posts