Hosting a React App in EC2

The easy way...

Connect to instance using SSH

cd /path/to/keyfile
shh -i "keyfilename.pem" username@ipaddress

Clone the repo

git clone repo-url

HTTPS Cloning credentials

  • Username - GitHub username

  • Password - Personal access token

Install Node

sudo snap install node --classic

Install packages and build

cd repofolder
npm i
npm run build

Now, you’ll have your static HTML, CSS, JS files of your react app in the build folder which you can serve using Nginx, Apache, or serve node package

Serving static build files with serve

Refer - https://create-react-app.dev/docs/deployment/

sudo npm install -g serve
sudo serve -s build -l 80

We serve to port 80 using -l 80 so that we can access it without mentioning the port. 80 is the default port for HTTP

💡Your site will now be live at http://ipaddress

If you are unable to access the site, you have to enable Outbound traffic to Port 80 in EC2 security group network rules.

Using screen to persist the terminal session

Normally, the terminal where the react app is running will get terminated when we close the SSH session. We can use screen to create a terminal session that will run detached even when we close our terminal session.

→ Use the command screen and press enter in the following prompt to create a new session. You can use the serve command from here.

→ Use screen -r to resume the previous screen in a separate SSH session.

When you make a change

Once you push a change to your GitHub,

→ Use git pull in your server to bring in the new changes.

→ Use npm run build to rebuild with the new changes

Last updated