Dockerfile: How to run as non-root user

Recently I’ve deployed some Spring Boot services using Docker. Going through some blog posts about best practices, I’ve noticed that we run the application as a root user inside the container. This is a security issue when the Docker Daemon is run as root. There is a rootless mode but I haven’t encountered that yet in the wild.

To check if your Docker Daemon is running as root you can use:

$ ps -p $(pidof dockerd) -o user=
root

Running applications as a non-root user inside the container is easy:

# Debian / Ubuntu
RUN addgroup --system --gid 10000 app && adduser --system --uid 10000 --gid 10000 --no-create-home app
USER app

# Alpine
RUN addgroup -S app -g 10000 && adduser -S app -G app -u 10000 -H
USER app

Both the user id and group id is far away from normal users/groups. Additionally we don’t need a $HOME folder so we skip creating one.