How to Build React Application using Docker vs NGINX

In this post, we will see the details and implementation of Build React Application using Docker vs NGINX. We will go through step by step with an example.

Example Project

This is a simple project which demonstrates serving static React application with NGINX and Docker. We have a simple app with a header, footer and with a message.

Here is the example project where you can clone and run on your machine

// clone the project
git clone https://github.com/bbachi/react-nginx-docker

// install and start the dependencies
npm install
npm start

// build the docker image
docker build -t react-ui .
// run the app
docker run -d --name reactui -p 80:80 react-ui

This is a simple React app that has the header, footer and some message on the dashboard. Here are the Header.js, Footer.js and, App.js files

import React from 'react';

const Header = () => {

    return (
        <div class="header">
            Simple React App
        </div>
    )
    
};

export default Header

Header.js

import React from 'react';

const Footer = () => {

    return (
        <div class="footer">
            2020
        </div>
    )
    
};

export default Footer

Footer.js

import React from 'react';
import Header from './header/header'
import Footer from './footer/footer'
import './App.css';

function App() {
  return (
    <div className="App">
      <Header />
      <div class="dashboard">
        <h1>Simple React App served by NGINX and Docker</h1>
      </div>
      <Footer />
    </div>
  );
}

export default App;

App.js

Just Enough NGINX For This Project

We are not going through everything about NGINX here and we just go through just enough for this project. If you are already familiar with this stuff, you can skip over to the next section.

NGINX processes are divided into one master process and several worker processes. The master process takes care of evaluating configuration and maintaining worker processes and the worker processes take care of actual requests. We can define the number of worker processes in the configuration file which can be placed in the directory /usr/local/etc/nginx, /etc/nginx or /usr/local/nginx/conf.

The configuration file consists of directives that form the modules or contexts. There are two kinds of directives: simple directives and block directives. A simple directive has names and parameters separated by a space and ends with a semicolon like this listen 80; . A block directive is the same but has additional information and surrounded by braces like this { listen 80; root /usr/share/nginx/html; }.

Let’s understand the NGINX configuration file that we used in this project. Below is the nginx.conf file which is located under folder .nginx at root location of the project.

Everything is a context in the configuration file. We have a hierarchical context that starts with the main context. For example, worker_processes and events are defined in the main context and another context starts with http. We have another context inside http called server which listens on port 80 and serving static assets from the root location /usr/share/nginx/html.

We can have multiple declarations of the server inside the http context and we can have multiple declarations of location inside the server context.

worker_processes 4;

events { worker_connections 1024; }

http {
    server {
        listen 80;
        root  /usr/share/nginx/html;
        include /etc/nginx/mime.types;

        location /appui {
            try_files $uri /index.html;
        }
    }
}

nginx.conf

Implementation

We use Docker as a container runtime for this project. We are using multi-stage builds to build the Docker image. Here is the Dockerfile for the project.

# stage1 as builder
FROM node:10-alpine as builder

# copy the package.json to install dependencies
COPY package.json package-lock.json ./

# Install the dependencies and make the folder
RUN npm install && mkdir /react-ui && mv ./node_modules ./react-ui

WORKDIR /react-ui

COPY . .

# Build the project and copy the files
RUN npm run build


FROM nginx:alpine

#!/bin/sh

COPY ./.nginx/nginx.conf /etc/nginx/nginx.conf

## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*

# Copy from the stahg 1
COPY --from=builder /react-ui/build /usr/share/nginx/html

EXPOSE 3000 80

ENTRYPOINT ["nginx", "-g", "daemon off;"]

Dockerfile*\

Stage 1

We are using node:10-alpine as a base image for the stage1 and copying package.json to install all the dependencies. We then copy the remaining project later, in that way we can skip the installing dependencies every time there is a change in the files. Docker uses a cache to build the image from existing layers if there is no change.

We build the project with the react-scripts and all the built static files are placed in the /build folder.

Stage 2

Stage 2 starts with the base image nginx:alpine and copy the nginx.conf file, remove the index file from the root location, and finally, copy all the files from stage 1 to the root location where it can serve the content from.

Build the Image and Run the Project

Let’s build the project with this command docker build -t react-ui. and you can run the project with this command docker run -d --name reactui -p 80:80 react-ui . You can run the app on [http://localhost:80](http://localhost:80/appui)

Project running on localhost

Important Things to notice

The container port and nginx listen port should be the same which is 80 otherwise you would get ERR_EMPTY_RESPONSE when you run the project.

// container port
docker run -d --name react-ui -p 80:80 reactui

// nginx conf
http {   
   server {
      listen 80;
   }
}

We should include this directive in the nginx.conf file otherwise all the styles are rendered as plain text in the browser.

include /etc/nginx/mime.types;

Exec Into the Running Container

While the container is in running state we can exec into it and see the contents of the file system.

docker exec -it reactui /bin/sh

We can actually see all the contents under /usr/share/nginx/html

File system inside docker

Summary

  • NGINX can be used as a web server or reverse proxy to serve the static content.
  • All the NGINX configuration can be placed in this file nginx.conf .
  • We need to build the react app and place all the static files in the root location of the NGINX to serve the web.
  • Docker is used as the container runtime.
  • We use multi-stage builds to reduce the final image size and remove unnecessary files from the production environment.
  • Docker image can be built with docker build -t react-ui .
  • Run the container with this command docker run -d --name reactui -p 80:80 react-ui.
  • It’s very important to match ports while running the container and the listen port in nginx.conf file. Otherwise, you would get an ERR_EMPTY_RESPONSE error**.**
  • You can exec into the container to explore the file system with this command docker exec -it reactui /bin/sh.

Conclusion

NGINX is a high-performance web server that serves content and application delivery, improves security, facilitates availability and scalability for the web apps. If you want to avoid or there is no need for building UI apps with Java or node js server runtime, you can build the UI app and serve the static files with the NGINX at scale. Thank you for reading!

#react #docker #javascript #nginx #development

How to Build React Application using Docker vs NGINX
1 Likes142.80 GEEK