Docker volume permission denied issue for apache running in docker while apache creating files in docroot

docker

I have created one docker image having apache in it. While running that image into container apache root process is running as root and child processes are running as www-data.
One docker volume (VOLUME defined in Dockerfile) gets created as /app/cache/example which is configured as docroot in apache.

Apache running in container actually rendering data from one of backend http endpoint and caching static assets in apache docroot.

But issue is apache is not able to write static assets into the docker volume permission denied issue is coming into the logs and hence all requests are going to backend http endpoint.

For resolving this issue, i have followed below approaches, but unfortunately no luck till now:

  1. changed the ownership of volume at both sides host and container with www-data. Both host and container having this www-data user with same info like username, uid, shell etc..

  2. chmod to 777 at both host and container side.

  3. Even followed the below one in Dockerfile:

    RUN useradd foo
    RUN mkdir /data && touch /data/x
    RUN chown -R foo:foo /data
    VOLUME /data
    

Need help of experts to resolve this issue.

Best Answer

You might have more luck mounting the volume to a directory on the host machine (as in mounting it outside the /var/lib/docker mounts). The convenient thing about doing this is that you can use setfacl to recursively set the default permissions on the directory to be rw by www-data, just explicitly set the uid when you create the container for the www-data user and use that to the set the permissions from the host as the named user most probably won't exist on the host.

An additional thing you might want to look into is not running anything in your container as root at all. Even if your Apache instance is binding to a port <1024 you can use something like the following to allow low port binding without any root permissions:

setcap cap_net_bind_service=+ep <your Apache binary>

Although, the port you're binding to shouldn't matter from within the container because you could, for example, just map port 8080 to a different host port at runtime.

If you make sure to add a USER directive to the end of your docker file there shouldn't be any instances of having mixed permissions.