📜  deploy create react app pm2 - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:26.343000             🧑  作者: Mango

Deploy Create React App with PM2

If you're building a React application with Create React App, you might want to deploy it on a production environment. One popular tool to help with deployment is PM2, a process manager for Node.js applications. This article will walk you through the process of deploying your React app with PM2.

Prerequisites

Before we get started, make sure you have the following installed on your production server:

  • Node.js
  • NPM
  • PM2

If you haven't installed PM2 yet, you can do so by running:

npm install pm2 -g
Building Your React App

Before we can deploy our app, we need to build it. If you haven't done so already, run the following command in your React app directory:

npm run build

This will create a build folder in your app's directory with all the necessary files to run your app.

Deploying with PM2

To deploy your app with PM2, follow these steps:

  1. Open a terminal on your production server and navigate to your app's directory.

  2. Start your app by running the following command:

    pm2 start npm --name "my-app" -- start
    

    This will start your app using the start script defined in your package.json file. The --name option sets a custom name for your app, which you can use to reference it later.

  3. Check that your app is running by running:

    pm2 list
    

    You should see your app listed with the name you set in the previous step.

  4. Set up a reverse proxy to serve your app. This step will vary depending on your server setup, but generally involves setting up a web server (such as Nginx or Apache) to proxy requests to your app running on a specific port. For example, if your app is running on port 3000, you could set up Nginx to serve your app on port 80. Here's an example Nginx configuration:

    server {
        listen 80;
        server_name mydomain.com;
    
        location / {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
    

    Update the server_name, proxy_pass, and other settings as necessary for your setup.

  5. Save your Nginx configuration and restart Nginx:

    sudo service nginx restart
    

    Your React app is now deployed and served by Nginx, with PM2 managing the Node.js process.

Conclusion

In this article, we walked through the steps to deploy a Create React App with PM2. With PM2, you can easily manage your Node.js processes and scale your app as needed.