using sudo with ExecStart (systemd)
Asked Answered
K

2

18

I am trying to get a node.js site live on port 80 (I am using Digital Ocean). I doing this using systemd with in service file

...
ExecStart=/usr/bin/nodejs /var/www/bin/app.js
...

On localhost this works fine on port 80 if I use sudo to start the site, but not without sudo. Apparently you need to run as root for ports below 1024.

How do I allow sudo in the ExecStart? Or am I going completely the wrong way here and if so, how do I get the express app on port 80?

Cheers, Mike

Kado answered 30/4, 2016 at 20:25 Comment(0)
W
27

Systemd starts the executable stated in ExecStart= as root by default.

However, if you have specified User= or Group= in your service file overriding that default, and still need to run an executable that requires sudo, prepend the command with the absolute path to your sudo location:

...
ExecStart=/usr/bin/sudo /usr/bin/nodejs /var/www/bin/app.js
...
Weatherboard answered 29/11, 2018 at 10:56 Comment(0)
H
7

Systemd starts the executable stated in ExecStart= as root by default. This means if you haven't specified User= or Group= in our service file, your binary is started privileged.

You can verify this by starting id, or whoami program. Ex: ExecStart=/usr/bin/id or ExecStart=/usr/bin/whoami (note the path for the programs might be different for you)

Hump answered 1/5, 2016 at 17:44 Comment(4)
I have indeed specified a Group (non-root), but I would like to keep it that way as it is good practice not to run websites as root. How can I work around my problem?Kado
You need to have a .socket unit for the port which listens on it as privileged user. Then systemd passes your service the socket. It needs code modifications on nodejs to make it systemd socket activation though.Hump
I tried require('systemd'); var port = process.env.LISTEN_PID > 0 ? 'systemd' : 3050; app.set('port', port); but no luck so far.Kado
in the end I used sudo setcap cap_net_bind_service=+ep /usr/bin/nodejs to allow nodejs to publish on ports below 1024Kado

© 2022 - 2024 — McMap. All rights reserved.