Learn about Dockerize a React App

In this article, I'm going to show how to deploy the react application into the docker container. Let's jump into it.

Prerequisites

Step 1. Create a React app. If you don't have one.

Make sure you have installed the Node and then Open the Command Prompt, then enter the below command

npx create-react-app <my-react-app>

Replace my-react-app with any name you wish and then open it with VS code or any editor.

 VS code

Step 2. Create a docker ignore file

This file allows us to specify the files and directories to be excluded when building a Docker image. Create a .dockerignore file on the root directory of our project. Then, type the /node_modules inside the dockerignore to ignore the folder while building.

Docker ignore file

Step 3. Create a Docker image

The docker file holds the instructions for building your docker image. Create a file named docker file and copy and paste the below instructions.

FROM node:14.17.0-alpine as build

WORKDIR /app

COPY package.json package-lock.json ./

RUN npm install

COPY . .

RUN npm run build

FROM nginx:1.21.4-alpine

COPY --from=build /app/build /usr/share/nginx/html

EXPOSE 80

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

The Dockerfile uses a two-stage build process.

  • The first stage (builder) is based on the node: alpine image and is used to install dependencies for your React app.
  • The second stage (nginx: alpine) is a lightweight Nginx image used to serve the built React app.
  • The file copies the necessary files and runs commands to build and serve the app.

Step 4. Build the Docker image

Go to the terminal in vs code and then run the below command to build a docker image

docker image build -t my-react-app:latest .

Replace the my-react app with your react app name.

 Docker image

If you open the Docker desktop, you can able to see our image.

 Docker desktop

Step 5. Run the Container

Use the below command to run the docker image on the container

docker container run -p 80:80 --name my-react-app my-react-app:latest

Replace the my-react app with your app name.

Container

Finally, navigate to the http:localhost:80 to see if the application is running on the container.

Navigate

I hope you learned how to deploy the React app in the Docker container. Let me know if you are facing issues while following the steps!