How To Deploy a React app using Nginx and Ubuntu 16.04 / 18.04 LTS / 19.10 / 20.04 LTS
This story will assist you to deploy React or any JS application in Ubuntu.
Server requirements
You need a Linux based system, I’m gonna use Ubuntu 18.04 for this story, you are free to use your own 😀
Disk : ~25GB
Memory : 2GB
CPU: 1 core
First logged into your remote system via ssh (Secure Shell).
ssh root@server_ip_address
Let’s begin by updating server’s package index
sudo apt-get update
Installation
Step 1: Install NodeJS and npm
Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. NPM is a package manager for the JavaScript programming language. It is the default package manager for Node.js.
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
sudo apt-get install nodejs
Check your Node & NPM version now
node -v
npm -v
Step 2: Install Nginx
Nginx is a totally free, open-source, high-performance HTTP server.
sudo apt-get install nginx
Step 3: Deployment
cd /var/www/html
sudo git clone [Your repository URL with branch]
cd [Your Repository Name]
sudo npm install
sudo npm run build
Step 4: Permit Nginx to access your application folder
sudo gpasswd -a "$USER" www-data
sudo chown -R "$USER":www-data /var/www/html
find /var/www/html -type f -exec chmod 0660 {} \;
sudo find /var/www/html -type d -exec chmod 2770 {} \;
Step 5: Configure Nginx to serve your React application
sudo rm -rf /etc/nginx/sites-available/default
sudo rm -rf /etc/nginx/sites-enabled/default
sudo nano /etc/nginx/sites-available/myreactapp
Now paste the below code in myreactapp file
server {
listen 80;
server_name [your_IP] [domain.com] [www.domain.com];
root /var/www/html/[directory]/build;
index index.html index.htm; location / {
try_files $uri /index.html =404;
}}
Step 6: Enable the file by linking to the sites-enabled dir
sudo ln -s /etc/nginx/sites-available/myreactapp /etc/nginx/sites-enabled
Step 7: Test Nginx config
sudo nginx -t
You should see output like this
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
If the test failed then check the Nginx configuration step again.
Step 8: Do not forget to restart your Nginx server
sudo systemctl restart nginx
Now open your browser and go to http://youripaddress or http://domain.com
If you want to activate SSL certificate on your domain/app, please read this story.
Have fun 🔥 💪
If you have any query, please put in below. Find me on Github.