How to use sudo inside a docker container?

Better Stack Team
Updated on October 5, 2023

By default, the root user inside a Docker container does not require sudo to perform privileged operations. This is because Docker containers run as a non-root user by default, and this user has full root privileges inside the container.

However, if you need to run a command inside a container as a non-root user and that command requires elevated privileges, you can use the sudo command. To use sudo inside a Docker container, you need to ensure that the sudo command is installed inside the container.

To install sudo in a Docker container, you can use the following command in your Dockerfile:

 
RUN apt-get update && apt-get install -y sudo

This command updates the package lists and installs the sudo package in the container. Once sudo is installed, you can use it to run privileged commands inside the container.

For example, to run a command as the root user inside the container using sudo, you can use the following command:

 
sudo <command>

Replace <command> with the command you want to run with elevated privileges. You will be prompted to enter the password of the current user in the container before the command is executed. If you want to run the command without entering a password, you can modify the sudoers file inside the container to allow passwordless access. However, this is not recommended for security reasons.