Once your Node.js application runs flawlessly locally, the next step is moving it to a production web server. Unlike PHP, where files are simply dropped into a directory, Node.js requires its own continuous background process and proper server configuration.
In this guide, we will look at a professional way to install Node.js on a Linux (Ubuntu/Debian) server using NVM, the PM2 process manager, and the Nginx web server.
1. Installing Node.js via NVM
Instead of installing directly via the system package manager (apt), it is much better to use NVM (Node Version Manager). This allows you to easily switch between Node.js versions without breaking system dependencies.
# Downloading and running the NVM installation script curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash # Reload terminal configuration source ~/.bashrc # Installing the latest stable LTS release of Node.js nvm install --lts # Verifying the installation success node -v npm -v
2. Keeping the App Running 24/7 with PM2
If you start your app with the node app.js command, it will stop immediately as soon as you close
your terminal. To keep your application running 24/7 and ensure it automatically restarts on crashes or server
reboots, we use the PM2 process manager.
# Installing PM2 globally via npm sudo npm install pm2 -g # Starting your application and naming the process pm2 start app.js --name "my-node-project" # Configuring PM2 to automatically launch on Linux server boot pm2 startup # (Follow the command printed on screen by PM2 and paste it!) # Saving the current process list state pm2 save
3. Configuring Nginx as a Reverse Proxy
Your Node.js application usually listens on a specific local port (e.g., port 3000). To make it accessible to the world via standard port 80 (HTTP) or 443 (HTTPS), we place Nginx in front of it to act as a Reverse Proxy.
Open your website\'s Nginx configuration file:
sudo nano /etc/nginx/sites-available/default
Inside the location / block, adjust the settings to forward traffic to your app\'s local port:
server {
listen 80;
server_name your-domain.com www.your-domain.com;
location / {
proxy_pass http://localhost:3000; # The port where Node.js is listening
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;
}
}
Save the file, test the Nginx configuration, and restart the service:
sudo nginx -t sudo systemctl restart nginx
Now, your Node.js application is securely isolated in the background of your server, while Nginx professionally and efficiently handles all external visitor requests.