Docker is a popular tool for software developers and engineers looking to streamline the process of building, testing, and deploying applications. With its ability to create lightweight, portable containers that can run on any platform, Docker has significantly impacted the way we build and deploy software applications.
One of the many benefits of Docker is that it allows you to easily containerize your applications, which can help to simplify the process of deploying your code to different environments. In this article, we will focus specifically on how to Dockerize a React application.
React is a popular JavaScript library for building user interfaces, while Vite is a modern build tool that enables fast and efficient development.
Prerequisite
To follow along in this tutorial, you will need the following:
Node and npm installed on your machine
A recent version of Docker on your local machine.
A text editor (preferably, VSCode)
Create a React Application
Create a new folder and open it within your text editor. Navigate to your terminal and type in the following command:
Go into the
package.json
file within your application and update thedev
command within the script tag with thisType in the following command to start your development server
How to Dockerize a React Application
Create two files in the root directory named Dockerfile Dockerfile.dev respectively. The difference between these files is that the former is used for a production build while the latter is used for a development build.
Copy the following code into the two Dockerfiles
Create a new file within the root directory and name it
docker-compose.yml
Copy the code below and paste it into the fileNow that we have set up our application. Go to your terminal and type in the following code to build the application
If everything ran successfuly, you should see a message like the one below in your terminal
docker-compose up
[+] Running 1/1
- Container docker-react-client-1 Recreated 1.6s
Attaching to docker-react-client-1
docker-react-client-1 |
docker-react-client-1 | > docker-react@0.0.0 dev
docker-react-client-1 | > vite --port 3000 --host
docker-react-client-1 |
docker-react-client-1 |
docker-react-client-1 | VITE v4.1.4 ready in 4809 ms
docker-react-client-1 |
docker-react-client-1 | Local: http://localhost:3000/
docker-react-client-1 | Network: http://172.19.0.2:3000/
Voila!! You have dockerized your first react application. Now you can go ahead and develop your application and all the changes you make will be automatically picked up by docker whenever you run the docker-compose up
command.
To see your application, go to your browser and type http://localhost:3000/
If you found this helpful, please like, comment and share it. I'd like this article to reach as many people as possible.
The source code can be found here on github. Don't forget to star
Top comments (0)