Sign In

Curriculum 6: Creating Resources

Imperative vs Declarative

12 min · 15 XP

Imperative vs Declarative Management

Kubernetes supports two fundamentally different approaches to managing resources. Understanding when to use each one is a key skill.

Imperative Commands

Imperative commands tell Kubernetes exactly what to do right now:

# Create a deployment
kubectl create deployment nginx --image=nginx

# Scale it up
kubectl scale deployment nginx --replicas=5

# Update the image
kubectl set image deployment/nginx nginx=nginx:1.27

# Delete it
kubectl delete deployment nginx

Each command is a single action. You are giving step-by-step instructions.

Declarative Configuration

Declarative management describes the desired end state in a file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 5
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.27
kubectl apply -f deployment.yaml

You describe what you want, and Kubernetes figures out how to get there.

When to Use Each Approach

Use imperative commands for:

  • Quick experiments and learning
  • One-off debugging tasks
  • Generating YAML templates with --dry-run=client -o yaml

Use declarative configuration for:

  • Production workloads
  • Anything that should be reproducible
  • Version-controlled infrastructure
  • Team collaboration

GitOps Patterns

Declarative management is the foundation of GitOps, where your Git repository is the source of truth for your cluster state:

  1. Store all manifests in a Git repository
  2. Use pull requests to review changes
  3. A tool like Argo CD or Flux watches the repository
  4. Changes merged to main are automatically applied to the cluster
# Typical GitOps workflow
git checkout -b update-replicas
# Edit deployment.yaml to change replicas
git add deployment.yaml
git commit -m "Scale nginx to 5 replicas"
git push origin update-replicas
# Create PR, get review, merge -- cluster updates automatically

Best Practices

  • Never mix imperative and declarative management for the same resource
  • Use kubectl diff before applying to preview changes:
kubectl diff -f deployment.yaml
  • Keep manifests organized by namespace or application in your repository
  • Use labels consistently to identify resources managed by each team

Key Takeaways

  • Imperative commands are fast for learning; declarative is essential for production
  • Declarative management is idempotent and version-control friendly
  • GitOps builds on declarative patterns by using Git as the source of truth
  • Never mix imperative and declarative approaches for the same resource
  • Use kubectl diff to preview changes before applying