NelsonCode

How to deploy a react application with docker in 6 steps

Deploy react app with docker
Deploy react app with docker

1. DockerFile of Frontend

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

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

Frontend Developer and Content Creator from El Salvador