Nginx – Why Does Nginx Start Process as Root?

nginx

I have installed nginx server. I've just checked listening ports and saw the following:

$ sudo lsof -nP -i | grep LISTEN
sshd       614     root    3u  IPv4   7712      0t0  TCP *:22 (LISTEN)
nginx      822     root    7u  IPv4   8745      0t0  TCP *:80 (LISTEN)
nginx      827 www-data    7u  IPv4   8745      0t0  TCP *:80 (LISTEN)
nginx      828 www-data    7u  IPv4   8745      0t0  TCP *:80 (LISTEN)
nginx      829 www-data    7u  IPv4   8745      0t0  TCP *:80 (LISTEN)
nginx      830 www-data    7u  IPv4   8745      0t0  TCP *:80 (LISTEN)
.
.
.

And I'm just interested why there is four nginx processes run as 'www-data' user and one as 'root user'?

Best Answer

The process you noticed is the master process, the process that starts all other nginx processes. This process is started by the init script that starts nginx. The reason this process is running as root is simply because you started it as root! You can start it as another user, but you will have to make sure that all resources nginx needs are available to this user. That would typically be at least /var/log/nginx and the pid-file under /var/run/.

Most importantly; Only root processes can listen to ports below 1024. A webserver typically runs at port 80 and/or 443. That means it needs to be started as root.

In conclusion, the master process being run by root is completely normal and in most cases necessary for normal operation.

Edit: Running anything as root carries an implicit security risk. Normally developers of this kind of software have much knowledge about attack vectors and take great care to execute as little as possible as root. In the end you simply have to trust that the software is of good quality.

If you still feel uneasy there is a way to run nginx as another user and still use ports below 1024. You can use iptables to redirect all incoming traffic on port 80 to another port, for example 8080, and have nginx listen on that port.

Related Question