简体   繁体   中英

React site giving 502 Bad Gateway on domain if npm start is not running, nginx

So I am trying to make my react website work where the website doesnt load unless npm start is initiated in the root directory. I need the website to always work even if I am not running npm start.

As you can tell, I am a complete noob in how react sites work, so some help would be appreciated. Thanks.

The package.json is:

    {
  "name": "XXXXX",
  "version": "1.0.0",
  "description": "XXXXXXXX",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
    "build": "node index.js"
  },
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.19.0",
    "ejs": "^3.1.3",
    "express": "^4.17.1",
    "node-fetch": "^2.6.0",
    "request": "^2.88.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.4"
  }
}

If you're hosting it on for example Debian or Ubuntu with SystemD, you could create a Service file for that task.

Firstly you have to create a service file for that:

nano /etc/systemd/system/my-react-js-service.service

With the content:

[Unit]
Description=ReactJS Website Service
After=network.target
After=nginx.service

[Service]
Type=simple
User=www-data
Restart=on-failure
WorkingDirectory=/var/www/<your-code-directory>
ExecStart=npm start

[Install]
WantedBy=multi-user.target

The working directory needs to be the directory in wich you normally run npm start and the user must be the user with whom you normally run npm start . Be sure that the user has enough permissions in the working directory.

Now you have to reload SystemD:

systemctl daemon-reload

And finally start your Service:

systemctl start my-react-js-service.service

If you want, you can also start your service on startup with the following command:
 systemctl enable my-react-js-service.service

You can use npm build to create a production version of your site, that you can host on your server. This won't need npm start to work.

npm build will create a build directory. You need to take all of the files generated/copied inside and put them on your server.

You can read more about the process here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM