Search code examples
reactjspm2foreverservereact-scripts

React build run on server using pm2


I have compiled my react app using

react-scripts build

And it generated a build\ folder in the root directory of App. I am running the build\ folder using

sudo serve -T -p 443 build/

This runs my React app successfully on HTTPS since I am passing -T. But I needed to run my app forever using any of the modules available. I was looking into node modules forever & pm2. I am trying to using pm2 in the following way:

sudo pm2 serve -T -p 443 build/

It throws:

error: unknown option `-T'

and when I use:

sudo pm2 serve -p 443 build/

It works on console but I am not able to access my app from URL

[ec2-user@ip-10-XXX-XX-XXX UI]$ sudo pm2 serve -p 443 build/
[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /usr/local/lib/node_modules/pm2/lib/API/Serve.js in fork_mode (1 instance)
[PM2] Done.
[PM2] Serving /var/www/html/UI/build on port 8080
┌─────────────────────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐
│ App name                │ id │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ user │ watching │
├─────────────────────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤
│ static-page-server-8080 │ 0  │ fork │ 26609 │ online │ 0       │ 0s     │ 2%  │ 21.7 MB   │ root │ disabled │
└─────────────────────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

Can someone help me with this? Or if there is any other way to run your react app on production forever.


Solution

  • You need to use a pm2 JSON config to run arbitrary binaries:

    app.config.json

    {
      apps : [
        {
          name      : "your-app",
          script    : "npx",
          interpreter: "none",
          args: "serve -p 8443 -T"
        }
      ]
    }
    

    To start:

    pm2 start app.config.json
    

    interpreter: "none" tells pm2 not to treat the script like a JavaScript file when executing, and instead to treat it like an ordinary binary.

    If you have a serve binary in the same directory as the app config, you can execute serve directly instead of npx.