Make your app more awesome. 😎😎😎
Docker is an open-source containerization platform. Docker enables developers to package applications into containers — standardized executable components that combine application source code with all the operating system (OS) libraries and dependencies required to run the code in any environment.
To make your react app ready for hosting, we must dockerize it.
To proceed, you must have some basic knowledge of docker and docker-compose
Don't worry if you do not know much about docker; follow me for my next article for docker basics to advance. 😉
Let the fun begin. 🥳🥳🥳
Steps to dockerize your React app:
Our react app need two images one is a node for compiling and building, and the other is nginx for running our HTML
The working directory in a node is /app, and for nginx, it is /usr/share/nginx/html
- Use the alpine stable version of node and nginx.
- Name the node image container as build so that after we build it, we can refer to build and copy the files from there.
- Copy package.json and package-lock.json to install the package instead so copying from the working directory in your local computer.
- After installing packages, copy the files from the local computer to the container.
- Install react scripts and run npm build
- Use an nginx image, copy the build folder from build to /usr/share/nginx/html
- Since our application uses a react-router if it has nested and deep routes, it creates an issue in nginx.
- Create an nginx.config file and copy it to /etc/nginx/conf.d/default.conf
9. Expose port 80
10. To run nginx within the container without halting, we should use
daemon off configuration directive described in official docs.
Finally, create a docker image from the docker file using the following commands:
docker image build -t <username>/<image-name> .docker push <username>/<image-name>
To test it before pushing, use :
docker container run -d -p 8080:80 <username>/<image-name>
I highly recommend to use eslint vs-code extension while developing because even if there is a simple error your page won’t show up and it will be very difficult to know if it's a problem with dockerizing or application code.
One can use docker-compose also for speeding up the testing and building. image simultaneously in a better way
Create a docker-compose.yml file and run the following commands:
If you have come this far, you definitely liked the article. Please do consider applauding the article and following me for more such articles.
I have written an article on making your react app ready for hosting by making it a progressive web app, server-side rendering, dockerizing, and deploying in AWS using Terraform.