Preamble
PM2 is a NodeJS process management tool that can automatically manage and restart processes when there is an error. In addition, PM2 can also be used to deploy ReactJS as a production build. Here are the steps to deploy a ReactJS application using PM2 on a windows machine:
Perform
- Build apps
- First of all, you need to create a ReactJs project and build your application:
- Create a project:
1 2 |
npx create-react-app my-app |
- Build project
1 2 |
npm run build |
or:
1 2 |
yarn run build |
- PM2 settings
- You need to install PM2 to serve the application, use the following command in the terminal:
1 2 |
npm install pm2 -g |
- Run the newly built directory with PM2
1 2 |
pm2 serve <path> <port> |
- Now, we need to get the build directory to run in PM2 by:
1 2 |
pm2 serve myReactApp/ 3000 --name "my-react-app" --spa |
- myReactApp/: The directory of the application. You need to point to the correct directory you just built above.
- 3000: Port to serve.
- “my-react-app”: Name for the project. This name will be displayed in the progress of PM2 with the command “pm2 list”. Otherwise pm2 will generate the name automatically
- –spa: Parameter for Single Page Application, redirect to the original URL. This parameter is required for react apps because otherwise the page won’t be able to show the router again when reloading the page.
- For example, Here I will run the dashboard project on port 3000:
1 2 |
pm2 serve ./build 3000 --name "dashboard" --spa |
- Monitor and manage running applications with PM2:
- We can see all running processes with the command:
1 2 |
pm2 llist |
- Go to localhost:3000 to see the application just started:
1 2 |
- And can start, stop or delete running processes with:
1 2 |
pm2 <start/stop/delete> <process id/process name> |
- Example to stop the application just running above:
1 2 |
pm2 stop dashboard |
Finish
- Above is the simple way to run React application with PM2. You can do the same on VPS to deoploy your React application. Thanks!! https://pm2.keymetrics.io/