how to make non root user as sudo user in docker alpine image?

17,645

First thing, you do not need to assign root permission to newly created user, which kill purpose of the user.

So you do not need to change user to root user, you can run command in the running container with root user.

docker exec -it --user root mycontainer sh

or in Dockerfile

USER root
# Run root operation here
# Change user back to cassandra
USER cassandra

Btw you can create root user using below commands

Dockerfile

RUN adduser -D $USER \
        && echo "$USER ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/$USER \
        && chmod 0440 /etc/sudoers.d/$USER
USER $USER
WORKDIR $HOME
RUN whoami
RUN sudo whoami

Build Output

Step 9/11 : RUN whoami
 ---> Running in d52065213d2d
default
Removing intermediate container d52065213d2d
 ---> c1b526ea8342
Step 10/11 : RUN sudo whoami
 ---> Running in 5f4ddd11a5f2
root
Share:
17,645
andy
Author by

andy

Updated on July 29, 2022

Comments

  • andy
    andy almost 2 years

    I am trying build cassandra docker image using alpine based os. on the container run process i am getting permission related issue, as i am running as cassandra user. i am unable to run sudo and switch my user cassandra as sudo user. below is my sample docker file, shows only sudo user related logic--

    FROM alpine:latest
    RUN apk --no-cache update \
        && apk --no-cache add sudo
    copy run.sh /usr/local/
    RUN addgroup -S cassandra && adduser -S cassandra -G cassandra
    RUN chown -R cassandra:cassandra /home/cassandra/
    RUN echo 'cassandra  ALL=(ALL) /bin/su' >>  /etc/sudoers
    USER cassandra
    ENTRYPOINT [ "sh","/usr/local/run.sh"]
    

    after login to container i am unable to perform any sudo related task.

  • Alexander  Pravdin
    Alexander Pravdin over 2 years
    Sometimes it is needed to create a user with high privileges for a tool that forcibly doesn't work under the root user.