Search code examples
kuberneteskubectl

Restart n number of pods in K8s


I am working on an application which is running on the Kubernetes cluster. I want to restart the n number of pods manually in a sequence. Can we do that? Would kubectl scale <options> work here?


Solution

  • The answer is yes, you can restart 5 out of 10 pods of a particular deployment. Though it won't be a single command for this.

    As you correctly assumed kubectl scale will help you here.

    Restart of 5 pods out of 10 contains 2 operations:

    1. Scaling down the deployment from 10 to 5 pods

      kubectl scale deployment deployment-name --replicas=5
      
    2. Scaling up the deployment from 5 to 10 pods back:

      kubectl scale deployment deployment-name --replicas=10
      

    Also you can delete exact pods, kube-controller-manager with deployment/replicaset controllers within will make sure that desired state will match the exact state and therefore missing pods will be automatically rescheduled.


    However following best practice (thanks to @DavidMaze), ideal scenario is restart the whole deployment. This can be done with following command:

    kubectl rollout restart deployment deployment-name
    

    This is safer option and it allows to roll back easily in case of any mistakes/errors.

    Also it's possible to restart pods 1 by 1 within the deployment when rollout restart is requested.

    .spec.strategy.rollingUpdate.maxUnavailable should be set to 1 which means only 1 pods at most will be unavailable during the restart - reference to max unavailable.

    Kubernetes Deployments