How to run my container as a nonRoot user

Viewed 3098

My dockerfile:

FROM httpd:2.4
RUN useradd -u 8877 john
USER john
// docker build -t my-apache2 .

// docker run -dit --name my-running-app -p 8080:80 my-apache2

Any help would be appreciated

1 Answers

If you want to add specific user then solution is to create a custom image which extends a base image and adds a user e.g.

FROM:httpd
USER <user>[:<group>]

and then you can run container with that user

docker run --user <user>[:<group>] httpd

Without extending the base image you will receive the following error message from docker engine

docker: Error response from daemon: unable to find user <user>: no matching entries in passwd file

Reference: https://docs.docker.com/engine/reference/builder/#user

If you want to use the stock image with non-root user then instead of using a username above you can just specify its UID instead. This will make linux run as that user id without having to check if it exists or not.

Of course, any files that it interacts with will need to be writable by that user. But as an example, change the default user and group within a container to your own with adding --user $(id -u):$(id -g):

docker run -dit --name my-running-app -p 8080:80 --user $(id -u):$(id -g) my-apache2

See the docker command line reference here https://docs.docker.com/engine/reference/commandline/run/ https://docs.docker.com/engine/reference/commandline/exec/

Related