Running postgres docker container as a custom user
When running docker, I follow the below process to run postgres as non root user inside the container.Am still trying to grok some of these points.
#create a system user, any uid shud be fine, I chose 2000
sudo useradd -u 2000 -r postgres
# create a directory on the host for bind mount
mkdir -p ~/volumes/postgres
# change ownership to postgres user
sudo chown $(id -u postgres):$(id -g postgres) ~/volumes/postgres
sudo chmod 700 -R ~/volumes/postgres
And run docker postgres container with below args
docker run — user “$(id -u postgres):$(id -g postgres)” -v ~/volumes/postgres:/var/lib/postgresql/data -d postgres:12.2
docker runs the container process as user with uid 2000 and as that user is on the host, it has permissions to the data_dir.
One point to note is that the user with uid 2000 might not exist inside the container.To compensate that, the passwd and group are faked as below
https://github.com/docker-library/postgres/blob/master/12/docker-entrypoint.sh#L70-L76
Another note is that if the postgres user doesn’t have permissions to change ownership on host, hence in any of our entrypoint scripts any ownership changing commands will fail.
Also when you have custom entrypoint in script, u might have noticed this notation exec “$@”.The below answers that.