Minh
Minh

Reputation: 2300

Switching Between Root and Non-Root Users in Docker

So I'm trying to deploy a Django app on Minikube. But in one of the containers, the image requires me to be in root for certain tasks and then switch the postgres user to create some databases and then switch back to root to run more commands.

I know I can use the USER functionality for Docker but that messes up certain task depending on what user I'm in. I have also tried running su - postgres but that returns an error saying that the command has to be from the terminal.

Any thoughts on how to fix this?

Upvotes: 0

Views: 3077

Answers (2)

ivan.sim
ivan.sim

Reputation: 9268

If say container is based on the official Postgres image, you can try create a script for all your root tasks and COPY that script to the container's /docker-entrypoint-initdb.d folder. Any .sql and .sh scripts in this folder will be executed AFTER the entrypoint calls initdb, with gosu postgres as seen in the entrypoint script.

If you need to sandwich the initdb between two sets of root tasks, then you will have to carve your own entrypoint script.

Upvotes: 0

BMitch
BMitch

Reputation: 263637

The typical tool for this in is gosu. When included in your container, you'd run gosu postgres $cmd where the command is whatever you need to run. If it's the only command you need to have running in the container at the end of your entrypoint script, then you'd exec gosu postgres $cmd. The gosu page includes details of why you'd use their tool, the main reasons being TTY and signal handling. Note the end of their readme also lists a few other alternatives which are worth considering.

Upvotes: 1

Related Questions