run nodejs on port 80

How to Run NodeJS on Port 80

NodeJS is a powerful JS-based web framework that allows you to build and run websites and applications using Javascript. In this article, we will look at how to run NodeJS on Port 80. You can also use these steps to run NodeJS on different port.

How to Run NodeJS on Port 80

Please make sure that you have stopped any process (like Apache, NGINX) running on port 80 before you proceed further. Otherwise you will get an error “EADDRINUSE” meaning port number is in use and your server won’t start.

If you have not installed NodeJS in your Linux, run the following commands to install it.

$ sudo apt install nodejs

$ sudo yum install nodejs

1. Create Server File

Open terminal and run the following command to create server.js file for server-related code.

$ sudo vi server.js

Also read : How to Enable HTTP Strict Transport Security Policy

2. Include http module

NodeJS comes with built-in http module required to setup a NodeJS server. Add the following line to above file to include http module.

var http = require('http');

Also read : How does RewriteBase work with Example

3. Create NodeJS Server

We will use createServer() to create NodeJS server. Add the following lines to server.js file.

var http = require('http');

//create a server object:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
}).listen(80); //the server object listens on port 80

Observe the last line where we specify listen(80). This will ensure that your NodeJS server runs on port 80.

If you want to run NodeJS on different port, change 80 to your required port number (e.g 8080).

Also the function defined in createServer() will be executed whenever someone sends a request to your NodeJS server. In this case, it simply returns “Hello World!” string.

Also read : How to Change Apache Log Level

4. Run NodeJS Server

Run the following command to start NodeJS server.

$ sudo node server.js

Open browser and visit or http://localhost and you will see “Hello World!” message on your browser.

In this article, we have learnt how to run NodeJS on port 80. You can use these steps to run NodeJS server on different ports.

Also read : How to Serve Static Files using NodeJS in NGINX

Leave a Reply

Your email address will not be published. Required fields are marked *