In this tutorial, I am going to explain the simple and easy steps to run a React App in a docker container.
First you need to create an empty react application by following this create-react-app steps. Once you have created the sample react app, the follow the below steps:
npm install create-react-app --global
)create-react-app react-docker-app
)react-docker-app
folder and run it, to make sure all is good. (cd react-docker-app && yarn start
)That’s all. Now jump to create a Dockerfile
file on root directory of your project. Below is the sample code for Dockerfile
.
1 2 3 4 5 6 7 8 9 10 | FROM mhart/alpine-node:11 AS builder WORKDIR /app COPY . . RUN yarn run build FROM mhart/alpine-node RUN yarn global add serve WORKDIR /app COPY --from=builder /app/build . CMD ["serve", "-p", "80", "-s", "."] |
Now build the image, you can run the following command from the project root folder, where your Docker-file
is:
1 2 3 4 | docker build -t react-docker-app. #You will get below output: Successfully tagged react-docker-app:latest |
Finally, run this container now. To run it locally, you need to provide the name of the image and the port we want the React app to be accessible on. Note that we used port 80
in the serve command, so need to make sure to use 80
when specifying the container port like this:
1 | docker run -it -p 8080:80 react-docker-app |
Now you can access you react application using http://localhost:8080
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: create-react-app docker production, docker container for react app, react-docker, reacts