Setting up a Create-React-App with PM2 and Nginx on AWS EC2

Next: Creation of the NGINX server

sudo apt-gey install nginx -y

cd /etc/nginx/sites-available/
vi my-app.com

Inside this file we add server configurations

server {
listen 80;
  server_name my-app.com;
  server_name your.server.ip.goes.here;

  root /home/ubuntu/my-app.com;
  index index.html;
  
  access_log /var/log/nginx/my-app.com.access.log;
  error_log /var/log/nginx/my-app.com.error.log;

  # Use below if your app is configured to render on Port 80
  location / {
    try_files $uri /index.html =404;
  }

  # Use below if your app is configured to run on a dev port
  location / {
    try_files $uri /index.html =404;

    proxy_pass http://localhost:<app-port-number>/;
    proxy_http_version 1.1;
    proxy_set_header HOST $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
  }

}

Note: Do not forget to

  • replace app-name with your project name
  • add your application port number

Verify your nginx configuration does not have any errors and restart nginx server

# verify nginx configuration
sudo nginx -t

# restart nginx server to load new configuration
sudo systemctl restart nginx

Last step: Start the application with below command

pm2 start my-app/node_modules/react-scripts/scripts/start.js --name "my-app"

Below are few commands that are handy while using pm2

pm2 status
pm2 restart my-app
pm2 stop my-app
pm2 start my-app
pm2 delete my-app