Run a Docker Container with Non-Privileged User

When you build your own Docker Image with a Dockerfile, your process inside this container will typically run as the root user per default. This can be a security issue for productive environments in case your process becomes vulnerable.

For this reason it is recommended that your run your process inside a Docker container always as a Non-Privileged (or Non-Root) User. This can easily archived with the USER command.

FROM imixs/wildfly:latest

RUN .....
# switch to non-privileged user
USER imixs

But to run such an container you have to make sure that this user exists in your container.  Otherwise you will get an error message from the docker daemon :

docker: Error response from daemon: linux spec user: unable to find user imixs: no matching entries in passwd file.

Create a Non-Privileged User

When you look around the docker universum on DockerHub you will find a lot of examples of Dockerfiles created a user like this:

# create non-privileged user and group 
RUN groupadd -r imixs && adduser imixs

This will create a normal user with an unpredictable userid (uid) . For example the uid given to the user can be something like 1001 or 1002. This can become difficult later to grant file permissions to mounted volumes.

For that reason you sometimes can see Dockerfiles creating a user like this:

RUN groupadd -r jboss -g 1000 && useradd -u 1000 -r -g jboss -m -d /opt/jboss -s /sbin/nologin -c "JBoss user" jboss && \
 chmod 755 /opt/jboss

In this example a user ‘jboss’ is created with the uid and gid 1000. This can work fine on your local environment. But in a productive system this can lead into strange situations. The reason is, that the uid and gid are shared between the docker host and the docker container. The uid 1000 is typically assigned to an existing user which means that your process will run under this existing user with the uid 1000. But in a productive environment this uid can be reserved for specific jobs and maybe you don’t want that this user is running your docker process.

Create a System User

To solve this situation you should always create a system-user as the non-privileged user in your docker container:

RUN groupadd -r imixs -g 901 && useradd -u 901 -r -g imixs 

This command will create a user and group with the ids 901 which normally will not conflict with existing uids on the host system.

In addition you can use the -u option in the docker run command to switch the non-privileged user to a different uid:

docker run --name="mycontainer" -it -u 902 mycontainer /bin/bash

For an example how to build a container with a non-privileged user you can take a look into the docker wildfly container on DockerHub.  This container is the base container for the Imixs-Workflow project.

One Reply to “Run a Docker Container with Non-Privileged User”

Comments are closed.