How to deploy a react application with docker in 6 steps

Deploy react app with docker

1. DockerFile of Frontend

if your environment variable is for example
http://localhost:8000/api put only /api

FROM node:14

WORKDIR /app

COPY . /app

ENV REACT_APP_REST=/api

RUN npm install

RUN npm i -g serve

RUN npm run build

EXPOSE 5000

CMD ["serve", "-s", "build"]

2. DockerFile of Backend

FROM node:14

WORKDIR /app

COPY . /app

RUN npm install

EXPOSE 8000

CMD [ "npm", "run", "serve" ]

3. Endpoint of Backend with Express JS

The endpoint begins with /api as we had defined it in the Frontend

const express = require("express");
const app = express();
const games = require("./api");
const cors = require("cors");

app.use(cors());
app.use(express.json());

app.get("/api/games", ({res}) => {
res.status(200).json(games);
});

const port = 8000;

app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

4. Create file DockerFile of Nginx

FROM nginx:latest

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

EXPOSE 80

5. Create Nginx conf

events {
worker_connections 768;
# multi_accept on;
}

http {
server {
listen 80 default_server;
listen [::]:80 default_server;

root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri /index.html =404;

location / {
proxy_pass http://frontendreact:5000;
}

location /api {
proxy_pass http://backendnode:8000;
}
}
}

6. Docker Compose

version: "3.9"
services:
backendnode:
build: ./backendnode
expose:
- "8000"
volumes:
- ./backendnode:/usr/src/app
frontendreact:
build: ./frontend
expose:
- "5000"
volumes:
- ./frontend:/usr/src/app
nginx:
build: ./nginx
ports:
- "80:80"
links:
- frontendreact
- backendnode
restart: always

Code of example in Github 🔗

Frontend Developer and Content Creator from El Salvador

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Integration of WordPress with AWS RDS.

Event-driven digital object architecture for natural science collection

Crust and Darwinia Announce Partnership to further strengthen the Polkadot Ecosystem

Google Kubernetes Engine: default deployment security problems

TryHackMe Fowsniff 1 room walkthrough

The Best Cad Software For Mac

5 Programming Languages You Can Learn in 10 Minutes-ish

An hourglass

How to prepare for and succeed at a coding boot camp?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nelson Hernández

Nelson Hernández

Frontend Developer and Content Creator from El Salvador

More from Medium

Brief intro on various API Specifications REST, SOAP, GraphQL and GRPC

Relational Database working in 5 minutes

Spring Data and Redis Keys

Installing Apache APISIX on Windows