7

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.

Faizan
  • 181
  • 1
  • 1
  • 11

2 Answers2

3

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.

emory
  • 10,725
  • 2
  • 30
  • 58
  • 1
    I need to run the container as a non-root in user. After switching the user the `php-fpm` command does not execute and thus the server does not start. – Faizan Oct 15 '18 at 12:58
  • I know. If you use the --command switch it will exact doit.sh as user. Everything outside of doit.sh gets executed as root. – emory Oct 15 '18 at 13:06
  • Still with the command trick, if you just run or execute into the container root will be the default user. – Szabolcs Feb 16 '22 at 13:08
2

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
Paulo Moreira
  • 411
  • 5
  • 13