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

containersdockerfile-permissions

I'm trying to add a file to a Docker image built from the official tomcat image. That image does not seem to have root rights, as I'm logged in as user tomcat if I run bash:

docker run -it tomcat /bin/bash
tomcat@06359f7cc4db:/usr/local/tomcat$ 

If I instruct a Dockerfile to copy a file to that container, the file has permissions 644 and the owner is root. As far as I understand, that seems to be reasonable as all commands in the Dockerfile are run as root. However, if I try to change ownership of that file to tomcat:tomcat, I get a Operation not permitted error.

Why can't I change the permissions of a file copied to that image?

How it can be reproduced:

mkdir docker-addfilepermission
cd docker-addfilepermission
touch test.txt
echo 'FROM tomcat
COPY test.txt /usr/local/tomcat/webapps/
RUN chown tomcat:tomcat /usr/local/tomcat/webapps/test.txt' > Dockerfile

docker build .

The output of docker build .:

Sending build context to Docker daemon 3.072 kB
Sending build context to Docker daemon 
Step 0 : FROM tomcat
 ---> 44859847ef64
Step 1 : COPY test.txt /usr/local/tomcat/webapps/
 ---> Using cache
 ---> a2ccb92480a4
Step 2 : RUN chown tomcat:tomcat /usr/local/tomcat/webapps/test.txt
 ---> Running in 208e7ff0ec8f
chown: changing ownership of '/usr/local/tomcat/webapps/test.txt': Operation not permitted
2014/11/01 00:30:33 The command [/bin/sh -c chown tomcat:tomcat /usr/local/tomcat/webapps/test.txt] returned a non-zero code: 1

Best Answer

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.