Deploy NodeJs & React Use pm2
A concise guide to deploy a Node.js and React app using PM2, covering frontend build, file transfer, and reliable serving.
Step 1: Build the React Frontend
Compile your React application into production-ready static files with the following command:
npm run build
This generates optimized assets in the build directory (or a custom output folder if configured otherwise in your package.json).
Step 2: Transfer Build Files to the Server
Move the contents of the build folder to your Node.js server’s designated directory. You can use secure file transfer methods like scp or rsync. For example:
scp -r build/* user@server:/path/to/app/static
Additionally, ensure your Node.js backend files (e.g., server.js, package.json) are also transferred to the server’s root application directory.
Step 3: Serve the Application with PM2
Run your Node.js application and serve the React frontend using PM2, a powerful process manager. Use the following steps:
Install PM2 on the server (if not already installed):
npm install -g pm2
Start the Node.js App:
Navigate to your app’s root directory and launch the backend with PM2:
pm2 start server.js --name "node-react-app"
Replace server.js with your main Node.js entry file and "node-react-app" with a custom app name.
Serve Static Files (if not handled by Node.js):
If your Node.js app doesn’t serve the React build files directly (e.g., via Express), use PM2 to serve them separately:
pm2 serve /path/to/app/static --name "react-frontend" --port 3000
Adjust
/path/to/app/staticto the folder containing your React build files.Set
--portto your desired port (e.g.,3000).
Best Practices:
Ensure your Node.js app is configured to serve static files (e.g., using
express.static) if you want a single process.Test the deployment by accessing
http://<server-ip>:<port>in a browser.Monitor logs with
pm2 logsor manage processes withpm2 listfor troubleshooting.
This approach leverages PM2’s capabilities to keep your Node.js and React application running smoothly in production.