How to Dockerize React App in few easy steps

ยท

2 min read

How to Dockerize React App in few easy steps

Before, Starting this article I'm assuming that you have already installed Docker on your machine and it is running successfully.

Create a New React Project

First, you have to create a new react application at any where you want on your machine with the following command

create-react-app project-name

This will successfully create your react application at your defined destination.

Now you have to create two new files named Dockerfile and .dockerignore at the root folder of your project.

tempsnip.png

Make sure to name the files correctly, If you are using VS-code then it should show the docker icon before your file name as in the above image.

After that, you have to add a few lines of code in both newly created files. In your Dockerfile add these few lines of code

FROM node:13.12.0-alpine
# set working directory
WORKDIR /app
# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH
# install app dependencies
COPY package.json ./
COPY package-lock.json ./
RUN npm install --silent
RUN npm install react-scripts@5.0.0 -g --silent
# add app
COPY . ./
# start app
CMD ["npm", "start"]

Above lines starting with # are indicating the comments about what their below lines do. Also, make sure your react-scripts version is same as the react-scripts version in your package.json file.

And in your .dockerignore file add following lines of code

node_modules
build
.dockerignore
Dockerfile
Dockerfile.prod

After that, start your new terminal from VS-code and run the following command to create the image of your react-app in a docker container

docker build -t containername:tag

You can replace the **containername **and **tag ** name as you want.

This will take few seconds and will successfully build your react-app image in a docker container

docker.PNG

To make sure, you may go to the Docker desktop application and should see your image in the images section below

dockerimage.png

Finally, you have to run the container you just created with the following command

docker run -it -p 3000:3000 containername:tag

Make sure to replace the **containername ** and **tag ** names if you have changed that while building the container. Now go to the Docker desktop application Containers/App section and you should see the container of your react application. Click on the first right side option of OPEN IN BROWSER and here we go your react app is now dockerized and running successfully ๐ŸŽ‰

Capture.PNG

See you again soon with the new article. Cheers ๐Ÿฅ‚

ย