Skip to content

โš”๏ธ Imperative vs Declarative in Kubernetes

Kubernetes supports two main approaches to managing resources: imperative and declarative. Understanding both is key to efficient cluster management.


โœ… Imperative Approach

You tell Kubernetes exactly what to do and when using CLI commands.

Pros:

  • Quick for testing and prototyping
  • No need for YAML files

Cons:

  • Hard to track changes over time
  • Difficult to version or audit

Examples:

# Create a pod
kubectl run nginx --image=nginx

# Expose a pod
kubectl expose pod nginx --port=80 --name=nginx-service

# Scale a deployment
kubectl scale deployment nginx-deployment --replicas=3

# Set an image
kubectl set image deployment/nginx-deployment nginx=nginx:1.20

๐Ÿงพ Declarative Approach

You define the desired state in a YAML file and apply it.

Pros:

  • Reproducible
  • Version-controlled
  • Declarative diffing and idempotency

Cons:

  • Slower for ad-hoc tasks
  • Requires YAML management skills

Example YAML:

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

Apply it:

kubectl apply -f pod.yaml

Declarative is the backbone of GitOps and infrastructure-as-code.


โš–๏ธ Comparison Table

Feature Imperative Declarative
Use case Quick, one-off tasks Stable, repeatable deployments
Source of truth Human memory / CLI YAML files / Git
Version control โŒ Not tracked easily โœ… Easy with Git
Rollback/history โŒ Manual โœ… With Git or CI/CD history
Best for production? ๐Ÿšซ No โœ… Yes

๐Ÿงช Mixed Example: Dry Run Imperative + Declarative

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

โœ… Summary

Approach When to Use
Imperative Fast testing, one-off commands
Declarative Production, GitOps, long-term stability

Use imperative to move fast and declarative to stay safe and sane.