17

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

Mike
  • 3,775
  • 8
  • 39
  • 79

2 Answers2

25

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
...
nassan
  • 716
  • 7
  • 18
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)

Umut
  • 2,317
  • 1
  • 17
  • 19
  • 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? – Mike May 01 '16 at 20:25
  • 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. – Umut May 02 '16 at 04:38
  • I tried require('systemd'); var port = process.env.LISTEN_PID > 0 ? 'systemd' : 3050; app.set('port', port); but no luck so far. – Mike May 02 '16 at 20:36
  • 1
    in the end I used sudo setcap cap_net_bind_service=+ep /usr/bin/nodejs to allow nodejs to publish on ports below 1024 – Mike May 06 '16 at 12:55