DEV Community

Zeshan
Zeshan

Posted on

How to Dockerize a React Application

Docker helps us package applications and their dependencies into containers, ensuring they run consistently on any system.

Image description

This guide will show you how to dockerize a React application, making it easy to deploy on Windows, Linux, or macOS.

What You'll Need

Before you start, make sure you have:

Step 1: Set Up Your React Application

First, let's create a simple React app using Create React App.

  1. Create a new React project:

    npx create-react-app my-react-app
    cd my-react-app
    
  2. Start the development server to test the app:

    npm start
    

    Open your browser and go to http://localhost:3000. You should see the default Create React App welcome screen.

Step 2: Create a Dockerfile

A Dockerfile tells Docker how to build your application. Create a file named Dockerfile in your project folder and add the following:

# Use an official Node.js image as the base
FROM node:14 AS build

# Set the working directory
WORKDIR /app

# Copy package.json and package-lock.json
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application
COPY . .

# Build the app
RUN npm run build

# Use an official nginx image to serve the build
FROM nginx:alpine

# Copy the build output to the nginx html directory
COPY --from=build /app/build /usr/share/nginx/html

# Expose port 80
EXPOSE 80

# Start nginx
CMD ["nginx", "-g", "daemon off;"]
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Docker Ignore File

To ensure Docker doesn't copy unnecessary files, create a .dockerignore file in your project folder and add the following:

node_modules
build
.dockerignore
Dockerfile
Enter fullscreen mode Exit fullscreen mode

Step 4: Build Your Docker Image

Open your terminal, make sure you're in the project folder, and run:

docker build -t my-react-app .
Enter fullscreen mode Exit fullscreen mode

This command tells Docker to build an image named my-react-app using the instructions in the Dockerfile.

Step 5: Run Your Docker Container

Now, let's run our container:

docker run -p 80:80 my-react-app
Enter fullscreen mode Exit fullscreen mode

This command tells Docker to run the my-react-app image and map port 80 on your machine to port 80 in the container.

Step 6: Access Your Application

Open your browser and go to http://localhost. You should see your React app running, but this time it's served by an Nginx server inside a Docker container.

Conclusion

You’ve successfully dockerized your React application! This setup ensures your app will run the same way on any machine with Docker installed, making it easier to share and deploy.

Dockerizing applications might seem daunting at first, but it greatly simplifies deployment and ensures consistency across environments.
Happy coding!

Top comments (0)