Exec commands on kubernetes pods with root access

I have one pod running with name 'jenkins-app-2843651954-4zqdp'. I want to install few softwares temporarily on this pod. How can I do this?

I am trying this- kubectl exec -it jenkins-app-2843651954-4zqdp -- /bin/bash and then running apt-get install commands but since the user I am accessing with doesn't have sudo access I am not able to run commands


Solution 1:

  • Use kubectl describe pod ... to find the node running your Pod and the container ID (docker://...)
  • SSH into the node
  • run docker exec -it -u root ID /bin/bash

Solution 2:

There are some plugins for kubectl that may help you achieve this: https://github.com/jordanwilson230/kubectl-plugins

One of the plugins called, 'ssh', will allow you to exec as root user by running (for example) kubectl ssh -u root -p nginx-0

Solution 3:

Building on @jordanwilson230's answer he also developed a bash-script called exec-as which uses Docker-in-Docker to accomplish this: https://github.com/jordanwilson230/kubectl-plugins/blob/krew/kubectl-exec-as

When installed via kubectl plugin manager krew → kubectl krew install exec-as you can simply

kubectl exec-as -u <username> <podname> -- /bin/bash

This only works in Kubernetes clusters which allow priviledged containers.

Solution 4:

Just in case you come across to look for an answer for minikube, the minikube ssh command can actually work with docker command together here, which makes it fairly easy:

  1. Find the container ID:

    $ minikube ssh docker container ls
    
  2. Add the -u 0 option to docker command (quote is necessary for the whole docker command):

    $ minikube ssh "docker container exec -it -u 0 <Container ID> /bin/bash"
    

NOTE: this is NOT for Kubernetes in general, it works for minikube only. While I feel we need the root access quit a lot in local development environment, it's worth to mention it in this thread.