DEV Community

Cover image for How to deploy a react application with docker in 6 steps
Nelson Hernández
Nelson Hernández

Posted on

How to deploy a react application with docker in 6 steps

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"]
Enter fullscreen mode Exit fullscreen mode

2. DockerFile of Backend

FROM node:14

WORKDIR /app

COPY . /app

RUN npm install

EXPOSE 8000

CMD [ "npm", "run", "serve" ]
Enter fullscreen mode Exit fullscreen mode

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}`);
});
Enter fullscreen mode Exit fullscreen mode

4. Create file DockerFile of Nginx

FROM nginx:latest

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

EXPOSE 80
Enter fullscreen mode Exit fullscreen mode

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;
        }
    } 
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Code of example in Github 🔗

Top comments (0)