Imperative & Declarative in Kubernetes

Imperative vs Declarative
  • Imperative: Tell the machine what to do and how to do it.
  • Declarative: Tell the machine what to do what should happen. But It does not tell the machine how to do things.

Kubernetes Imperative

Create objects

$ kubectl run --image=nginx nginx
$ kubectl create deployment --image=nginx
$ kubectl expose deployment nginx --port 80

Update Objects

$ kubectl edit deployment nginx
$ kubectl scale deployment nginx --replicas=5
$ kubectl set image deployment nginx nginx=nginx:1.18

Managing objects with the object configuration files(yaml)

$ kubectl create -f nginx.yaml
$ kubectl replace -f nginx.yaml
$ kubectl delete -f nginx.yaml

Imperative approach problems

  • What if you have run the create command? if the object already exists now, then it would fail with an error.
  • When you update an object, you should always make sure that the objects exist first before running the replace command. If an object does not exist, the replace command failed with an error message.

In the imperative approach, you must always be aware of the current configurations and perform checks to make sure that things are in place before making a change

Kubernetes Declarative

$ kubectl apply -f nginx.yaml
  • apply command for creating, updating, or deleting the object. The apply command will look at the existing configuration and figure out what changes need to be made to the system.

Kubectl apply command is intelligent enough to create an object if it does not already exist. if the object exists and so it only updates the object with the new changes.

Leave a Reply

Your email address will not be published.

ANOTE.DEV