In this blog post we will show step by step how to dockerize a React application created using Vite.

Create a React app

  1. Run the command npm create vite@latest.

  2. For Project name type: myApp and press enter.

  3. Choose React from the menu.

  4. From the menu you can choose either Typescript or Javascript.

  5. Change in to your project’s directory and run the command npm install.

Edit package.json.

  1. Edit the package.json file and in the scripts section add the following command: "exposed-port": "vite --host".

  2. Save and exit.

Create Dockerfile

  1. In your project’s root directory create the Dockerfile by typing: touch Dockerfile.

  2. Open your Dockerfile in your favourite editor and type the following:

# The version of Node that we will use
FROM node:22-alpine3.20

# The working directory of the app in the container
WORKDIR /react-app

# Install the packages in package.json
RUN npm install

# Copy the project files from the host to the work directory in the container
COPY . /react-app/

# Expose the port in the container so that it can be accessed from the outside
EXPOSE 5174

# Command to run the app
CMD ["npm", "run", "exposed-port"]
  1. Save and exit.

Create .dockerignore file

  1. In the root directory of your project create a .dockerignore file: touch .dockerignore.

  2. Open the .dockerignore file in your favourite editor and add the following:

node_modules
npm-debug.log
build
.git
*.md
.gitignore

We want to exclude these directories and files because they are not needed in our container and therefore, we do not wish to copy them. With regards to the node_modules directory we want to install the packages in the container instead of copying them over since the folder tends to be huge and will take a long time to copy over from the host to the container.

  1. Save and exit.

Create a Docker compose file for hot reloading

  1. Create a docker-compose.yml file in the root directory of your project.

  2. In your favourite editor, add the following lines to the docker-compose.yml file:

version: "1.0"
services:
  react-app:
    image: my-react-app
    stdin_open: true
    ports:
      - "5174:5174"
    environment:
      - CHOKIDAR_USEPOLLING=true
      - CHOKIDAR INTERVAL=500 # Decrease CPU usage by checking every 500ms
    volumes:
      - "./react-app:delegated"
      - /react-app/node_modules/
  1. Save and exit.

Build the Docker container

  1. At the command prompt type the following command: docker build -t my-react-app ..

Enable hot reloading in the docker container

  1. In order to run the Docker container with hot reload we type the following command in our project’s root directory: docker run -i -v .:/react-app:delegated -v /react-app/node_modules -p 5174:5174 my-react-app.

You should now have your React app running with hot reload enabled.