Imperative and Declarative Method on Kubernetes
╰┈➤ Imperative Method
In the imperative method, what is to be done is specified step by step and the operations are carried out directly by the user with commands. This approach requires manual interaction with the system.
Features:
It specifies how to do it: The user initiates operations by writing specific commands.
It is fast: Ideal for simple and instant changes.
It is temporary: Long-term management is difficult because the operations are not recorded.
Examples:
#Create a Pod:
kubectl run mypod --image=nginx:latest --port=80
#Delete a Pod:
kubectl delete pod nginx-pod
#Update a Pod:
kubectl set image pod/nginx nginx=nginx:latest
╰┈➤ Declarative Method
In the declarative method, the desired end state is defined and the system automatically reaches that state. The user specifies “what to do” but does not detail “how” to do it. Kubernetes uses control loops to provide and maintain this end state.
Features:
Specifies what to do: The user manages resources through descriptive files such as YAML or JSON.
Repeatable: The same definitions provide the same result every time.
Automatic remediation: Kubernetes continuously remediates the actual state to match the defined state.
#Definition of a Deployment Example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.17
To Apply the Definition:
kubectl apply -f deployment.yaml
🧐 Compare:
Comparison of imperative and declarative approaches in Kubernetes:
CrIterIon | ImperatIve | DeclaratIve |
---|---|---|
Approach | Immediate and command-based | State-based and descriptive |
Implementation | Uses kubectl commands | Uses YAML or JSON files |
Traceability | Harder to track | Easier to track, integrates well with version control |
Process | Step-by-step instructions | Desired state specified |