Getting started with react takes minutes but production deployments (although quick) can be intimidating. This post documents the step-by-step deployment using Ubuntu 18.04 LTS and NGINX.

Objectives

Time required: 10 minutes

Prerequisites

To follow along, you should have the following:

  1. A basic understanding of how JavaScript and React
  2. Somewhere to host your application (I will be using a GCP VM instance)

Throughout the article the following domain is used mydomainname.com, this needs to be replaced with the domain name or IP of your server. For SSL and HTTPS setup this guide can be followed.


Step 1 - build your application

Before deploying the application you must build the project which produces a directory with an optimized codebase. This is contained within a build folder and encapsulates everything the application needs to run. If the application is deployed somewhere other than your development system you can either build the code locally and migrate the codebase and build on the deployment machine or migrate just the build directory.

cd project-folder
sudo npm install
sudo npm run build

This creates a build folder directly within the working directory. Before moving to the next step, let's relocate the folder to a typical deployment location /var/www/. Create this /var/www/ folder if it does not exist and copy over the build directory.

sudo mkdir /var/www/
sudo scp -r ./build/* /var/www/build/

Next NGINX needs to be configured to serve this build.

Step 2 - install and configure NGINX

Install NGINX using the following command sudo apt install nginx. This creates an NGINX folder under /etc/nginx/. To host the web app, the default NGINX config file must be updated or a new one created. In this walkthrough, the existing default file is replaced. Change the content of the file /etc/nginx/sites-enabled/ to the following:

server {
    listen 0.0.0.0:80;
    server_name mydomainname.com;
    access_log /var/log/nginx/app.log;
    root /var/www/build;
    index index.html index.htm;
    try_files $uri /index.html;
    location / {
        try_files $uri $uri/ = 404;
    }
}

Note: /var/www/build must coincide with the location of the production build folder from the previous step.

Note: server_name value ( mydomainname.com above) must coincide with the server's access point. This can either be the IP address or domain name.

Step 3 - deploy

For the changes to take effect the NGINX service must be restart:

sudo service nginx stop
sudo service nginx start

The application should now be running and accessible using the server_name provided in the config file.

Good luck and happy coding!