To serve a build folder using PM2, you can follow these steps:

  1. Build Your Application: First, make sure you have built your application and have the necessary files in the build folder. The build folder should contain the production-ready files that are ready to be served.

  2. Install PM2: If you haven't already, install PM2 globally on your server using npm:

    npm install -g pm2
  3. Serve the Build Folder with PM2: Use PM2 to serve the build folder as a static file server. You can do this by running PM2 with the serve command and specifying the path to the build folder:

    pm2 serve /path/to/your/build-folder 8080

    Replace /path/to/your/build-folder with the actual path to your build folder, and 8080 with the desired port number. PM2 will start serving the build folder on the specified port.

  4. Setting Up Startup Script: To ensure your application starts automatically on server boot, you can set up a startup script for PM2. This will vary depending on your server's operating system.

    For example, on Linux, you can use the following command to generate the startup script:

    pm2 startup

    This will display a command that you need to run to set up the startup script. Execute the provided command to enable PM2 to start your application on server boot.

  5. Manage Your Application with PM2: Once your application is running with PM2, you can use various PM2 commands to manage it. For example:

    • To list all running applications managed by PM2: pm2 list
    • To stop your application: pm2 stop <app_name_or_id>
    • To start your application: pm2 start <app_name_or_id>
    • To restart your application: pm2 restart <app_name_or_id>
    • To view logs: pm2 logs <app_name_or_id>

PM2 will handle serving the static files from the build folder and restart your application automatically if it crashes. It's a robust process manager that makes it easy to run and manage Node.js applications in production environments.

Have questions or queries?
Get in Touch