'Docker custom user Permission Denied, while accessing container's file system
I've created a custom user using my Dockerfile. Here is my Dockerfile:
FROM python:3.7-alpine3.10
# Make /opt/ working directory in docker container.
WORKDIR /opt/
# Copy source code to image
COPY app app
# Create a user
RUN adduser -S my_user
# Change owner and permissions
RUN chown -R my_user /opt/
RUN chmod -R 755 /opt/
USER my_user
# Start main.py script after container is up.
ENTRYPOINT python app/main.py
In my script, I'm creating a file in the container's /opt/app/
directory, and this directory is mounted at host's /var
in docker-compose using /var/log/app:/opt/app/:z
.
When I run the container as root (without creating any users in Dockerfile), this works perfectly but using custom user, I'm getting [Error 13] permission denied
in my script.
I've also changed the owner of the directory in Docker file and also given the permissions as 755
. So what am I missing here?
Note: I've referred to a similar question but it didn't work for me: Cannot create directory. Permission denied inside docker container
Solution 1:[1]
You are running chown when you build the image. But you are mapping that folder as a volume when you run the container, which happens afterwards. During build time the chown runs successfully and the folder becomes owned by my_user
, but when you run the container, the -v option overrides the container's /opt
folder with the host's /var
, and so the ownership and permissions of the host's folder apply.
This is because Docker builds images as a set of overlay filesystems, which become read-only when the image is built (the result of Dockerfile). When you run a container from an image, Docker adds an additional layer to that overlay filesystem stack, which is read/write. The layers above (Dockerfile) do not change the layers below (your running container), but the other way around.
More info in the Docker overview.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Isra |