Hot Reload in ReactJS with Docker



Hot-Reloading is adding dynamic functionality to the react application on the web browser. This means if we change something in the code of the application it immediately reflects this change on the web application front. But before "reloading" anything we must know "loading", that is to make some ReactJs project on the Node Docker container.

Creation and Containerization of React App

Step 1: React app

Use the prebuild commands to create a basic react application.

Example

$npx create-react-app reactapp

Output

npx: installed 67 in 19.076s

Creating a new React app in /home/hemant/project/reactapp.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...


> core-js@3.26.1 postinstall /home/hemant/project/test/reactapp/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

> core-js-pure@3.26.1 postinstall /home/hemant/project/test/reactapp/node_modules/core-js-pure
> node -e "try{require('./postinstall')}catch(e){}"

+ cra-template@1.2.0
+ react-scripts@5.0.1
+ react@18.2.0
+ react-dom@18.2.0
added 1407 packages from 624 contributors in 233.937s

213 packages are looking for funding
  run `npm fund` for details


Initialized a git repository.

Installing template dependencies using npm...
npm WARN @apideck/better-ajv-errors@0.3.6 requires a peer of ajv@>=8 but none is installed. You must install peer dependencies yourself.
npm WARN fork-ts-checker-webpack-plugin@6.5.2 requires a peer of typescript@>= 2.7 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ @testing-library/jest-dom@5.16.5
+ @testing-library/react@13.4.0
+ @testing-library/user-event@13.5.0
+ web-vitals@2.1.4
added 72 packages from 89 contributors in 21.128s

226 packages are looking for funding
  run `npm fund` for details

Removing template package using npm...

npm WARN @apideck/better-ajv-errors@0.3.6 requires a peer of ajv@>=8 but none is installed. You must install peer dependencies yourself.
npm WARN fork-ts-checker-webpack-plugin@6.5.2 requires a peer of typescript@>= 2.7 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

removed 1 package and audited 1479 packages in 9.798s

226 packages are looking for funding
  run `npm fund` for details

found 1 high severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details
Git commit not created Error: Command failed: git commit -m "Initialize project using Create React App"
   at checkExecSyncError (child_process.js:790:11)
   at execSync (child_process.js:863:15)
   at tryGitCommit (/home/hemant/project/test/reactapp/node_modules/react-scripts/scripts/init.js:62:5)
   at module.exports (/home/hemant/project/test/reactapp/node_modules/react-scripts/scripts/init.js:350:25)
   at [eval]:3:14
   at Script.runInThisContext (vm.js:134:12)
   at Object.runInThisContext (vm.js:310:38)
   at internal/process/execution.js:81:19
   at [eval]-wrapper:6:22
   at evalScript (internal/process/execution.js:80:60) {
  status: 128,
  signal: null,
  output: [ null, null, null ],
  pid: 8786,
  stdout: null,
  stderr: null
}
Removing .git directory...

Success! Created reactapp at /home/hemant/project/reactapp
Inside that directory, you can run several commands:

  npm start
   Starts the development server.

  npm run build
   Bundles the app into static files for production.

  npm test
   Starts the test runner.

  npm run eject
   Removes this tool and copies build dependencies, configuration files
   and scripts into the app directory. If you do this, you can't go back!

We suggest that you begin by typing:

  cd reactapp
  npm start

Happy hacking!

A new folder "reactapp" will be created after the execution of the above command. This has all the required files for the react web application to work. We can also run this application on the host platform but our need is to run this application on the Docker container and provide it the functionality of hot reloading.

Step 2: Dockerfile

Now create a dockerfile for this react application.

Example

#Here we will use node as the base image. FROM node:14.21.1-alpine #create a working directory inside the container. WORKDIR /app #Environment variables. ENV PATH /app/node_modules/.bin:$PATH #copy the files from the host to the container. COPY package.json ./ COPY package-lock.json ./ #install npm and react versions. RUN npm install --silent RUN npm install react-scripts@5.0.1 -g --silent #install nodemon to provide hot-reloading functionality. RUN npm install nodemon --save-dev COPY . ./ #use nodemon to run the react application using npm. CMD ["nodemon", "--exec", "npm", "start"]

Step 3: Create Dockerignore

By creating a .dockerignore file we will ignore some non-required files from copying to the container.

Example

node_modules build .dockerignore Dockerfile Dockerfile.prod

Step 4: Build an Image

Now all the prerequisites are completed, we just have to create the image for this react application and then run it on the container to test.

Example

$docker build -t react_img .

Output

Sending build context to Docker daemon  587.3kB
Step 1/10 : FROM node:14.21.1-alpine
 ---> 87112681acad
Step 2/10 : WORKDIR /app
 ---> Using cache
 ---> 0b207dfe1b40
Step 3/10 : ENV PATH /app/node_modules/.bin:$PATH
 ---> Using cache
 ---> 8a6c9d9d6d96
Step 4/10 : COPY package.json ./
 ---> Using cache
 ---> 97342fa619fa
Step 5/10 : COPY package-lock.json ./
 ---> Using cache
 ---> 8c04867af3e6
Step 6/10 : RUN npm install --silent
 ---> Using cache
 ---> 0ab355131c9e
Step 7/10 : RUN npm install react-scripts@5.0.1 -g --silent
 ---> Using cache
 ---> 1698f24cd34c
Step 8/10 : RUN npm install nodemon --save-dev
 ---> Using cache
 ---> 8b2ed3bc8422
Step 9/10 : COPY . ./
 ---> Using cache
 ---> f69b093c6605
Step 10/10 : CMD ["nodemon", "--exec", "npm", "start"]
 ---> Using cache
 ---> 13071aaea8eb
Successfully built 13071aaea8eb
Successfully tagged react_img:latest

Step 5: Create Container

Here we have to create the docker container for the above-created image "react_img". Also during containerization, we need to publish the port numbers from host to container.

Example

$docker run -it --name react_container_app -p 3000:3000 react_img

Output

[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `npm start`

> reactapp@0.1.0 start /app
> react-scripts start

Compiled successfully!
You can now view reactapp in the browser.

   Local:            http://localhost:3000
   On Your Network:  http://172.17.0.2:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully

Check the server on the "localhost:3000", the app is working fine.

Hot-Reload the application server

There are two ways to hot reload the react application, one is changing code inside the docker container and the other is changing code outside the container.

From Inside the Container

First, jump inside the container using the exec command

$docker exec -it react_container_app sh

Now change the directory to app/src/ and change the code inside App.js and see if any changes in the web application are seen or not. Change the text to "THIS IS TUTORIALSPOINT REACT APPLICATION."

Example

$cd src/ $vi App.js

Output

import logo from './logo.svg';
import './App.css';

function App() {
   return (
      <div className="App">
      <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <p>
         THIS IS TUTORIALSPOINT REACT APPLICATION.
      </p>
      <a
         className="App-link"
         href="https://reactjs.org"
         target="_blank"
         rel="noopener noreferrer"
      >
         Learn React
      </a>
      </header>
   </div>
  );
}

export default App;
~
~
~
~

Now check if changes occurred.

Hence the react application is responding to any live changes in the code.

From Outside the Container

For this task to get executed you need to create a new container and bind that container to the volume or application directory, This will allow the container to detect any kind of changes in the code on the host machine as well.

Create the container.

Example

$docker run -it \ --name new_react_container \ --volume ./reactapp/:/app/ \ -p 3000:3000 react_img

Check if the server is running.

Change the code now at the host directory and see the changes.

Example

$cd /reactapp/src $vi App.js

Output

import logo from './logo.svg';
import './App.css';

function App() {
   return (
      <div className="App">
      <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <p>
         CHANGES FROM OUTSIDE THE CONTAINER.
      </p>
      <a
         className="App-link"
         href="https://reactjs.org"
         target="_blank"
         rel="noopener noreferrer"
      >
         Learn React
      </a>
      </header>
   </div>
   );
}

export default App;
~
~
~
~

Check if the changes occurred on the web application.

These were some of the ways you can hot reload a react container during any new updates in the application.

Updated on: 2022-12-28T11:17:20+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements