DEV Community

Pavlo
Pavlo

Posted on • Originally published at itsyndicate.org

How to Restart Kubernetes Pods with kubectl

Restarting Kubernetes pods is a common task that can be necessary for various reasons, such as applying configuration changes, recovering from errors, or updating application versions. While Kubernetes doesn't provide a direct kubectl restart pod command, there are several effective methods to achieve a pod restart using kubectl.

1. Rolling Restart Using kubectl rollout restart

Starting from Kubernetes version 1.15, you can perform a rolling restart of your deployments. This approach restarts each pod in a deployment sequentially, ensuring that your application remains available during the process.

kubectl rollout restart deployment <deployment-name>

Replace <deployment-name> with the name of your deployment. This command triggers the deployment to restart all its pods gracefully.

2. Scaling the Number of Replicas

Another method to restart pods is by scaling the deployment down to zero replicas and then scaling it back up to the desired number. This effectively deletes all existing pods and creates new ones.

kubectl scale deployment <deployment-name> --replicas=0
kubectl scale deployment <deployment-name> --replicas=<desired-number>

Replace <deployment-name> with your deployment's name and <desired-number> with the number of replicas you want. Note that scaling down to zero will temporarily take your application offline.

3. Deleting Pods Manually

If you delete a pod manually, Kubernetes' deployment controller will automatically create a new pod to maintain the desired state.

kubectl delete pod <pod-name>

Replace <pod-name> with the name of the pod you wish to delete. This method is useful for restarting individual pods without affecting the entire deployment.

4. Updating Environment Variables

Modifying an environment variable in the deployment's pod template forces the pods to restart, applying the new configuration.

kubectl set env deployment/<deployment-name> <ENV_VAR_NAME>=<new-value>

Replace <deployment-name> with your deployment's name, <ENV_VAR_NAME> with the environment variable name, and <new-value> with the new value. This change triggers Kubernetes to roll out the updated pods.

5. Editing the Deployment

Manually editing the deployment to change a field in the pod template, such as adding an annotation, will trigger a restart of the pods.

kubectl edit deployment/<deployment-name>

In the editor, add or modify a field in the spec.template.metadata section. For example:

annotations:
kubernetes.io/change-cause: "trigger restart"

After saving the changes, Kubernetes will initiate a rolling update, restarting the pods.

Each of these methods provides a way to restart pods in Kubernetes, depending on your specific requirements and the nature of your application.

For more insights on Kubernetes and DevOps, visit the ITSyndicate Blog.

Top comments (0)