- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Command
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(){ process.setgid(‘unknown’) process.setuid(‘unknown’) }
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) { res.write("Success!"); res.end(); }); server.listen(80, null, null, function() { console.log('User ID is:',process.getuid()+', Group ID:',process.getgid()); drop_root_priviliges(); console.log('User ID is:',process.getuid()+', Group ID:',process.getgid()); });