Step 1: Create a ReactJS Application Set Up the React Application: Ensure you have Node.js and npm (Node Package Manager) installed on you...
Step 1: Create a ReactJS Application
Set Up the React Application:
Ensure you have Node.js and npm (Node Package Manager) installed on your machine. You can verify this by running:
node -v npm -v
If not installed, you can download and install Node.js from nodejs.org.
Create a New React Application:
Use the
create-react-app
tool to set up a new React project. Open a terminal and run:npx create-react-app my-react-appThis will create a new directory named
my-react-app
with a basic React application template.Navigate to the Application Directory:
cd my-react-appTest the Application:
To make sure everything is working, you can start the development server:
npm startOpen your browser and go to
http://localhost:3000
to see the default React application.
Step 2: Create a Dockerfile
Create a Dockerfile:
In the root of your React application directory (
my-react-app
), create a file namedDockerfile
with the following content:# Step 1: Build the React applicationFROM node:18 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 code COPY . . # Build the application RUN npm run build # Step 2: Serve the React application FROM nginx:alpine # Copy the build output to the Nginx server's root directory COPY --from=build /app/build /usr/share/nginx/html # Expose port 80 EXPOSE 80 # Start Nginx server CMD ["nginx", "-g", "daemon off;"]
This Dockerfile does two main things:
- Build Stage: Uses a Node.js image to build the React application.
- Serve Stage: Uses an Nginx image to serve the built React application.
Step 3: Build and Run the Docker Container
Build the Docker Image:
In the root directory of your project (where the Dockerfile is located), run the following command to build the Docker image:
docker build -t my-react-app .This command builds the Docker image and tags it as
my-react-app
.Run the Docker Container:
After building the image, you can run it in a container with:
shdocker run -p 8080:80 my-react-app
This command maps port 80 in the container to port 8080 on your host machine.
Access the Application:
Open your browser and go to
http://localhost:8080
to see your React application running inside the Docker container.
COMMENTS