Client and Server Hot Reloading with React and Docker
This guide is intended for projects that require an Express web server that serves a React client application and will be deployed in a Docker container.
For projects that only require a stand alone React client app, this guide is superfluous and the create-react-app started guide² should be followed.
1. Install the bootstrapping tools
Both Express and React provide bootstrapping tools to help kickstart a project. These tools provide much of the boiler plate required during set up.
npm install --global express-generator create-react-app
yarn global add express-generator create-react-app
2. Create an Express app
Use the Express bootstrap tool to create the Express server. This tool assumes you will be using Express to render the UI using a templating engine so that section of the app can be removed before replacing it with React.
# Remove the files that will be replaced by React
rm -rf public/ views/
# Install all of the dependancies
3. Create a React app
Like the Express app, the bootstrapping tools can be used to create the React application.
4. Create the docker images
Create a Dockerfile and copy the following gist.
5. Create the docker-compose.yml
When building the containers locally, mount the development folders as read-only volumes to allow react-scripts/nodemon to detect code changes.
6. Install hot reloading package
To enable hot reloading of the server, install
nodemon to the dev dependancies.
npm install --save-dev nodemon
7. Add the start npm commands
Before the app can be built locally, npm needs a start command for the client and server. Add these commands to your package.json
"start:client": "(cd client && npm start)",
"start:server": "nodemon ./bin/www",
Finally, proxy the requests from the React application to the Express server. To do this, add the following to your package.json
8. Build it
To build the docker containers, run
docker-compose up --build and your new application will be available at http://localhost:3000