This article helps you to deploy a React application using docker containers. To know about docker and docker containers refer this article. This involves creating a react app using npx, then we use the docker file to deploy the docker containers using nginx images.
Create a React application
First, we need to create a React application. For this we can use npx
npx create-react-app react-docker-example cd react-docker-example && npm install npm start
Run the app in the localhost at
http://localhost:3000/ or if any cloud such as AWS or Azure VMs with the
3000 port to check the app is running.
First, create a dockerfile in the React app folder with the following lines of dockerfile code.
# build stage FROM node:lts-alpine as build-stage WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build # production stage FROM nginx:stable-alpine as production-stage COPY --from=build-stage /app/dist /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
FROMis the base image in which React app needed to run here. Here we use
node:lts-alpineimage to first build the artifacts for the React app, that it set as
WORKDIRis the dir where the app is build and run.
- Then we copy
package.jsonto the workdir
- Then run
npm installto install dependencies and run
npm run buildto build the dependencies.
- In production-stage we run the react application using
For this we need to copy the files to
nginx/htmlfolder, then we expose the port
Build the docker image
Next step is to build the docker image using the docker file using the following command
docker build -t dockertutorial/react-example .
-t is used for
tag command here we named as react-example and we need to mention the folder here
. used for selecting all. It take some time to build it and shows following result.
Run the container
The last step is to run the container.
docker run command is used to run the container from the image we created as following
$docker run -d -it -p 80:80 --name reactapp dockertutorial/react-example:latest fd2285a0a2e37afc9d0317ce6c668d2c2bf23a71d75a9df8b8d7134c8d223573
-druns the command in detached mode.
-prefers to port which expose container to local system, here it expose port 80 of container to port 80 of local machine.
-itruns in interactive mode with the tag name and
--namerefers to name of the container.
Then go to
http://localhost:80 or if you use cloud VM use the public IP address and select the port
80. It gives the following results
This react application can also be run with multiple containers using docker compose. This will be our next article.
If any suggestion and queries please comment it, so I can improve my self.
1,057 total views