Learn how to deploy a React app with Nginx on Ubuntu. Step-by-step guide covering build, server config, reverse proxy, SSL, and production optimization.
To host a React application on an Ubuntu server, you need to
install Node.js and npm, build your application, and then use a web server like Nginx to serve the static files.Prerequisites
- An Ubuntu server (virtual machine or physical).
- SSH access to your server (use a client like PuTTY on Windows).
- A React application built on your local machine.
Step-by-Step Deployment Guide
- Connect to Your Server
Use SSH to connect to your Ubuntu server using its IP address and your credentials. - Install Node.js and npm
React requires Node.js and npm to build the application.- Update your server's package list:
sudo apt update - Install Node.js and npm:
sudo apt install nodejs npm - Verify the installation:
node -vandnpm -v
- Update your server's package list:
- Transfer Your React App Files
Build your React application on your local machine using the command:npm run build. This creates a production-optimizedbuilddirectory. Transfer the contents of thisbuilddirectory to your Ubuntu server using tools likescp,rsync, or by cloning your repository from GitHub on the server itself. - Install and Configure Nginx
Nginx is a high-performance web server that will serve your application's static files.- Install Nginx:
sudo apt install nginx - Start and enable the Nginx service:
sudo systemctl start nginxandsudo systemctl enable nginx - Create a new Nginx configuration file for your site in the
/etc/nginx/sites-available/directory. You can use a text editor likenano(e.g.,sudo nano /etc/nginx/sites-available/your_domain):(Replacenginxserver { listen 80; server_name your_domain www.your_domain; root /var/www/your_domain/html; index index.html index.htm; location / { try_files $uri $uri/ /index.html; } }your_domainwith your actual domain name and adjust therootpath to where you placed your build files, for example,/var/www/your_domain/html).
- Install Nginx:
- Enable Your Nginx Site
- Create a symbolic link from your configuration file in
sites-availableto thesites-enableddirectory:sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/ - Test your Nginx configuration for syntax errors:
sudo nginx -t - Restart Nginx to apply the changes:
sudo systemctl restart nginx
- Create a symbolic link from your configuration file in
Your
React application should now be accessible in a web browser via your
server's IP address or domain name. For a secure connection, you should
also set up SSL certificates using a tool like Certbot.
No comments:
Post a Comment