Declarative VS Imperative Practical - Kubernetes Nginx Deployment Guide

Practical hands-on tutorial demonstrating Kubernetes Nginx deployment using both declarative YAML configuration and imperative kubectl commands with copy-paste examples and downloadable YAML files.

About Nginx Deployment in Kubernetes

Kubernetes provides two main approaches to deploy applications: imperative and declarative. Both methods can be used to deploy an Nginx container, each with its own advantages and use cases.

Imperative Approach

Direct commands that tell Kubernetes exactly what to do. Quick and straightforward for simple deployments.

Declarative Approach

Define the desired state in YAML files. Better for complex deployments, version control, and reproducibility.

Imperative Deployment

The imperative approach uses direct kubectl commands to create and manage resources.

Create Nginx Deployment

kubectl create deployment mynginx1 --image=nginx

This command creates a deployment named "mynginx1" using the official Nginx image from Docker Hub.

Command Breakdown:

  • kubectl create deployment → Command to create a deployment
  • mynginx1 → Name of the deployment
  • --image=nginx → Specifies the container image to use

Check Deployment Status

kubectl get deploy

Displays all deployments in the current namespace, showing their status and configuration.

Output Explanation:

  • NAME → Name of the deployment
  • READY → Number of ready replicas vs. desired replicas
  • UP-TO-DATE → Number of updated replicas
  • AVAILABLE → Number of available replicas
  • AGE → Time since the deployment was created

Declarative Deployment

The declarative approach uses YAML configuration files to define the desired state of your deployment.

Create Deployment from YAML

kubectl create -f deploy-example.yaml

This command creates resources defined in the deploy-example.yaml file.

Download Example YAML File

Download deploy-example.yaml

This YAML file defines an Nginx deployment with specific configurations.

Declarative Approach Benefits:

  • Version Control → YAML files can be stored in Git
  • Reproducibility → Same deployment across environments
  • Documentation → Configuration is self-documenting
  • Complex Configurations → Better for complex deployments

Cleanup Commands

These commands remove the deployments created in the previous steps.

Delete Imperative Deployment

kubectl delete deployment mynginx1

Deletes the deployment created using the imperative method.

Delete Declarative Deployment

kubectl delete deploy mynginx2

Deletes the deployment created using the declarative method.

Note:

Deleting a deployment will also delete all associated Pods and ReplicaSets created by that deployment.