Docker - Cannot delete files inside container via script Docker - Cannot delete files inside container via script docker docker

Docker - Cannot delete files inside container via script


  • 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 /tmptotal 8Kdrwxrwxrwt    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.14COPY ./data.txt /tmp/data.txtRUN chmod 777 /tmp/data.txtRUN chown postgres:postgres /tmp/data.txtCOPY ./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.