Search code examples
dockerdockerfiledocker-build

Building Docker image as non root user


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

Solution

  • 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