Sometimes being root inside a docker container is a pain especially when mounting files and having to create and modify files inside the container.

So what is an easy way around this issue? Well docker allows you to launch a container and become the UID and GID you pass in:

$ docker run --rm -ti --user (id -u $USER):(id -g $USER) ubuntu:16.04
groups: cannot find name for group ID 1000
I have no name!@f8b2e4f05d4e:/$

Though this approach works it means you can’t setup a bashrc or special completion tools as they are not configured for new users that do not have a home directory.

The Solution

FROM ubuntu:16.04
LABEL maintainer="Crunchy234"

# Update the apt packages in the container.
RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y \
sudo \
apt-utils

# Create directories for the container
RUN mkdir /home/working

# Set default UID and GID to create user with
ENV USERID 1001
ENV GROUPID 1001

RUN mkdir -p /home/developer && \
echo "developer:x:${USERID}:${GROUPID}:Developer,,,:/home/developer:/bin/bash" >> /etc/passwd && \
echo "developer:x:${USERID}:" >> /etc/group && \
chown ${USERID}:${GROUPID} -R /home/working && \
cp /root/.bashrc /home/developer && \
usermod -m -d /home/developer developer && \
echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer && \
chmod 0440 /etc/sudoers.d/developer && \
chown ${USERID}:${GROUPID} -R /home/developer

WORKDIR /home/working
ENTRYPOINT usermod -u $USERID developer && \
groupmod -g $GROUPID developer && \
su developer && \
bash

To create this container:

$ docker build -t docker-as-user .

To run the container:

$ docker run --rm -ti -e USERID=$(id -u $USER) -e GROUPID=$(id -g $USER) docker-as-user
su: Authentication failure
(Ignored)
developer@2de334de689b:/home/working$

Now inside this container when you create and destroy files you are doing so as the user and you have full completion as well.

Current issues

  • You have to exit the container twice to exit. The first exit exits the user.
  • It’s not a clean entrypoint so non interactive scripts may be an issue.

Feel free to contribute to the repository and improve it on GitHub: https://github.com/crunchy234/docker-as-user