This guide walks you through the process of dockerizing a basic react application.
# Set base image to create the React application image
FROM node:20-alpine
# Create a user with permission to run the app
# -S creates a system user, -G adds the user to a group
# This step avoids running the app as root
RUN addgroup app && adduser -S -G app app
# Set the user to run the app
USER app
# Set working directory
WORKDIR /app
# Copy package.json and package-lock.json to the working directory
# This helps leverage Docker's cache, so dependencies won't be reinstalled if they haven't changed
COPY package*.json ./
# Sometimes the ownership of the files changes to root
# This can cause errors like EACCESS: permission denied
# We change the ownership to the app user to avoid these issues
USER root
# Change ownership of the /app directory to the app user
RUN chown -R app:app .
# Switch back to the app user
USER app
# Install dependencies
RUN npm install
# Copy the rest of the application files to the working directory
COPY . .
# Expose port 5173 for the React development server
EXPOSE 5173
# Command to run the React app
CMD ["npm", "run", "dev"]When you run the React Docker image, you won’t be able to access it through localhost because Docker operates in an isolated environment. To make the application accessible from the host machine, you need to map the port properly.
Run the following command to map the container’s port 5173 to the host machine’s port 5173:
docker run -p 5173:5173 react-dockerEven after this, you might not be able to access your app. This is because Docker uses isolated networking. To make the application publicly accessible, you’ll need to update the dev command in your package.json to allow external access.
Update the dev command to:
"dev": "vite --host"This change allows the React app to be accessible from the localhost URL.
If you make changes to your application (e.g., editing a div in the React app), you'll need to rebuild the Docker image to reflect the changes. This requires running the docker build command, creating a new image, and running the image again.
However, to avoid this step and reflect changes in real-time, you can mount your local directory to the Docker container. This way, the Docker container will directly use the files you are working on without rebuilding the image.
Run the following command:
docker run -p 5173:5713 -v "$(pwd):/app" -v /app/node_modules react-docker-v "$(pwd):/app": Mounts your current working directory to the/appdirectory inside the Docker container. Any changes you make locally will be immediately reflected in the container.-v /app/node_modules: Ensures that the container uses the dependencies specified in the Docker image’spackage.json. This avoids the need to rebuild the image or re-run it when dependencies are updated.
This setup enables you to work with your React application inside Docker, while reflecting changes in real-time without needing to rebuild the Docker image each time.