Imperative Vs. Declarative Kubernetes Commands: What’s the difference?

Behdad Kardgar
13 min readMay 26, 2023

--

Lets have a short overview of what is Kubernetes and why its important. Kubernetes is an open-source container orchestration system that automates the deployment, scaling, and management of containerized applications. It was developed by Google and is now maintained by the Cloud Native Computing Foundation (CNCF).

Kubernetes is important because it simplifies the process of deploying and managing containerized applications at scale. It provides a consistent and standardized way to manage containers, regardless of the underlying infrastructure or the container runtime used.

The architecture of Kubernetes consists of several key components, including:

  1. Master node: This is the control plane of Kubernetes and is responsible for managing the overall state of the system.
  2. Worker node: This is the node where containerized applications are deployed and run.
  3. API server: This is the main interface for interacting with the Kubernetes system.
  4. etcd: This is the distributed key-value store used to store the configuration data of the Kubernetes cluster.
  5. Controller manager: This component is responsible for managing the various controllers that ensure the desired state of the system is maintained.
  6. Scheduler: This component is responsible for scheduling containerized applications on the worker nodes.

In addition to these components, Kubernetes also has a powerful set of features and capabilities, including:

  • Self-healing: Kubernetes can automatically recover from failures and ensure that the desired state of the system is maintained.
  • Scaling: Kubernetes can automatically scale applications up or down based on demand.
  • Service discovery: Kubernetes provides a built-in mechanism for discovering and connecting to services.
  • Load balancing: Kubernetes can automatically load balance traffic across multiple instances of an application.
  • Rollouts and rollbacks: Kubernetes can perform rolling updates and rollbacks to ensure that changes to the system are made smoothly and without downtime.

Overall, Kubernetes is a powerful tool for managing containerized applications at scale. It provides a consistent and standardized way to manage containers, regardless of the underlying infrastructure or the container runtime used, and offers a wide range of features and capabilities to make managing containers easier and more efficient.

Imperative Kubernetes commands

Imperative commands in Kubernetes are commands that directly manipulate the state of the system. These commands are used to create, update, or delete resources in the Kubernetes cluster. With imperative commands, you specify the exact changes you want to make to the system, and Kubernetes carries out those changes immediately.

Examples of imperative commands in Kubernetes include:

  1. kubectl run: This command is used to create a new deployment, replicaset, or pod.
  2. kubectl expose: This command is used to create a new service for a deployment or replicaset.
  3. kubectl scale: This command is used to scale up or down the number of replicas in a deployment or replicaset.
  4. kubectl delete: This command is used to delete resources such as deployments, services, or pods.

Pros of using imperative commands:

  • Immediate feedback: With imperative commands, changes are made to the system immediately, and you can see the results of those changes right away.
  • Flexibility: Imperative commands give you fine-grained control over the changes you make to the system. You can specify exactly what changes you want to make and how you want to make them.
  • Ease of use: Imperative commands are easy to learn and use, even for beginners.

Cons of using imperative commands:

  • Lack of version control: With imperative commands, changes to the system are made immediately, without any tracking or version control. This can make it difficult to roll back changes if something goes wrong.
  • Complexity: With the fine-grained control offered by imperative commands comes a certain level of complexity. Managing and coordinating multiple imperative commands can become difficult as the size and complexity of the Kubernetes cluster grows.
  • Difficulty in reproducibility: As imperative commands are immediate, it can be difficult to reproduce the exact same setup in another environment or cluster.

Overall, imperative commands offer a flexible and powerful way to manage Kubernetes resources, especially for small and simple tasks. However, as the complexity and scale of the Kubernetes cluster grows, imperative commands can become increasingly difficult to manage, and the lack of version control and reproducibility can be limiting.

Declarative Kubernetes manifests

Declarative manifests are the preferred way of defining and managing Kubernetes resources. In contrast to imperative commands, where the user specifies the exact steps that need to be taken to create or update a resource, declarative manifests describe the desired state of the resource, and Kubernetes takes care of creating or updating the resource to match that state.

Declarative manifests are written in YAML or JSON and define the desired state of a Kubernetes resource. The manifest includes the resource’s metadata, such as its name, namespace, and labels, as well as its specification, which describes the desired configuration of the resource. When a declarative manifest is applied to the Kubernetes cluster, Kubernetes compares the desired state in the manifest with the current state of the resource and makes any necessary changes to ensure that the resource is in the desired state.

Here are some examples of declarative manifests in Kubernetes:

  1. Deployment manifest:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app-deployment
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app-container
image: my-app-image:latest
ports:
- containerPort: 8080

This manifest describes a deployment that should run three replicas of a container based on the my-app-image:latest Docker image.

  1. Service manifest:
apiVersion: v1
kind: Service
metadata:
name: my-app-service
spec:
selector:
app: my-app
ports:
- name: http
port: 80
targetPort: 8080

This manifest describes a service that exposes the my-app deployment on port 80.

Declarative manifests offer several advantages over imperative commands:

  1. Idempotency: Declarative manifests are idempotent, meaning that they can be applied multiple times without causing unintended changes. This is because Kubernetes compares the current state of the resource with the desired state in the manifest before making any changes.
  2. Version control: Declarative manifests can be version controlled using tools like Git, allowing you to track changes to your Kubernetes resources over time.
  3. Collaboration: Declarative manifests can be shared with others, allowing for easier collaboration on Kubernetes resource management.

However, declarative manifests also have some disadvantages:

  1. Complexity: Declarative manifests can be more complex to write than imperative commands, especially for complex resources.
  2. Learning curve: Declarative manifests require a learning curve to understand how to write them correctly and troubleshoot errors.

Declarative manifests are the recommended approach for managing Kubernetes resources, as they offer many advantages over imperative commands.

Kubernetes deployment

Kubernetes Deployment: Kubernetes deployment is the process of deploying containerized applications and managing their lifecycle. A Kubernetes deployment is a high-level resource that defines how an application should be deployed and updated.

Deployment Strategies: There are two common deployment strategies in Kubernetes: imperative and declarative.

Imperative Deployment: Imperative deployment is the traditional way of deploying applications in Kubernetes, where the user specifies the exact steps to be taken to deploy the application. In other words, the user specifies the desired state of the system and the steps needed to achieve that state. Imperative deployment is achieved through the use of Kubernetes commands, such as kubectl run and kubectl create.

Example of Imperative Deployment: To create an nginx deployment with two replicas using imperative commands, you can use the following command:

kubectl run nginx --image=nginx --replicas=2

Pros and Cons of Imperative Deployment: The main advantage of imperative deployment is that it provides fine-grained control over the deployment process. However, this control comes at the cost of complexity and maintenance. Imperative deployment requires a high level of expertise and can be error-prone, especially in large and complex systems.

Declarative Deployment: Declarative deployment is a newer way of deploying applications in Kubernetes, where the user specifies the desired state of the system rather than the steps needed to achieve that state. In other words, the user declares what they want the system to look like, and Kubernetes takes care of the rest.

Example of Declarative Deployment: To create an nginx deployment with two replicas using declarative manifests, you can use the following YAML file:

apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx

Pros and Cons of Declarative Deployment: The main advantage of declarative deployment is that it is simpler and easier to manage than imperative deployment. Declarative deployment is also more scalable and less error-prone than imperative deployment. However, it provides less fine-grained control over the deployment process.

Comparison of Deployment Strategies: Imperative deployment is better suited for smaller and simpler systems where fine-grained control is required. Declarative deployment is better suited for larger and more complex systems where scalability and ease of management are more important. In general, it is recommended to use declarative deployment whenever possible, and only resort to imperative deployment when necessary.

Kubernetes deployment is an essential part of the application lifecycle management process. Both imperative and declarative deployment strategies have their pros and cons, and the choice between the two depends on the specific needs of the system.

Kubernetes configuration management

Configuration management in Kubernetes refers to the process of managing the configuration of your applications and services running in the cluster. This includes managing the container images, environment variables, volumes, and other configuration parameters that are required for your application to run.

In Kubernetes, there are two main approaches to configuration management: using imperative commands and using declarative manifests.

Managing configuration using imperative commands:

With imperative commands, you can manage the configuration of your applications and services by directly modifying the configuration of the running containers in your Kubernetes cluster. This can be done using commands like kubectl set, kubectl edit, and kubectl patch.

Examples of managing configuration using imperative commands in Kubernetes include:

  • Changing the environment variables of a running container:
kubectl set env deployment/myapp APP_ENV=production
  • Updating the image of a running container:
kubectl set image deployment/myapp myapp=nginx:latest
  • Adding a new volume to a running container:
kubectl set volume deployment/myapp - add - name=myvol - type=configMap - configMap-name=myconfigmap

Pros of using imperative commands for configuration management:

  • Flexibility: With imperative commands, you have complete control over the configuration of your applications and services.
  • Real-time updates: Changes made using imperative commands take effect immediately.

Cons of using imperative commands for configuration management:

  • No version control: With imperative commands, changes are made directly to the running containers, without any version control or history.
  • Complexity: As the configuration of your applications and services grows more complex, managing them using imperative commands can become difficult.

Managing configuration using declarative manifests:

With declarative manifests, you can define the desired configuration of your applications and services in YAML or JSON files, and then apply those manifests to the Kubernetes cluster using commands like kubectl apply.

Examples of managing configuration using declarative manifests in Kubernetes include:

  • Defining the environment variables for a deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 1
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: nginx
env:
- name: APP_ENV
value: production
  • Defining the volume mounts for a deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 1
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: nginx
volumeMounts:
- name: myvol
mountPath: /data
volumes:
- name: myvol
configMap:
name: myconfigmap

Pros of using declarative manifests for configuration management:

  • Version control: With declarative manifests, changes are versioned and tracked, making it easy to roll back changes or compare different versions.
  • Reproducibility: Declarative manifests can be used to reproduce the exact same configuration across different environments and clusters.

Cons of using declarative manifests for configuration management:

  • Learning curve: Writing declarative manifests can be challenging for beginners.
  • Delayed updates: Changes made using declarative manifests can take a few seconds to be applied to the running containers.

Overall, both imperative commands and declarative manifests have their own advantages and disadvantages when it comes to managing the configuration of your applications and services in Kubernetes.

Kubernetes scaling

Kubernetes provides various strategies for scaling applications in a cluster. Scaling refers to the process of increasing or decreasing the number of replicas of a pod, deployment, or statefulset.

There are two primary methods for scaling in Kubernetes: Imperative commands and Declarative manifests.

Imperative Scaling Commands: Imperative scaling involves directly manipulating the number of replicas in a Kubernetes object using commands. To scale a deployment using an imperative command, you would run the following:

$ kubectl scale deployment my-deployment --replicas=5

This command increases the number of replicas for the deployment called my-deployment to 5. Similarly, you can use the kubectl scale command to decrease the number of replicas.

Pros of Imperative Scaling:

  • Quick and easy to use
  • Directly manipulates the current state of the object
  • Useful for one-off scaling operations

Cons of Imperative Scaling:

  • Difficult to maintain and track changes
  • No clear audit trail of scaling operations
  • Not recommended for managing production environments

Declarative Scaling Manifests: Declarative scaling involves specifying the desired number of replicas in the Kubernetes manifest file. To scale a deployment declaratively, you would update the manifest file to reflect the desired number of replicas:

apiVersion: apps/v1
kind: Deployment
metadata:
name: my-deployment
spec:
replicas: 5
...

Then, you can apply the updated manifest using the kubectl apply command:

$ kubectl apply -f my-deployment.yaml

This command updates the deployment with the new desired number of replicas.

Pros of Declarative Scaling:

  • Provides a clear and maintainable configuration file
  • Facilitates infrastructure as code
  • Easily repeatable across multiple environments

Cons of Declarative Scaling:

  • More time-consuming and complex to set up initially
  • May require a higher level of expertise to use
  • May be challenging to update or change the desired state once set

Comparison of Scaling Strategies: Both imperative and declarative scaling have their advantages and disadvantages. Imperative scaling is useful for quick and one-off scaling operations, while declarative scaling is better suited for managing production environments and creating a clear audit trail of changes.

It is important to consider the needs and goals of your deployment when choosing a scaling strategy in Kubernetes. For example, a development environment may require more frequent scaling operations, while a production environment may prioritize maintainability and consistency.

Kubernetes operations

Kubernetes operations refer to the management and maintenance of the Kubernetes cluster itself, as well as the applications running on the cluster. This includes tasks such as monitoring, logging, debugging, and updating the cluster and its applications.

Imperative commands can be used to manage Kubernetes operations by directly interacting with the cluster through the command line interface. Examples of imperative commands for Kubernetes operations include:

  • kubectl logs: retrieves the logs of a specific pod or container
  • kubectl exec: executes a command inside a container
  • kubectl describe: provides detailed information about a specific resource in the cluster
  • kubectl rollout: manages rolling updates of applications

While imperative commands provide a quick and efficient way to manage Kubernetes operations, they can be error-prone and difficult to maintain, especially as the cluster grows larger and more complex.

Declarative manifests can also be used to manage Kubernetes operations, by defining the desired state of the cluster and its applications. Examples of declarative manifests for Kubernetes operations include:

  • Kubernetes operators: a Kubernetes extension that automates complex application management tasks
  • Helm charts: a package manager for Kubernetes that provides a declarative way to define and manage applications
  • Kubernetes configuration files: YAML or JSON files that describe the desired state of the cluster and its applications

Declarative manifests provide a more scalable and maintainable approach to managing Kubernetes operations, as they enable infrastructure as code and version control. However, they require a higher level of abstraction and can be more difficult to learn and use initially.

When choosing between imperative commands and declarative manifests for managing Kubernetes operations, it is important to consider factors such as the size and complexity of the cluster, the level of automation required, and the expertise of the team. A combination of both approaches may also be used, depending on the specific needs of the cluster and its applications.

Best practices

Best practices for using imperative commands:

  • Keep the command line arguments simple and easy to understand
  • Use descriptive names for resources and labels
  • Use piping and scripting to reduce repetitive tasks
  • Use the — dry-run flag to preview the changes before executing the command
  • Always use the — record flag when creating resources to track changes and provide audit logs
  • Avoid using imperative commands for complex tasks that can be done declaratively

Best practices for using declarative manifests:

  • Use version control systems like Git to manage your manifests
  • Use a consistent naming convention for your resources and labels
  • Use environment variables and parameterization to make your manifests more flexible and reusable
  • Use the kubectl apply command instead of create or replace to ensure idempotency and prevent unintended changes
  • Use the kubectl diff command to compare the desired state with the current state and preview changes before applying the manifests
  • Avoid using imperative commands for complex tasks that can be done declaratively

Recommendations for choosing the right approach:

  • Use imperative commands for simple, one-off tasks that require quick, ad-hoc changes
  • Use declarative manifests for complex, long-term tasks that require version control, testing, and reproducibility
  • Consider the size and complexity of your infrastructure when choosing between imperative and declarative approaches
  • Use a combination of both approaches when appropriate, such as using imperative commands for debugging or troubleshooting issues in a declarative environment.

It’s important to choose the right approach based on the specific needs and requirements of your Kubernetes environment. By following best practices and considering the pros and cons of each approach, you can create a more efficient and effective deployment strategy.

Conclusion

In conclusion, it is important to understand the differences between imperative and declarative approaches in Kubernetes, and choose the right approach based on your specific needs and requirements.

Here are the key points to recap:

  • Imperative commands are used to directly manipulate the state of Kubernetes resources, while declarative manifests define the desired state of resources.
  • Imperative commands provide more control and flexibility, while declarative manifests provide more stability and predictability.
  • Imperative commands are suitable for quick, one-off operations, while declarative manifests are more suitable for long-term management and automation.
  • Declarative manifests can be version controlled, making it easier to track changes and collaborate with team members.
  • Imperative commands are useful for debugging and troubleshooting, while declarative manifests are better for scaling and managing complex environments.

When choosing between imperative and declarative approaches, it is important to consider factors such as the size of your cluster, the complexity of your applications, and the level of control you require over your resources.

In general, it is recommended to use declarative manifests for managing production environments, as they provide more stability and predictability. However, imperative commands can be useful for quick operations and testing.

Ultimately, both approaches have their pros and cons, and the choice between them depends on the specific needs and requirements of your project.

In conclusion, understanding the differences between imperative and declarative approaches is important for effective management of Kubernetes environments. Choosing the right approach can help you achieve the desired level of control, stability, and scalability for your applications.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Behdad Kardgar
Behdad Kardgar

No responses yet

Write a response