pete19
pete19

Reputation: 53

Docker - Cannot delete files inside container via script

On this Postgres Docker image, I'm copying a couple of files over to configure the container.

(1) init.sh - copies to Docker entrypoint (2) data.txt - containing sensitive information

At the end of init.sh I want to delete data.txt, but the file never gets deleted.

docker-compose.yml

version: '3.6'

services:
  postgres_test:
    container_name: postgres_13_3
    image: postgres_13_3
    restart: unless-stopped
    build:
      context: ./postgres
      dockerfile: postgres_13_test.dk
    environment:
        POSTGRES_PASSWORD: 'test'

postgres_13_test.dk

FROM postgres:13.3-alpine3.14

# copy files over
COPY ./data.txt /tmp/data.txt
RUN chmod 777 /tmp/data.txt
COPY ./init.sh /docker-entrypoint-initdb.d/init.sh

init.sh

# ... do other things first

# then in the end, delete file
rm -rf /tmp/data.txt     # <-- file never gets deleted

What am I missing ?

UPDATE

Now rebuild the conatainer fesh w/ --no-cache, and now it shows this error message

postgres_13_3  | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sh
postgres_13_3  | rm: can't remove '/tmp/data.txt': Operation not permitted

How can I prevent this error ?

Upvotes: 1

Views: 2265

Answers (1)

atline
atline

Reputation: 31624

  • If you check its docker-entrypoint.sh, you will find the script /docker-entrypoint-initdb.d/* only be executed once when database setup at first time, this is why you later see your init.sh not executed.

  • After you setup a new container, the script has chance to execute, but you see permission issue, this is because the init.sh will be executed with postgres user, not root user, see this:

    if [ "$(id -u)" = '0' ]; then
            # then restart script as postgres user
            exec su-exec postgres "$BASH_SOURCE" "$@"
    fi
    

    Additional, if you check the permission of /tmp, you could see its permission is:

    ls -alh /tmp
    total 8K
    drwxrwxrwt    1 root     root        4.0K Aug  7 15:16 .
    drwxr-xr-x    1 root     root        4.0K Aug  7 15:25 ..
    -rwxrwxrwx    1 root     root           0 Aug  7 15:01 data.txt
    

    Here, t is sticky bit which means if user postgres and root not in same linux group, you won't be able to delete file although you still have w permission of /tmp. This is the reason you can't delete data.txt even you change permission to 777 for data.txt.

So, for you, the solution is to change the ownership of data.txt to postgres something with chown like next:

Dockerfile:

FROM postgres:13.3-alpine3.14

COPY ./data.txt /tmp/data.txt
RUN chmod 777 /tmp/data.txt
RUN chown postgres:postgres /tmp/data.txt
COPY ./init.sh /docker-entrypoint-initdb.d/init.sh

Or, not copy data.txt to /tmp, just setup a new folder like /tmp2, change its permission to 777, and copy data.txt to /tmp2.

Upvotes: 1

Related Questions