How to Install Node.js and NGINX on CentOS 8

Select distribution:
Traducciones al Español
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Create a Linode account to try this guide with a $100 credit.
This credit will be applied to any valid services used during your first 60 days.

Node.js is an open-source JavaScript runtime environment that can serve dynamic and responsive content and is often used to create and serve web applications. When serving Node.js applications, NGINX is commonly used to create a reverse proxy that points at a running Node.js server. In this guide, you will install and configure NGINX on a CentOS 8 Linode. NGINX will handle requests to static files, like index.html and also, create a reverse proxy to a Node.js server. You will then create a test JavaScript file in order to test your running Node.js server.

Before You Begin

  1. If you want to use a custom domain name for your site, purchase a domain name from a trusted registrar and use Linode’s DNS Manager to add the domain and create a domain record for it.

  2. Set up your Linode using the Getting Started and Securing your Server guides.

    Note
    Don’t forget to update your Linode’s /etc/hosts file with its public IP address and your site’s fully qualified domain name, as explained in the Update Your System’s hosts File section of the Getting Started guide.
  3. Install the SELinux core policy Python utilities. This will give you the ability to manage SELinux settings in a fine-grained way.

     sudo yum install -y policycoreutils-python-utils
    
    Note

    This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, visit our Users and Groups guide.

    All configuration files should be edited with elevated privileges. Remember to include sudo before running your text editor.

Install and Configure NGINX

NGINX site-specific configuration files are kept in /etc/nginx/sites-available and symlinked to /etc/nginx/sites-enabled/. Generally, you will create a new file containing a server block in the sites-available directory for each domain or subdomain you will be hosting. Then, you will set up a symlink to your files in the sites-enabled directory.

  1. Install NGINX, the command line utilities tmux, and tar.

    sudo dnf update
    sudo dnf install @nginx tmux tar
    
  2. Start NGINX and enable it to start automatically on reboots.

    sudo systemctl start nginx
    sudo systemctl enable nginx
    
  3. Create your site’s root directory. Replace example.com with your site’s domain name.

    sudo mkdir -p /var/www/example.com
    
  4. Use SELinux’s chcon command to change the file security context for web content.

    sudo chcon -t httpd_sys_content_t /var/www/example.com -R
    sudo chcon -t httpd_sys_rw_content_t /var/www/example.com -R
    
  5. Create the directories to store your site’s NGINX configuration files:

    sudo mkdir -p /etc/nginx/{sites-available,sites-enabled}
    
  6. Using your preferred text editor, create a new NGINX site configuration file located in the /etc/nginx/sites-available/ directory. Replace the example file name and any instances of example.com with your own domain name or IP address.

    File: /etc/nginx/sites-available/example.com
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    #Names a server and declares the listening port
    server {
        listen 80 default_server;
        server_name example.com www.example.com;
    
        #Configures the publicly served root directory
        #Configures the index file to be served
        root /var/www/example.com;
        index index.html index.htm;
    
        #These lines create a bypass for certain pathnames
        #www.example.com/test.js is now routed to port 3000
        #instead of port 80
        location ~* \.(js)$ {
            proxy_pass http://localhost:3000;
            proxy_set_header Host $host;
        }
    }
  7. Create a symlink from your NGINX configuration file in the sites-available directory to the sites-enabled directory.

    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    
  8. Using a text editor, update your NGINX configuration file, /etc/nginx/nginx.conf, with the following two changes:

    • Remove the default_server parameter from the listen directive.

    • Add an include directive to the /etc/nginx/sites-enabled/* directory. This include must be within your configuration file’s http block. Place the include directive below the include /etc/nginx/conf.d/*.conf; line.

    File: /etc/nginx/nginx.conf
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
    ...
    http {
    ...
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
    
        server {
            listen       80;
            listen       [::]:80;
        ...
        }
  9. Open your system’s firewall for http and https traffic.

    sudo firewall-cmd --zone=public --permanent --add-service=http
    sudo firewall-cmd --zone=public --permanent --add-service=https
    sudo firewall-cmd --reload
    
    Note

    If you plan to use any httpd scripts and modules on your server, update the corresponding SELinux Boolean variable. To allow HTTPD scripts and modules to connect to the network, use the following command:

    sudo setsebool -P httpd_can_network_connect on
    
    Note
    Linode’s free Cloud Firewall service can be used to replace or supplement internal firewall configuration. For more information on Cloud Firewalls, see our Getting Started with Cloud Firewalls guide. For help with solving general firewall issues, see the Troubleshooting Firewalls guide.
  10. Verify that there are no syntax errors in your site’s configuration file.

    sudo nginx -t
    

    Your output should resemble the following:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
  11. Restart NGINX to load your site’s configuration.

    sudo systemctl restart nginx
    

Create Your Site’s Index File

Note
Ensure you replace example.com with your own site’s name or IP address in all commands and examples in this section.
  1. Using the text editor of your choice, create your site’s index file in the root directory using the example below.

    File: /var/www/example.com/index.html
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    <!DOCTYPE html>
    <html>
    <body>
    
    <p><strong>If you have not finished the <a href="https://www.linode.com/docs/guides/how-to-install-nodejs-and-nginx-on-centos-8/">guide</a>, the button below will not work.</strong></p>
    
    <p>The button links to test.js. The test.js request is passed through NGINX and then handled by the Node.js server.</p>
    
    <a href="test.js">
    <button type="button">Go to test.js</button>
    </a>
    
    </body>
    </html>
        

Create Your Node.js Web Server

Install Node.js

  1. Install the Node Version Manager (NVM) for Node.js. This program helps you manage different Node.js versions on a single system.

    sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
    
  2. To start using nvm in the same terminal run the following commands:

    export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
    

    Verify that you have access to NVM by printing its current version.

    nvm --version
    

    You should see a similar output:

    0.35.3
  3. Install Node.js:

    Note
    As of writing this guide, the latest LTS version of Node.js is v12.16.2. Update this command with the version of Node.js you would like to install.
    nvm install 12.16.2
    
  4. Use NVM to run your preferred version of Node.js.

    nvm use 12.16.2
    

    Your output will resemble the following

    Now using node v12.16.2 (npm v6.14.4)

Create a Test JavaScript File

In the Install and Configure NGINX section you configured NGINX to listen on port 80 to serve its static content. You also configured a reverse proxy to your Linode’s localhost:3000 when a request for the /test.js file is made. In this section you will create the test.js file to be able to test your Node.js web server that you will create in the next section.

Note
Ensure you replace example.com with your own site’s name or IP address in all commands and examples in this section.
  1. Create the test.js file in your site’s root directory.

    File: /var/www/example.com/test.js
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>
    Your Node.JS server is working.
    </h2>
    
    <p>
    The below button is technically dynamic. You are now using Javascript on both the client-side and the server-side.</p>
    
    <button type="button" onclick="document.getElementById('sample').innerHTML = Date()"> Display the date and time.</button>
    <p id="sample"></p>
    
    </body>
    </html>
        

Create the Node.js Web Server File

In this section, you will create a file named server.js that will use Node.js modules to help you write a simple web server that can handle client requests and return responses to them.

  1. In your site’s root directory, create the server.js file with the following content.

    File: /var/www/example.com/server.js
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    //nodejs.org/api for API docs
    //Node.js web server
    var http = require("http"),                           //Import Node.js modules
        url = require("url"),
        path = require("path"),
        fs = require("fs");
    
    http.createServer(function(request, response) {       //Create server
    var name = url.parse(request.url).pathname;           //Parse URL
    var filename = path.join(process.cwd(), name);        //Create filename
    fs.readFile(filename, "binary", function(err, file) { //Read file
        if(err) {                                         //Tracking Errors
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(err + "\n");
            response.end();
            return;
        }
        response.writeHead(200);                          //Header request response
        response.write(file, "binary");                   //Sends body response
        response.end();                                   //Signals to server that
     });                                                  //header and body sent
    }).listen(3000);                                      //Listening port
    console.log("Server is listening on port 3000.")      //Terminal output
            
    
  2. Run a new tmux session:

    tmux
    

    Press return when prompted.

  3. Navigate to your root directory where your test.js file is located.

    cd /var/www/example.com
    
  4. Run your Node.js web server. Appending & to the end of a command will keep the web server’s process running in the background.

    node server.js &
    

    You should see your terminal return a process ID after issuing the previous command. Return to your command prompt by entering CTRL+C.

  5. Exit your tmux session.

    exit
    
  6. Open a browser and navigate to your site’s domain or IP address. You should see your site’s index.html page load.

  7. Click on the page’s Go to test.js button to load the test.js page whose content will be served dynamically with your Node.js web server.

  8. Click on the test page’s Display the date and time button to dynamically display the current date and time.

You have now completed the basic configurations to proxy requests to the Node.js server you wrote. As a next step, you may consider looking into further NGINX configurations to better handle serving static content and dynamic content from a reverse proxy.

There are many frameworks to help you continue to develop web apps using JavaScript. You may consider using Express.js, Ember.js, or Vue.js.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on


Your Feedback Is Important

Let us know if this guide made it easy to get the answer you needed.


Join the conversation.
Read other comments or post your own below. Comments must be respectful, constructive, and relevant to the topic of the guide. Do not post external links or advertisements. Before posting, consider if your comment would be better addressed by contacting our Support team or asking on our Community Site.