I recently finished one of my projects and wanted to host it online for the world to see all its beauty. I didn’t want to use Heroku as I thought that it abstracts too much of the server configurations and I myself wanted to know how the server configs worked.
I first started looking around on how to host a React app on DigitalOcean. Side note, if you haven’t set up a Linux VPS on DigitalOcean before, I’d highly recommend. It’s one of the simplest things to do and for the cheapest option it’s about 5$ a month. Not being paid to say that, I just enjoy their service and I’ll be using it on for the rest of the tutorial. Ok back to the server. I used DigitalOcean’s NodeJS One-Click app as my starting template.
After the server was created, I like to secure the server the first time I log in, here’s a link to an article I follow. Next do the installations.
sudo apt-get install nginx
sudo npm i -g create-react-app react-scripts@latest pm2@latest
Go to a directory where you’d like to your React app and run:
create-react-app my-app
Once you have a ready to deploy application, go to your react app’s directory and run
sudo npm run build
The above code creates a minified version of your code optimized for production in the my-app/build directory.
We use PM2 as an application manager in order to keep our app running after we log out of the server.
pm2 start my-app/node_modules/react-scripts/scripts/start.js --name "my-app"
This will have our application running in the background.
Here’s a few commands to note when using pm2:
pm2 status pm2 restart my-app pm2 stop my-app pm2 start my-app pm2 delete my-app
Now it’s time we get Nginx configured in order to expose our application.
First, create a new site in /etc/nginx/sites-available/
cd /etc/nginx/sites-available/ vim my-app.com
Then inside /etc/nginx/sites-available/my-app.com place the server configurations:
server {
listen 80; server_name my-app.com; server_name your.server.ip.goes.here; root /root/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;
location / { try_files $uri /index.html =404; }
}
Nginx needs to be told that a given site is active. To do this, create a symlink in sites-enabled
cd /etc/nginx/sites-enabled ln -s ../sites-available/my-app.com
Run nginx -t
to see if there are any errors with the config file, if any come up, try and find the error and correct it.
Restart Nginx:
/etc/init.d/nginx restart
Navigate to your servers IP on your local computer and your site should now be hosted!
ACTUALIZACIÓN
pm2 start "serve -s build" --name "react_pwa_eros"