How to use sudo inside a docker container?

前端 未结 11 764
臣服心动
臣服心动 2020-11-30 16:17

Normally, docker containers are run using the user root. I\'d like to use a different user, which is no problem using docker\'s USER directive. But this use

11条回答
  •  孤城傲影
    2020-11-30 16:46

    Unlike accepted answer, I use usermod instead.

    Assume already logged-in as root in docker, and "fruit" is the new non-root username I want to add, simply run this commands:

    apt update && apt install sudo
    adduser fruit
    usermod -aG sudo fruit
    

    Remember to save image after update. Use docker ps to get current running docker's and , then run docker commit -m "added sudo user" to save docker image.

    Then test with:

    su fruit
    sudo whoami
    

    Or test by direct login(ensure save image first) as that non-root user when launch docker:

    docker run -it --user fruit 
    sudo whoami
    

    You can use sudo -k to reset password prompt timestamp:

    sudo whoami # No password prompt
    sudo -k # Invalidates the user's cached credentials
    sudo whoami # This will prompt for password
    

提交回复
热议问题