0

In my company, we have a common pattern of running usermod near the of the Dockerfile in order to get the permissions straight.

E.g.:

FROM php:7.3-fpm-alpine
...
COPY . .
RUN usermod -u $USER_ID www-data && chown -R www-data:www-data $COMPOSER_HOME ./
USER www-data
CMD ["php-fpm"]

This has the benefit that the container won't run as root, yet due to cache invalidation, the command will almost always need to be triggered and it may take quite a long time during build.

I want a very quick build of my Dockerfile and whilst I can have every previous layer cached, this one as is will always need to be executed on a source file change and it may take a while depending on the amount of files for the project.

I am wondering if there is a way to avoid running usermod and chown. but if I can add the files in a certain with the permissions already in place or if this approach could already be considered best practice.

I also remember a pattern of having my hosts' user in the docker group in order to be able to have access to the files?

Besides increasing build speed, I also want to avoid injecting the host's user id.

Is there a way to achieve this?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • Generally for security purposes I'd expect the application code to be owned by `root`, _not_ the `www-data` user, so that the application code can't be accidentally modified. Similarly, you shouldn't usually need the non-root user ID in the container to match anything on the host. I'd just delete the `RUN` line you have here. – David Maze Jul 20 '20 at 14:55
  • @DavidMaze Can you please explicate this? Background is that the container also run in a local dev stack, and hence binaries such as composer need write permission in certain folders. Just deleting the the RUN statement won't suffice in this case. I have the feeling we are doing something wrong, but I have no idea on how to do it differently. – k0pernikus Jul 20 '20 at 18:54
  • Just found out about https://github.com/moby/moby/issues/6119#issuecomment-338920866 -- will try `COPY --chown=someuser:somegroup /foo /bar` approach and post it as an answer if it works. – k0pernikus Jul 20 '20 at 18:58

1 Answers1

0

Since Docker 17.09 and up one can add the chown flag to both COPY and ADD:

COPY --chown=someuser:somegroup /foo /bar
ADD --chown=someuser:somegroup /foo /bar

I stumbled over a medium post by Leonid Makarov and by that over an github issue, and there the solution was provided.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347