Q:

How can I change permission on folder inside Dockerfile

I was trying to push container on heroku but I get this error when changing permission
FROM  ubuntu:latest

ENV PORT=80

RUN apt-get update \
    && apt-get install -y curl zip unzip  \
            php7.4 php7.4-fpm \
            nginx gettext-base sudo

COPY ./webapp /var/www/myapp

WORKDIR /var/www/myapp

COPY default.conf.template /etc/nginx/conf.d/default.conf.template

COPY nginx.conf /etc/nginx/nginx.conf

RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo

USER docker

RUN  chown -R www-data:www-data /var/www

RUN  chmod -R 755 /var/www

CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'

I have this error
Step 10/12 : RUN  chown -R www-data:www-data /var/www
 ---> Running in c5952535d0cc
chown: changing ownership of '/var/www/html/index.nginx-debian.html': Operation not permitted
chown: changing ownership of '/var/www/html': Operation not permitted
chown: changing ownership of '/var/www/myapp/index.php': Operation not permitted
chown: changing ownership of '/var/www/myapp/.gitignore': Operation not permitted
chown: changing ownership of '/var/www/myapp': Operation not permitted
chown: changing ownership of '/var/www': Operation not permitted
The command '/bin/sh -c chown -R www-data:www-data /var/www' returned a non-zero code: 1
 !    Error: docker build exited with Error: 1

Thank you in advance.

A:

USER docker

RUN  chown -R www-data:www-data /var/www

USER docker will cause all subsequent RUN commands to be run as docker user (see USER docs), however this user does not have permissions to change ownership of /var/www during the build, hence your error. 
You should run your chown command before setting docker user, something like:
# [ ... ]
COPY nginx.conf /etc/nginx/nginx.conf

RUN  chown -R www-data:www-data /var/www

RUN  chmod -R 755 /var/www

RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo

USER docker

Or even better:
# [ ... ]
COPY nginx.conf /etc/nginx/nginx.conf

RUN chown -R www-data:www-data /var/www && \
  chmod -R 755 /var/www && \
  useradd -m docker && echo "docker:docker" | chpasswd && \
  adduser docker sudo

USER docker

Which would use less layers 

