Use User in Dockerfile

Contents

Here is a simple dockerfile which will run an application inside the container. The problem here is, that the command is issued as root.

1
2
3
4
5
6
7
8
9
FROM debian:stretch-20200422-slim

WORKDIR /app/

COPY application /app/

EXPOSE 8080

CMD [ "/app/application"]
1
2
3
$HOST> docker build -t my-application:1.0.0 .
$HOST> docker run -it -p 8080 my-application:1.0.0
$CONT> ps -u

You’ll see that your program is running for user root. To prevent this you need to specify a user inside the dockerfile.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
FROM debian:stretch-20200422-slim

USER 1000

WORKDIR /app/

COPY application /app/

EXPOSE 8080

CMD [ "/app/application"]

So now the application is running under a none priviledged user 1000. But be aware that there might be some extra work open. If you just add the user to your dockerfile and you are also copy some additional data into the image, those files could now be in a directory, where our user 1000 does not have access to. Make sure when copying additional files into the image, that the user 1000 can access them.