Best practices when running Node.js with port 80 (Ubuntu) in Linux

We know that most of the time we want our node applications to listen on port 80. While it is a widely used technique and many times we don’t need anything else then just simply mentioning the port as 80 in our project configurations. The real issue actually resides in the fact that many of the operating systems nowadays require root privileges for this to happen (e.g., OS X, BSD).

One workaround is to make sure that we start our application with the superuser.


sudo node server.js

While this might actually solve the problem for quite an extent, this approach has its vulnerabilities as well. There are many potential risks involved with this step. A simple case would be if someone takes control of our app and then starts doing bad stuff to it.

That’s why it is usually not recommended to run the application as root for the entire session.

An alternative and a better approach is to drop the user account that is currently running our process to a less secure user account, such as a normal account of ours.

In order to do such a thing, we need two methods on the global process which can handle this transfer of process from a secured to a less secure user.

These two global processes are −

  • setgid()

  • setuid()

We can create a simple function that will call the above two functions which will make sure that the port 80 remains protected, while it still prevents us from serving requests as the root user.

Consider the function shown below −

function drop_root_priviliges(){

A complete working example of the above function is shown below.

const process = require('process');
const http = require('http');
var server = http.createServer(function(req, res) {

server.listen(80, null, null, function() {
   console.log('User ID is:',process.getuid()+', Group ID:',process.getgid());
   console.log('User ID is:',process.getuid()+', Group ID:',process.getgid());

Updated on: 29-Jul-2021


Kickstart Your Career

Get certified by completing the course

Get Started