dockergoogle-cloud-platformgoogle-artifact-registry

Docker Build Fails on adduser Command with Google Cloud SDK Base Image


I'm working on a Dockerfile that uses gcr.io/google.com/cloudsdktool/google-cloud-cli:latest as a base image. My goal is to add a non-root user and configure it for passwordless sudo access. However, the build process fails at the step where I try to add a new user with the adduser command. Here's the relevant part of my Dockerfile:

# Example for Debian/Ubuntu base image
FROM gcr.io/google.com/cloudsdktool/google-cloud-cli:latest

# Other installation commands here...

# Add and configure a non-root user
ARG USER=coder
RUN adduser --disabled-password --gecos '' ${USER} && \
    echo "${USER} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/${USER} && \
    chmod 0440 /etc/sudoers.d/${USER}

USER ${USER}
WORKDIR /home/${USER}

During the build process, I encounter the following error:

Error: process "/bin/sh -c adduser --disabled-password --gecos '' ${USER} && echo \"${USER} ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/${USER} && chmod 0440 /etc/sudoers.d/${USER}" did not complete successfully: exit code: 2

This is the output from Terraform that's running the Docker build process. Despite following suggestions such as verifying the base image, considering the use of useradd instead of adduser, ensuring environment variables are correctly passed, and even attempting to break down the RUN command into smaller steps for debugging, the issue persists.

I am unsure if this is related to the specifics of the Google Cloud SDK base image or if there's an error in my approach to adding a user in this Docker environment. Has anyone faced a similar issue or has insights into what might be going wrong here?


Solution

  • This will do the job. The reason for your error was that the /etc/sudoers.d/ directory did not exist. If you install the sudo package then it creates that directory and your RUN command will work. See Dockerfile below.

    Echoing the comment from @David Maze: although you can do this, it might not really make sense to create a non-root user if you are going to be using sudo to run commands. Why not just do whatever as the root user?

    FROM gcr.io/google.com/cloudsdktool/google-cloud-cli:latest
    
    RUN apt-get update && \
        apt-get install -y \
            sudo
    
    ARG USER=coder
    RUN adduser --disabled-password --gecos '' ${USER} && \
        echo "${USER} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/${USER} && \
        chmod 0440 /etc/sudoers.d/${USER}
    
    USER ${USER}
    WORKDIR /home/${USER}
    
    # Check that sudo works.
    CMD whoami && sudo whoami
    

    enter image description here