How to add a file to a docker container which has no root permissions?

Solution 1:

There is likely a way to view and change the Dockerfile for tomcat, but I can't figure it out after a few minutes. My inelegant solution is to add this line before the chown:

USER root

If you want to de-elevate the privileges after (which is recommended) you could add this line:

USER tomcat

Alternately, work with an image that has no software installed so you can begin your Dockerfile as root and install tomcat and all that. It's actually odd they change that in their image from my experience. It makes sense to allow the intended end user to set the USER directive as they see fit.

Solution 2:

Since Docker 17.09 one can use the --chown flag on ADD/COPY operations in Dockerfile to change the owner in the ADD/COPY step itself rather than a separate RUN operation with chown which increases the size of the image as you have noted. It would have been good to have this as the default mode i.e. the permissions of the user copying the files are applied to the copied files. However, the Docker team did not want to break backward compatibility and hence introduced a new flag.

COPY --chown=<user>:<group> <hostPath> <containerPath>

The other alternatives are:

  1. Change the permission in a staging folder prior to building the image.
  2. Run the container via a bootstrap script that changes the ownership.
  3. Squash the layers!