8

New here, was wondering if someone had experience with building images as non root user?

I am building Kotlin project, (2 step build) and my goal is now to build it as non root user. Here is what my Dockerfile looks like. Any help would be appreciated:

# Build
FROM openjdk:11-jdk-slim as builder

# Compile application
WORKDIR /root
COPY . .
RUN ./gradlew build

FROM openjdk:11-jre-slim

# Add application
COPY --from=builder /root/build/libs/*.jar ./app.jar

# Set the build version
ARG build_version
ENV BUILD_VERSION=$build_version

COPY docker-entrypoint.sh /
RUN chmod 777 /docker-entrypoint.sh
CMD /docker-entrypoint.sh
3
  • 2
    You don't need root for that. You have to be inside docker group on most systems.
    – andreoss
    Apr 26, 2021 at 6:47
  • And I am asking how to do something like RUN groupadd -r test && useradd --no-log-init -r -g test test and use that user inside this dockerfile
    – vukojevicf
    Apr 26, 2021 at 6:52
  • A Docker container has its own filesystem space and its own /etc/passwd file; a user inside a container often won't match any particular host user.
    – David Maze
    Apr 26, 2021 at 11:33

1 Answer 1

11

In order to use Docker, you don't need to be a root user, you just need to be inside of the docker user group.

On Linux:

  1. If there is not already a docker group, you can create one using the command sudo groupadd docker.
  2. Add yourself and any other users you would like to be able to access docker to this group using the command sudo usermod -aG docker [username of user].
  3. Relog, so that Linux can re-evaluate user groups.

If you are not trying to run the command as root, but rather want to run the container as non-root, you can use the following DOCKERFILE contents (insert after FROM but before anything else.)

# Add a new user "john" with user id 8877
RUN useradd -u 8877 john
# Change to non-root privilege
USER john
5
  • Oh that second part was what I was asking for. So I just add a user like that and that's all?
    – vukojevicf
    Apr 26, 2021 at 7:00
  • Yep - that should work. All it needs to do is create a new user (in this case named john) and switch to this new user. Apr 26, 2021 at 7:01
  • 1
    Why user id 8877? Is that an arbitrary ID or is that significant?
    – Adil Sadik
    Jul 22, 2021 at 14:47
  • Pretty sure it's arbitrary. Not sure why I put that in there to be honest. Jul 23, 2021 at 20:31
  • 3
    @Adil Sadik In Linux users are identified by an unique uid and username, with the -u flag set you choose a id. without the flag it will assign the next available. linux.die.net/man/8/useradd Sep 13, 2021 at 1:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.