Non-Root User Setup for running Superviord in Docker Container
Generally speaking, use a Root user to run a process is not ideal, it grants too much permission to the process and increases the security risk. But if you try to solve this issue, you will run into a dilemma,
- Most of the examples/questions you will see you can solve with root permission
- You will also see there is no harm to run it with a non-root user as long as you provide enough read/write permission on logs and pid.
How do you choose to root or non-root?
The following structure gave us a solution.
To be able to run any subprocess as a different user from what supervisord is running as, you must run supervisord as root.
When you run supervisord as a user other than root, it cannot run subprocesses under another user. This is a UNIX process security restriction
It tells you if you run multiple subprocesses, you have to run as a root
to be able to start all the subprocesses, meaning that if you have more than 2 projects in you supervisord.conf
file, you need to start it with your root permission.
Other than that you can simply use a non-root with enough permission to start your supervisord
process.
How do you run a Non-Root in your docker container?
- Create a non-root user
ENV NON_ROOT_USER=non_root_userENV NON_ROOT_GID="103" \ NON_ROOT_UID="1003" \ NON_ROOT_WORK_DIR=/opt/local/${NON_ROOT_USER} \ NON_ROOT_HOME_DIR=/home/${NON_ROOT_USER}RUN groupadd -g 65532 nonroot && useradd -m -s $NON_ROOT_HOME_DIR -u 65532 $NON_ROOT_USER -g nonroot
- Add permission to your non-root user
RUN chmod g+wx /var/log/ && \ chmod g+wx /opt/local/
Here g+wx
adds write permission to group users.
- Add user config to your
supervisord.conf
[supervisord]nodaemon=trueuser=%(ENV_NON_ROOT_USER)s
- Run docker with your non-root user
This step is also very important, by default you will run your docker by root. But here you need to start it with a user.
You can either do it by docker command or docker-compose file.
In docker-compose.yml
, you can do
services: app: user: "${UID}:${GID}" # here it will be 103:1003
Or you can start your docker by
docker container run --rm -it \
--user UID:GID \ # here it will be 103:1003
Now it all sets ;)