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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github