askvity

How to Run Node.js on a Server?

Published in Node.js Deployment 5 mins read

Running a Node.js application on a server involves several steps, from setting up your code to ensuring it stays running reliably. Here's a breakdown of the process:

Step 1: Prepare Your Node.js Application

  • Create your Node.js application: This involves writing the server-side code using JavaScript, defining routes, and handling requests. A basic "Hello, World!" example might look like this (in a file named server.js):

    const http = require('http');
    
    const hostname = '127.0.0.1';
    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}/`);
    });
  • Install dependencies: Use npm install in your project directory to install all the necessary packages listed in your package.json file. This file should be located at the root of your node project and is usually created by running npm init command.

Step 2: Choose a Server Environment

You have several options for hosting your Node.js application:

  • Virtual Private Server (VPS): Provides more control and flexibility, allowing you to configure the environment exactly as needed. Examples include DigitalOcean, Linode, and Vultr.

  • Platform as a Service (PaaS): Simplifies deployment and management by providing a pre-configured environment. Examples include Heroku, AWS Elastic Beanstalk, and Google App Engine.

  • Cloud Functions/Serverless: Execute code in response to events, without managing servers. Examples include AWS Lambda, Google Cloud Functions, and Azure Functions.

Step 3: Upload Your Application

  • Using Git: If you're using Git for version control (recommended), you can push your repository to a service like GitHub, GitLab, or Bitbucket. Then, on your server, you can clone the repository.

  • Using FTP/SCP: You can use FTP (File Transfer Protocol) or SCP (Secure Copy Protocol) to directly upload your files to the server.

Step 4: Install Node.js and npm

On your server, you'll need to install Node.js and npm (Node Package Manager). The installation process varies depending on the operating system:

  • Linux (Debian/Ubuntu):

    sudo apt update
    sudo apt install nodejs npm
  • Linux (CentOS/RHEL):

    sudo yum install nodejs npm
  • macOS: You can use Homebrew:

    brew install node

Step 5: Run Your Application

  1. Navigate to your application directory on the server using the cd command.
  2. Start the server: In your terminal, run node server.js (or whatever your main application file is named). This command will start the Node.js server.
  3. Test the application: Open a web browser and navigate to the server's IP address or domain name on the specified port (e.g., http://your_server_ip:3000). You should see the "Hello, World!" message (or whatever your application outputs).

Step 6: Keep Your Application Running (Process Manager)

To ensure your application stays running even if it crashes or the server restarts, you should use a process manager like PM2 or Forever:

  • PM2 (Recommended):

    1. Install PM2 globally: npm install -g pm2
    2. Start your application with PM2: pm2 start server.js
    3. To ensure PM2 restarts your app on server reboot: pm2 startup systemd (followed by the command PM2 provides at the end of execution).
    4. Save the current PM2 process list: pm2 save
  • Forever:

    1. Install Forever globally: npm install -g forever
    2. Start your application with Forever: forever start server.js

Step 7: Configure a Reverse Proxy (Optional, but Recommended)

A reverse proxy like Nginx or Apache can improve security, performance, and manageability. It sits in front of your Node.js application and handles incoming requests, forwarding them to the appropriate application server.

  • Nginx (Example):

    1. Install Nginx: sudo apt install nginx (Debian/Ubuntu) or sudo yum install nginx (CentOS/RHEL).

    2. Create a new Nginx configuration file in /etc/nginx/sites-available/. For example, sudo nano /etc/nginx/sites-available/your_app.

    3. Add the following configuration (adjust the port and server name as needed):

      server {
          listen 80;
          server_name your_domain.com; # Replace with your domain
      
          location / {
              proxy_pass http://localhost:3000; # Proxy to your Node.js app
              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;
          }
      }
    4. Create a symbolic link to enable the configuration: sudo ln -s /etc/nginx/sites-available/your_app /etc/nginx/sites-enabled/

    5. Test the Nginx configuration: sudo nginx -t

    6. Restart Nginx: sudo systemctl restart nginx

Step 8: Stopping the Server

  • Using Ctrl+C: To stop the server manually, simply press Ctrl+C in the terminal where the server is running (if not using a process manager).
  • Using PM2: pm2 stop server.js or pm2 stop <app_name> or pm2 stop all
  • Using Forever: forever stop server.js or forever stop <pid> (find the PID using forever list).

By following these steps, you can successfully run your Node.js application on a server, ensuring it's accessible, reliable, and properly managed.

Related Articles