In today's era, where web applications increasingly rely on dynamic server-side processing, Node.js has become one of the leading environments for developing such applications. When it comes time to deploy these applications to a production server, it's important to ensure they run reliably 24/7 without the need for manual intervention. This is where PM2 comes into play, an advanced, powerful, and flexible process manager for Node.js that allows users to easily manage and maintain their applications in operation. This article provides a step-by-step guide on how to deploy a Node.js application on a Virtual private server (VPS) using PM2.
1. Setting Up the Environment
Before running the application, it is necessary to have Node.js and NPM (Node Package Manager) installed. This can be done using the following commands:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
2. Installing PM2
PM2 is a tool that runs as a background service and automatically restarts your application if it crashes. PM2 can be easily installed using NPM:
sudo npm install pm2 -g
3. Configuring the Application
After installing PM2, it's time to prepare your Node.js application. Make sure your application is uploaded to the VPS and that all dependencies are properly installed using the npm install
command in your application directory.
4. Starting the Application with PM2
You can start your application using PM2 with a simple command, which will also allow your application to automatically restart upon system reboot:
pm2 start app.js --name "myApp"
Replace app.js
with the name of the file that starts your application, and myApp
with a meaningful name for your application.
5. Setting Up Automatic Restart
PM2 offers the option to automatically restart applications after the server restarts. This can be achieved using the command:
pm2 startup systemd
After running this command, PM2 will display a command that needs to be copied and executed to activate this feature.
6. Maintaining the Application
PM2 provides useful commands for managing running applications, such as monitoring logs, displaying a list of running processes, and restarting them:
- To display logs, use
pm2 logs
. - To display a list of all applications managed by PM2, use
pm2 list
. - To restart an application, use
pm2 restart myApp
.
PM2 is a powerful tool for managing Node.js applications, simplifying their deployment and maintenance on production servers. With PM2, you can be confident that your application will always be running regardless of circumstances. With this guide, you should be able to easily deploy and manage your Node.js applications on any VPS.