One place for hosting & domains

      Nodejs

      How To Install Node.js on Debian 10


      Introduction

      Node.js is a JavaScript platform for general-purpose programming that allows users to build asynchronous network applications quickly. By leveraging JavaScript on both the front and backend, Node.js can make web application development more consistent and integrated.

      In this guide, we’ll show you how to get started with Node.js on a Debian 10 server. We will discuss installing Node from the default Debian repository, using a more up-to-date PPA repository, and using NVM (Node Version Manager) to install and activate different versions of Node.

      Finally, we will show how to uninstall these different versions of Node.

      Prerequisites

      This guide assumes that you are using Debian 10. Before you begin, you should have a non-root user with sudo privileges set up on your system. You can learn how to set this up by following the initial server setup for Debian 10 tutorial.

      Installing the Official Debian Node.js Package

      Debian contains a version of Node.js in its default repositories. At the time of writing, this version is 10.15.2, which will reach end-of-life on April 1, 2021. At this date it will no longer be supported with security and bug fixes. If you would like to experiment with Node using an easy-to-install, stable, and long-term option, then installing from the Debian repo may make sense.

      To get Node.js from the default Debian software repository, you can use the apt package manager. First, refresh your local package index:

      Then install the Node.js package, and npm the Node Package Manager:

      • sudo apt install nodejs npm

      To verify that the install was successful, run the node command with the -v flag to get the version:

      Output

      v10.15.2

      If you need a more recent version of Node.js than this, the next two sections will explain other installation options.

      Installing Using a PPA

      To work with a more recent version of Node.js, you can install from a PPA (personal package archive) maintained by NodeSource. This is an alternate repository that still works with `apt, and will have more up-to-date versions of Node.js than the official Debian repositories. NodeSource has PPAs available for Node versions from 0.10 through to 12.

      Let’s install the PPA now. This will add the repository to our package list and allow us to install the new packages using apt.

      From your home directory, use curl to retrieve the installation script for your preferred Node.js version, making sure to replace 12.x with your preferred version string (if different):

      • cd ~
      • curl -sL https://deb.nodesource.com/setup_12.x -o nodesource_setup.sh

      You can inspect the contents of this script with nano or your preferred text editor:

      If everything looks OK, exit your text editor and run the script using sudo:

      • sudo bash nodesource_setup.sh

      The PPA will be added to your configuration and your local package cache will be updated automatically. Now you can install the nodejs package in the same way you did in the previous step:

      We don’t need to install a separate package for npm in this case, as it is included in the nodejs packae.

      Verify the installation by running node with the -v version option:

      Output

      v12.8.0

      npm uses a configuration file in your home directory to keep track of updates. It will be created the first time you run npm. Execute this command to verify that npm is installed and to create the configuration file:

      Output

      6.10.2

      In order for some npm packages to work (those that require compiling code from source, for example), you will need to install the build-essential package:

      • sudo apt install build-essential

      You now have the necessary tools to work with npm packages that require compiling code from source.

      Installing Using NVM

      An alternative to installing Node.js through apt is to use a tool called nvm, which stands for “Node Version Manager”. Rather than working at the operating system level, nvm works at the level of an independent directory within your user’s home directory. This means that you can install multiple self-contained versions of Node.js without affecting the entire system.

      Controlling your environment with nvm allows you to access the newest versions of Node.js while also retaining and managing previous releases. It is a different utility from apt, however, and the versions of Node.js that you manage with it are distinct from those you manage with apt.

      To download the nvm installation script from the project’s GitHub page, you can use curl. Note that the version number may differ from what is highlighted here:

      • curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh -o install_nvm.sh

      Inspect the installation script with nano:

      If the script looks OK, exit your text editor and run the script with bash:

      We don’t need sudo here because nvm is not installed into any privileged system directories. It will instead install the software into a subdirectory of your home directory at ~/.nvm. It will also add some configuration to your ~/.profile file to enable the new software.

      To gain access to the nvm functionality, you’ll need to either log out and log back in again or source the ~/.profile file so that your current session knows about the changes:

      With nvm installed, you can install isolated Node.js versions. For information about the versions of Node.js that are available, type:

      Output

      . . . v10.16.2 (Latest LTS: Dubnium) v11.0.0 v11.1.0 v11.2.0 v11.3.0 v11.4.0 v11.5.0 v11.6.0 v11.7.0 v11.8.0 v11.9.0 v11.10.0 v11.10.1 v11.11.0 v11.12.0 v11.13.0 v11.14.0 v11.15.0 v12.0.0 v12.1.0 v12.2.0 v12.3.0 v12.3.1 v12.4.0 v12.5.0 v12.6.0 v12.7.0 v12.8.0

      As you can see, the current LTS version at the time of this writing is v10.16.2. You can install that by typing:

      Usually, nvm will switch to use the most recently installed version. You can tell nvm to use the version you just downloaded by typing:

      As always, you can verify the Node.js version currently being used by typing:

      Output

      v10.16.2

      If you have multiple Node.js versions, you can see what is installed by typing:

      If you wish to default to one of the versions, type:

      • nvm alias default 10.16.2

      This version will be automatically selected when a new session spawns. You can also reference it by the alias like this:

      Each version of Node.js will keep track of its own packages and has npm available to manage these.

      Removing Node.js

      You can uninstall Node.js using apt or nvm, depending on the version you want to target. To remove versions installed from the Debian repository or from the PPA, you will need to work with the apt utility at the system level.

      To remove either of these versions, type the following:

      This command will remove the package and the configuration files.

      To uninstall a version of Node.js that you have enabled using nvm, first determine whether or not the version you would like to remove is the current active version:

      If the version you are targeting is not the current active version, you can run:

      • nvm uninstall node_version

      This command will uninstall the selected version of Node.js.

      If the version you would like to remove is the current active version, you must first deactivate nvm to enable your changes:

      You can now uninstall the current version using the uninstall command above, which will remove all files associated with the targeted version of Node.js except the cached files that can be used for reinstallation.

      Conclusion

      There are a quite a few ways to get up and running with Node.js on your Debian 10 server. Your circumstances will dictate which of the above methods is best for your needs. While using the packaged version in the Debian repository is an option for experimentation, installing from a PPA and working with npm or nvm offers additional flexibility.



      Source link

      How To Write and Run Your First Program in Node.js


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Node.js is a popular open-source runtime environment that can execute JavaScript outside of the browser using the V8 JavaScript engine, which is the same engine used to power the Google Chrome web browser’s JavaScript execution. The Node runtime is commonly used to create command line tools and web servers.

      Learning Node.js will allow you to write your front-end code and your back-end code in the same language. Using JavaScript throughout your entire stack can help reduce time for context switching, and libraries are more easily shared between your back-end server and front-end projects.

      Also, thanks to its support for asynchronous execution, Node.js excels at I/O-intensive tasks, which is what makes it so suitable for the web. Real-time applications, like video streaming, or applications that continuously send and receive data, can run more efficiently when written in Node.js.

      In this tutorial you’ll create your first program with the Node.js runtime. You’ll be introduced to a few Node-specific concepts and build your way up to create a program that helps users inspect environment variables on their system. To do this, you’ll learn how to output strings to the console, receive input from the user, and access environment variables.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Outputting to the Console

      To write a “Hello, World!” program, open up a command line text editor such as nano and create a new file:

      With the text editor opened, enter the following code:

      hello.js

      console.log("Hello World");
      

      The console object in Node.js provides simple methods to write to stdout, stderr, or to any other Node.js stream, which in most cases is the command line. The log method prints to the stdout stream, so you can see it in your console.

      In the context of Node.js, streams are objects that can either receive data, like the stdout stream, or objects that can output data, like a network socket or a file. In the case of the stdout and stderr streams, any data sent to them will then be shown in the console. One of the great things about streams is that they're easily redirected, in which case you can redirect the output of your program to a file, for example.

      Save and exit nano by pressing CTRL+X, when prompted to save the file, press Y. Now your program is ready to run.

      Step 2 — Running the Program

      To run this program, use the node command as follows:

      The hello.js program will execute and display the following output:

      Output

      Hello World

      The Node.js interpreter read the file and executed console.log("Hello World"); by calling the log method of the global console object. The string "Hello World" was passed as an argument to the log function.

      Although quotation marks are necessary in the code to indicate that the text is a string, they are not printed to the screen.

      Having confirmed that the program works, let's make it more interactive.

      Step 3 — Receiving User Input via Command Line Arguments

      Every time you run the Node.js “Hello, World!” program, it produces the same output. In order to make the program more dynamic, let's get input from the user and display it on the screen.

      Command line tools often accept various arguments that modify their behavior. For example, running node with the --version argument prints the installed version instead of running the interpreter. In this step, you will make your code accept user input via command line arguments.

      Create a new file arguments.js with nano:

      Enter the following code:

      arguments.js

      console.log(process.argv);
      

      The process object is a global Node.js object that contains functions and data all related to the currently running Node.js process. The argv property is an array of strings containing all the command line arguments given to a program.

      Save and exit nano by typing CTRL+X, when prompted to save the file, press Y.

      Now when you run this program, you provide a command line argument like this:

      • node arguments.js hello world

      The output looks like the following:

      Output

      [ '/usr/bin/node', '/home/sammy/first-program/arguments.js', 'hello', 'world' ]

      The first argument in the process.argv array is always the location of the Node.js binary that is running the program. The second argument is always the location of the file being run. The remaining arguments are what the user entered, in this case: hello and world.

      We are mostly interested in the arguments that the user entered, not the default ones that Node.js provides. Open the arguments.js file for editing:

      Change console.log(process.arg); to the following:

      arguments.js

      console.log(process.argv.slice(2));
      

      Because argv is an array, you can use JavaScript's built-in slice method that returns a selection of elements. When you provide the slice function with 2 as its argument, you get all the elements of argv that comes after its second element; that is, the arguments the user entered.

      Re-run the program with the node command and the same arguments as last time:

      • node arguments.js hello world

      Now, the output looks like this:

      Output

      [ 'hello', 'world' ]

      Now that you can collect input from the user, let's collect input from the program's environment.

      Step 4 — Accessing Environment Variables

      Environment variables are key-value data stored outside of a program and provided by the OS. They are typically set by the system or user and are available to all running processes for configuration or state purposes. You can use Node's process object to access them.

      Use nano to create a new file environment.js:

      Add the following code:

      environment.js

      console.log(process.env);
      

      The env object stores all the environment variables that are available when Node.js is running the program.

      Save and exit like before, and run the environment.js file with the node command.

      Upon running the program, you should see output similar to the following:

      Output

      { SHELL: '/bin/bash', SESSION_MANAGER: 'local/digitalocean:@/tmp/.ICE-unix/1003,unix/digitalocean:/tmp/.ICE-unix/1003', COLORTERM: 'truecolor', SSH_AUTH_SOCK: '/run/user/1000/keyring/ssh', XMODIFIERS: '@im=ibus', DESKTOP_SESSION: 'ubuntu', SSH_AGENT_PID: '1150', PWD: '/home/sammy/first-program', LOGNAME: 'sammy', GPG_AGENT_INFO: '/run/user/1000/gnupg/S.gpg-agent:0:1', GJS_DEBUG_TOPICS: 'JS ERROR;JS LOG', WINDOWPATH: '2', HOME: '/home/sammy', USERNAME: 'sammy', IM_CONFIG_PHASE: '2', LANG: 'en_US.UTF-8', VTE_VERSION: '5601', CLUTTER_IM_MODULE: 'xim', GJS_DEBUG_OUTPUT: 'stderr', LESSCLOSE: '/usr/bin/lesspipe %s %s', TERM: 'xterm-256color', LESSOPEN: '| /usr/bin/lesspipe %s', USER: 'sammy', DISPLAY: ':0', SHLVL: '1', PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus', _: '/usr/bin/node', OLDPWD: '/home/sammy' }

      Keep in mind that many of the environment variables you see are dependent on the configuration and settings of your system, and your output may look substantially different than what you see here. Rather than viewing a long list of environment variables, you might want to retrieve a specific one.

      Step 5 — Accessing a Specified Environment Variable

      In this step you'll view environment variables and their values using the global process.env object and print their values to the console.

      The process.env object is a simple mapping between environment variable names and their values stored as strings. Like all objects in JavaScript, you access an individual property by referencing its name in square brackets.

      Open the environment.js file for editing:

      Change console.log(process.env); to:

      environment.js

      console.log(process.env["HOME"]);
      

      Save the file and exit. Now run the environment.js program:

      The output now looks like this:

      Output

      /home/sammy

      Instead of printing the entire object, you now only print the HOME property of process.env, which stores the value of the $HOME environment variable.

      Again, keep in mind that the output from this code will likely be different than what you see here because it is specific to your system. Now that you can specify the environment variable to retrieve, you can enhance your program by asking the user for the variable they want to see.

      Step 6 — Retrieving An Argument in Response to User Input

      Next, you'll use the ability to read command line arguments and environment variables to create a command line utility that prints the value of an environment variable to the screen.

      Use nano to create a new file echo.js:

      Add the following code:

      echo.js

      const args = process.argv.slice(2);
      console.log(process.env[args[0]]);
      

      The first line of echo.js stores all the command line arguments that the user provided into a constant variable called args. The second line prints the environment variable stored in the first element of args; that is, the first command line argument the user provided.

      Save and exit nano, then run the program as follows:

      Now, the output would be:

      Output

      /home/sammy

      The argument HOME was saved to the args array, which was then used to find its value in the environment via the process.env object.

      At this point you can now access the value of any environment variable on your system. To verify this, try viewing the following variables: PWD, USER, PATH.

      Retrieving single variables is good, but letting the user specify how many variables they want would be better.

      Step 7 — Viewing Multiple Environment Variables

      Currently, the application can only inspect one environment variable at a time. It would be useful if we could accept multiple command line arguments and get their corresponding value in the environment. Use nano to edit echo.js:

      Edit the file so that it has the following code instead:

      echo.js

      const args = process.argv.slice(2);
      
      args.forEach(arg => {
        console.log(process.env[arg]);
      });
      

      The forEach method is a standard JavaScript method on all array objects. It accepts a callback function that is used as it iterates over every element of the array. You use forEach on the args array, providing it a callback function that prints the current argument's value in the environment.

      Save and exit the file. Now re-run the program with two arguments:

      You would see the following output:

      Output

      /home/sammy /home/sammy/first-program

      The forEach function ensures that every command line argument in the args array is printed.

      Now you have a way to retrieve the variables the user asks for, but we still need to handle the case where the user enters bad data.

      Step 8 — Handling Undefined Input

      To see what happens if you give the program an argument that is not a valid environment variable, run the following:

      • node echo.js HOME PWD NOT_DEFINED

      The output will look similar to the following:

      Output

      /home/sammy /home/sammy/first-program undefined

      The first two lines print as expected, and the last line only has undefined. In JavaScript, an undefined value means that a variable or property has not been assigned a value. Because NOT_DEFINED is not a valid environment variable, it is shown as undefined.

      It would be more helpful to a user to see an error message if their command line argument was not found in the environment.

      Open echo.js for editing:

      Edit echo.js so that it has the following code:

      echo.js

      const args = process.argv.slice(2);
      
      args.forEach(arg => {
        let envVar = process.env[arg];
        if (envVar === undefined) {
          console.error(`Could not find "${arg}" in environment`);
        } else {
          console.log(envVar);
        }
      });
      

      Here, you have modified the callback function provided to forEach to do the following things:

      1. Get the command line argument's value in the environment and store it in a variable envVar.
      2. Check if the value of envVar is undefined.
      3. If the envVar is undefined, then we print a helpful message indicating that it could not be found.
      4. If an environment variable was found, we print its value.

      Note: The console.error function prints a message to the screen via the stderr stream, whereas console.log prints to the screen via the stdout stream. When you run this program via the command line, you won't notice the difference between the stdout and stderr streams, but it is good practice to print errors via the stderr stream so that they can be easier identified and processed by other programs, which can tell the difference.

      Now run the following command once more:

      • node echo.js HOME PWD NOT_DEFINED

      This time the output will be:

      Output

      /home/sammy /home/sammy/first-program Could not find "NOT_DEFINED" in environment

      Now when you provide a command line argument that's not an environment variable, you get a clear error message stating so.

      Conclusion

      Your first program displayed "Hello World" to the screen, and now you have written a Node.js command line utility that reads user arguments to display environment variables.

      If you want to take this further, you can change the behavior of this program even more. For example, you may want to validate the command line arguments before you print. If an argument is undefined, you can return an error, and the user will only get output if all arguments are valid environment variables.



      Source link

      How To Set Up a Node.js Application for Production on Debian 10


      Introduction

      Node.js is an open-source JavaScript runtime environment for building server-side and networking applications. The platform runs on Linux, macOS, FreeBSD, and Windows. Though you can run Node.js applications at the command line, this tutorial will focus on running them as a service. This means that the applications will restart on reboot or failure and are safe for use in a production environment.

      In this tutorial, you will set up a production-ready Node.js environment on a single Debian 10 server. This server will run a Node.js application managed by PM2, and provide users with secure access to the application through an Nginx reverse proxy. The Nginx server will offer HTTPS, using a free certificate provided by Let’s Encrypt.

      Prerequisites

      This guide assumes that you have the following:

      When you’ve completed the prerequisites, you will have a server serving your domain’s default placeholder page at https://your_domain/.

      Step 1 — Installing Node.js

      Let’s begin by installing the latest LTS release of Node.js, using the NodeSource package archives.

      To install the NodeSource PPA and access its contents, you will first need to update your package index and install curl:

      • sudo apt update
      • sudo apt install curl

      Make sure you’re in your home directory, and then use curl to retrieve the installation script for the Node.js 10.x archives:

      • cd ~
      • curl -sL https://deb.nodesource.com/setup_10.x -o nodesource_setup.sh

      You can inspect the contents of this script with nano or your preferred text editor:

      When you're done inspecting the script, run it under sudo:

      • sudo bash nodesource_setup.sh

      The PPA will be added to your configuration and your local package cache will be updated automatically. After running the setup script from Nodesource, you can install the Node.js package:

      To check which version of Node.js you have installed after these initial steps, type:

      Output

      v10.16.0

      Note: When installing from the NodeSource PPA, the Node.js executable is called nodejs, rather than node.

      The nodejs package contains the nodejs binary as well as npm, a package manager for Node modules, so you don't need to install npm separately.

      npm uses a configuration file in your home directory to keep track of updates. It will be created the first time you run npm. Execute this command to verify that npm is installed and to create the configuration file:

      Output

      6.9.0

      In order for some npm packages to work (those that require compiling code from source, for example), you will need to install the build-essential package:

      • sudo apt install build-essential

      You now have the necessary tools to work with npm packages that require compiling code from source.

      With the Node.js runtime installed, we can move on to writing a Node.js application.

      Step 2 — Creating a Node.js Application

      Let's write a Hello World application that returns "Hello World" to any HTTP requests. This sample application will help you get Node.js set up. You can replace it with your own application — just make sure that you modify your application to listen on the appropriate IP addresses and ports.

      First, let's create a sample application called hello.js:

      Insert the following code into the file:

      ~/hello.js

      const http = require('http');
      
      const hostname = 'localhost';
      const port = 3000;
      
      const server = http.createServer((req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Hello World!n');
      });
      
      server.listen(port, hostname, () => {
        console.log(`Server running at http://${hostname}:${port}/`);
      });
      

      Save the file and exit the editor.

      This Node.js application listens on the specified address (localhost) and port (3000), and returns "Hello World!" with a 200 HTTP success code. Since we're listening on localhost, remote clients won't be able to connect to our application.

      To test your application, type:

      You will see the following output:

      Output

      Server running at http://localhost:3000/

      Note: Running a Node.js application in this manner will block additional commands until you kill the application by pressing CTRL+C.

      To test the application, open another terminal session on your server, and connect to localhost with curl:

      • curl http://localhost:3000

      If you see the following output, the application is working properly and listening on the correct address and port:

      Output

      Hello World!

      If you do not see the expected output, make sure that your Node.js application is running and configured to listen on the proper address and port.

      Once you're sure it's working, kill the application (if you haven't already) by pressing CTRL+C.

      Step 3 — Installing PM2

      Next let's install PM2, a process manager for Node.js applications. PM2 makes it possible to daemonize applications so that they will run in the background as a service.

      Use npm to install the latest version of PM2 on your server:

      The -g option tells npm to install the module globally, so it's available system-wide.

      Let's first use the pm2 start command to run the hello.js application in the background:

      This also adds your application to PM2's process list, which is outputted every time you start an application:

      Output

      [PM2] Spawning PM2 daemon with pm2_home=/home/sammy/.pm2 [PM2] PM2 Successfully daemonized [PM2] Starting /home/sammy/hello.js in fork_mode (1 instance) [PM2] Done. ┌──────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────┬───────────┬───────┬──────────┐ │ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │ ├──────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────┼───────────┼───────┼──────────┤ │ hello │ 0 │ fork │ 1338 │ online │ 0 │ 0s │ 0% │ 23.0 MB │ sammy │ disabled │ └──────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────┴───────────┴───────┴──────────┘ Use `pm2 show <id|name>` to get more details about an app

      As you can see, PM2 automatically assigns an App name based on the filename without the .js extension, along with a PM2 id. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

      Applications that are running under PM2 will be restarted automatically if the application crashes or is killed, but we can take an additional step to get the application to launch on system startup using the startup subcommand. This subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots. Type the following:

      You will see output that looks like this, describing the service configuration that PM2 has generated:

      Output

      [PM2] Init System found: systemd Platform systemd Template [Unit] Description=PM2 process manager Documentation=https://pm2.keymetrics.io/ After=network.target [Service] Type=forking User=root LimitNOFILE=infinity LimitNPROC=infinity LimitCORE=infinity Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin Environment=PM2_HOME=/root/.pm2 PIDFile=/root/.pm2/pm2.pid Restart=on-failure ExecStart=/usr/lib/node_modules/pm2/bin/pm2 resurrect ExecReload=/usr/lib/node_modules/pm2/bin/pm2 reload all ExecStop=/usr/lib/node_modules/pm2/bin/pm2 kill [Install] WantedBy=multi-user.target Target path /etc/systemd/system/pm2-root.service Command list [ 'systemctl enable pm2-root' ] [PM2] Writing init configuration in /etc/systemd/system/pm2-root.service [PM2] Making script booting at startup... [PM2] [-] Executing: systemctl enable pm2-root... Created symlink /etc/systemd/system/multi-user.target.wants/pm2-root.service → /etc/systemd/system/pm2-root.service. [PM2] [v] Command successfully executed. +---------------------------------------+ [PM2] Freeze a process list on reboot via: $ pm2 save [PM2] Remove init script via: $ pm2 unstartup systemd

      You have now created a systemd unit that runs pm2 on boot. This pm2 instance, in turn, runs hello.js.

      Start the service with systemctl:

      • sudo systemctl start pm2-root.service

      Check the status of the systemd unit:

      • systemctl status pm2-root.service

      You should see output like the following:

      Output

      ● pm2-root.service - PM2 process manager Loaded: loaded (/etc/systemd/system/pm2-root.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2019-07-12 16:09:54 UTC; 4s ago

      For a detailed overview of systemd, see Systemd Essentials: Working with Services, Units, and the Journal.

      In addition to those we have covered, PM2 provides many subcommands that allow you to manage or look up information about your applications.

      Stop an application with this command (specify the PM2 App name or id):

      Restart an application:

      • pm2 restart app_name_or_id

      List the applications currently managed by PM2:

      Get information about a specific application using its App name:

      The PM2 process monitor can be pulled up with the monit subcommand. This displays the application status, CPU, and memory usage:

      Note that running pm2 without any arguments will also display a help page with example usage.

      Now that your Node.js application is running and managed by PM2, let's set up the reverse proxy.

      Step 4 — Setting Up Nginx as a Reverse Proxy Server

      Your application is running and listening on localhost, but you need to set up a way for your users to access it. We will set up the Nginx web server as a reverse proxy for this purpose.

      In the prerequisite tutorial, you set up your Nginx configuration in the /etc/nginx/sites-available/your_domain file. Open this file for editing:

      • sudo nano /etc/nginx/sites-available/your_domain

      Within the server block, you should have an existing location / block. Replace the contents of that block with the following configuration. If your application is set to listen on a different port, update the highlighted portion to the correct port number:

      /etc/nginx/sites-available/your_domain

      server {
      ...
          location / {
              proxy_pass http://localhost:3000;
              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection 'upgrade';
              proxy_set_header Host $host;
              proxy_cache_bypass $http_upgrade;
          }
      ...
      }
      

      This configures the server to respond to requests at its root. Assuming our server is available at your_domain, accessing https://your_domain/ via a web browser would send the request to hello.js, listening on port 3000 at localhost.

      You can add additional location blocks to the same server block to provide access to other applications on the same server. For example, if you were also running another Node.js application on port 3001, you could add this location block to allow access to it via https://your_domain/app2:

      /etc/nginx/sites-available/your_domain — Optional

      server {
      ...
          location /app2 {
              proxy_pass http://localhost:3001;
              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection 'upgrade';
              proxy_set_header Host $host;
              proxy_cache_bypass $http_upgrade;
          }
      ...
      }
      

      Once you are done adding the location blocks for your applications, save the file and exit your editor.

      Make sure you didn't introduce any syntax errors by typing:

      Restart Nginx:

      • sudo systemctl restart nginx

      Assuming that your Node.js application is running and your application and Nginx configurations are correct, you should now be able to access your application via the Nginx reverse proxy. Try it out by accessing your domain in the browser: https://your_domain.

      Conclusion

      Congratulations! You now have your Node.js application running behind an Nginx reverse proxy on a Debian 10 server. This reverse proxy setup is flexible enough to provide your users access to other applications or static web content that you want to share.



      Source link