How to deploy a react app using pm2 on a Server
Step 1 : Install PM2 Using NPM
Use the NPM package manager to install PM2 by entering the following command in the terminal:
npm install pm2 -g
Step 2 : Generate a PM2 Start Script for the Init System:
PM2 is designed to operate with the default init system on a Linux system (which it can automatically detect) to produce the startup script and set up PM2 as a service that can then be restarted at system boot. Simply execute the following command as root to generate the startup script:
Step 5 : Build React for Production Using PM2
Do the steps as follows:
1. Create a React app using this command (ignore the first command, if you have already created a project):
npx create-react-app react-app && cd react-app
2. Run this command when the React project is open:
npm run build
This will generate a build/folder in your project.
Step 6 : Run PM2 Command
Put now the project in the command by calling
pm2 serve build/ 3000 --name "my-react-app" --spa
- The build folder of the app: build
- The port for the serve: 3000
- The name for the PM2 Process will be visible in the "pm2 list": "my-react-app"
- The parameter for Single Page Application redirects to the root URL: --spa
Step 7 : Apps Running
Your applications are now running on port :3000, which we can access by opening a browser and going to yourdomain.com:3000 or your-ip:3000.
By setting up the apache sites-enabled with ProxyPreserveHost and ProxyPass, we can also hide the port from the URL.
Step 4 : Manage the Application
Let's use the following commands in the terminal to restart, reload, stop, and delete operational processes in the Node JS application using PM2:
- The application will restart:
pm2 restart my-react-app
- The application will reload:
pm2 reload my-react-app
- The application will stop:
pm2 stop my-react-app
- The application will delete:
pm2 delete my-react-app
The tutorial allows anyone to quickly and effectively learn the processes of the installation and configuration of PM2 on Ubuntu 22.04.