Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sudo inside a docker container?

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 user should be able to use sudo inside the container. This command is missing.

Here's a simple Dockerfile for this purpose:

FROM ubuntu:12.04  RUN useradd docker && echo "docker:docker" | chpasswd RUN mkdir -p /home/docker && chown -R docker:docker /home/docker  USER docker CMD /bin/bash 

Running this container, I get logged in with user 'docker'. When I try to use sudo, the command isn't found. So I tried to install the sudo package inside my Dockerfile using

RUN apt-get install sudo 

This results in Unable to locate package sudo

like image 413
drubb Avatar asked Sep 15 '14 10:09

drubb


People also ask

Can I do sudo in docker container?

sudo is a utility that allows users to run commands with root access. It is the most helpful command and is included in almost all major Linux distributions. Yes, almost all. Several Linux distros, particularly docker images, do not ship the sudo package by default.

Can you work inside a docker container?

Once you have your Docker container up and running, you can work with the environment of the Docker container in the same way you would do with an Ubuntu machine. You can access the bash or shell of the container and execute commands inside it and play around with the file system.

How do I run a docker container as a root user?

Docker containers are designed to be accessed as root users to execute commands that non-root users can't execute. We can run a command in a running container using the docker exec. We'll use the -i and -t option of the docker exec command to get the interactive shell with TTY terminal access.


1 Answers

Just got it. As regan pointed out, I had to add the user to the sudoers group. But the main reason was I'd forgotten to update the repositories cache, so apt-get couldn't find the sudo package. It's working now. Here's the completed code:

FROM ubuntu:12.04  RUN apt-get update && \       apt-get -y install sudo  RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo  USER docker CMD /bin/bash 
like image 180
drubb Avatar answered Sep 16 '22 14:09

drubb