Home > other >  Cannot rm -rf directories copied via COPY --chown user:group in the docker image
Cannot rm -rf directories copied via COPY --chown user:group in the docker image

Time:01-14

I cannot understand why I am not able to remove directories copied with COPY --chown user:group as the user inside my container.

File tree:

.
├── Dockerfile.copy
├── Dockerfile.run
└── build
    └── file.txt

Dockerfile.copy

FROM alpine:latest
WORKDIR /opt/app
RUN addgroup -g 98765 -S mygroup && adduser -S -u 56789 -G mygroup -D myuser
COPY --chown=myuser:mygroup build /opt/app/build
USER myuser:mygroup

in the CLI:

$ docker build --file=Dockerfile.copy --tag=copy:latest --progress="plain" .
> ... building

$ docker run copy:latest whoami
> myuser

$ docker run copy:latest ls -altrh
> total 12K
> drwxr-xr-x    1 root     root        4.0K Jan 13 09:25 ..
> drwxr-xr-x    4 myuser   mygroup     4.0K Jan 13 09:26 build
> drwxr-xr-x    1 root     root        4.0K Jan 13 09:26 .

$ docker run copy:latest rm -rf build
> rm: can't remove 'build': Permission denied

Error received when running rm -rf build is:

rm: can't remove 'build': Permission denied

Whereas in the other image, when I use RUN chown, I am able to remove the directory without errors.

Dockerfile.run

FROM alpine:latest
WORKDIR /opt/app
RUN addgroup -g 98765 -S mygroup && adduser -S -u 56789 -G mygroup -D myuser
COPY build /opt/app/build
RUN chown -R myuser:mygroup /opt/app
USER myuser:mygroup

then in CLI:

$ docker build --file=Dockerfile.run --tag=run:latest --progress="plain" .
> ... building
$ docker run run:latest rm -rf build
> (nothing, no errors)

My docker version:

$ docker --version
> Docker version 20.10.21, build baeda1f

Why is that, what am I missing and don't understand about the COPY --chown user:group?

CodePudding user response:

In your first Dockerfile, myuser owns /opt/app/build.

In your second Dockerfile, myuser owns /opt/app.

To be able to remove the directory, you need access to modify /opt/app.

  • Related