What is Docker?
Docker is a containerization platform that allows you to package an application and its dependencies in an isolated container. A container is a standardized unit that contains everything an application needs to run, including code, runtime, libraries, and environment variables. This approach helps ensure that the application runs consistently across any environment in which it runs, regardless of differences between operating systems or configurations.
Create a React app
To get started, let's make sure we have Node.js and npm (Node Package Manager) installed on our system. We then create a new React project using the following command:
npx create-react-app my-react-app
This command creates a basic structure for a React application in the
Create a Dockerfile
A Dockerfile is a text document that contains instructions for building a Docker image. Let's create a file called
Dockerfile in the root of our React project and add the following statements:
# Use an official Node.js image as a base FROM node:20 # Set the working directory in the app WORKDIR /usr/src/app # Copy the package.json and package-lock.json files to your working directory COPY package*.json ./ # Install dependencies RUN npm install # Copy all files to working directory COPY . . # Expose port 3000 EXPOSE 3000 # Start the React application CMD ["npm", "start"]
This Dockerfile uses an official Node.js image as a base and sets up the environment to run a React app.
Create a .dockerignore file
Let's create a file called
.dockerignore in the same directory as our Dockerfile. This file is similar to .gitignore and specifies which files or folders should be excluded when copying files to the Docker image. An example of
.dockerignore would be:
Building and Running the Docker Image
Now that we have our Dockerfile configured, we can build the Docker image by running the following command in the project directory:
docker build -t my-react-app .
This command creates a Docker image called "my-react-app" using the instructions in the Dockerfile.
After building the image, we can run a container based on it:
docker run -p 3000:3000 my-react-app
This command launches a container based on the "my-react-app" image and maps port 3000 of the container to port 3000 of our local system. Now we can open a browser and access the React app at http://localhost:3000.
Using Docker with React simplifies the deployment of applications, ensuring they run consistently across different environments. This approach is particularly useful when working in a team or when you want to deploy the application on different platforms without having to worry about configuration differences.
In this article, we created a Dockerfile for a React app and saw how to build and run a Docker image to containerize the application. Docker offers many other advanced features, but this is a great starting point for integrating Docker into your React development workflow.