Dockerfile entrypoint unable to switch user

15.8k views Asked by At

I am unable to switch user to a non-root user from the entry point script. The User directive to change the user in Dockerfile works, but I am not able to change permissions using chmod. To overcome this issue I created entrypoint.sh script to change the folder permissions but when I try to switch user using su command, it apparently doesn't work, the container is still running as root.

The Dockerfile

FROM php:7.2-fpm

# Installing dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    mysql-client \
    libpng-dev \
    libjpeg62-turbo-dev \
    libfreetype6-dev \
    locales \
    zip \
    jpegoptim optipng pngquant gifsicle \
    vim \
    unzip \
    git \
    curl

# Installing composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

ENV USER_ID=1000
ENV GROUP_ID=1000
ENV USER_NAME=www
ENV GROUP_NAME=www

RUN groupadd -g $GROUP_ID $GROUP_NAME
RUN useradd -u $USER_ID -ms /bin/bash -g $GROUP_NAME $USER_NAME
RUN mkdir /app
WORKDIR /app

EXPOSE 9000

COPY ./entrypoint.sh /
RUN ["chmod", "+x", "/entrypoint.sh"]
ENTRYPOINT ["/entrypoint.sh"]

Entrypoint.sh file

#!/bin/bash
if [ -n "$USER_ID" -a -n "$GROUP_ID" ]; then
    chown -R $USER_NAME:$GROUP_NAME .
    su $USER_NAME
fi

php-fpm

exec "$@"

whatever I do I am not able to switch user from the entrypoint.sh script.

My case is to run the container as non-root user.

2

There are 2 answers

3
emory On

I think that your su command should be something like

su $USERNAME --command "/doit.sh"

b/c your entrpoiny script is switching user, doing nothing, and then switching back to root.

0
Paulo Moreira On

To solve this you need to change your dockerfile and add:

RUN echo "root  ALL = NOPASSWD: /bin/su ALL" >> /etc/sudoers

Or use gosu what is better:

# install gosu
# seealso:
# https://docs.docker.com/develop/develop-images/dockerfile_best-practices/
# https://github.com/tianon/gosu/blob/master/INSTALL.md
# https://github.com/tianon/gosu
RUN set -eux; \
    apt-get update; \
    apt-get install -y gosu; \
    rm -rf /var/lib/apt/lists/*; \
# verify that the binary works
    gosu nobody true

Then inside entrypoint.sh:

gosu root yourservice &
#ie: gosu root /usr/sbin/sshd -D &

exec gosu no-root-user yourservice2
# ie: exec gosu no-root-user tail -f /dev/null