Skip to content

Instantly share code, notes, and snippets.

@alkrauss48
Last active November 10, 2022 16:24
Show Gist options
  • Star 68 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save alkrauss48/2dd9f9d84ed6ebff9240ccfa49a80662 to your computer and use it in GitHub Desktop.
Save alkrauss48/2dd9f9d84ed6ebff9240ccfa49a80662 to your computer and use it in GitHub Desktop.
Running a docker container as a non-root user
# By default, Docker containers run as the root user. This is bad because:
# 1) You're more likely to modify up settings that you shouldn't be
# 2) If an attacker gets access to your container - well, that's bad if they're root.
# Here's how you can run change a Docker container to run as a non-root user
## CREATE APP USER ##
# Create the home directory for the new app user.
RUN mkdir -p /home/app
# Create an app user so our program doesn't run as root.
RUN groupadd -r app &&\
useradd -r -g app -d /home/app -s /sbin/nologin -c "Docker image user" app
# Set the home directory to our app user's home.
ENV HOME=/home/app
ENV APP_HOME=/home/app/my-project
## SETTING UP THE APP ##
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
# ***
# Do any custom logic needed prior to adding your code here
# ***
# Copy in the application code.
ADD . $APP_HOME
# Chown all the files to the app user.
RUN chown -R app:app $APP_HOME
# Change to the app user.
USER app
@antoninfansunarc
Copy link

Docker run -u root or 0 getinto root access , do we have a fix for that ??

@dipanjanmukherjee83
Copy link

Hi @alkrauss48 how can we add UID and GID in stack file or compose file. I know we can use uid,gid and mode with secret but we want non-root user who can run the containers and services.

@tavasim
Copy link

tavasim commented Mar 14, 2019

Did you had an issue that the chown increases the image size significantly ? Any solution for that ?

@sethbergman
Copy link

Here's how I setup a non-root user with the base image of ubuntu:18.04:

RUN \
    groupadd -g 999 foo && useradd -u 999 -g foo -G sudo -m -s /bin/bash foo && \
    sed -i /etc/sudoers -re 's/^%sudo.*/%sudo ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^root.*/root ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^#includedir.*/## **Removed the include directive** ##"/g' && \
    echo "foo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && \
    echo "Customized the sudoers file for passwordless access to the foo user!" && \
    echo "foo user:";  su - foo -c id

@wadewilliams
Copy link

Instead of

ADD . $APP_HOME
RUN chown ... 
COPY --chown=app:app . $APP_HOME

Runs faster and fixes @tavasim's reference to the image size.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment