How to Dockerize the Create React App

Docker is pretty cool.

Bundling all your app environment in a single file is just awesome.

It saves you a lot of headache when dealing with dependencies/setup and other environment issues when creating a stable build system for your production app.

In this tutorial, we will dockerize a React app built with the famous create-react-app package using Docker.

Setup

  1. Install create-react-app globally.
create-react-appcreate-react-app
1
npm i -g [email protected]
  1. Create a new React app
create-react-appcreate-react-app
1
2
3
npm create-react-app dockerized-react-app
cd dockerized-react-app
npm start
  1. In the dockerized-react-app folder create a file named Dockerfile
1
touch Dockerfile
  1. In the Dockerfile, add the following code
Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
FROM mhart/alpine-node:11 AS builder

ARG REACT_APP_ENV
ENV REACT_APP_ENV=\${REACT_APP_ENV}

WORKDIR /app
COPY . .
RUN npm install react-scripts -g
RUN npm install
RUN NODE_ENV=production REACT_APP_ENV=\$REACT_APP_ENV npm run build

FROM mhart/alpine-node
RUN npm install serve -g --silent
WORKDIR /app
COPY --from=builder /app/build .
EXPOSE 5002
CMD ["serve", "-p", "5002", "-s", "."]doc

I’d recommend you to add a .dockerignore file in your root directory. This will speed up the docker build process by ignoring a dynamically generated files and dependencies.

.dockerignore
1
node_modules
  1. Create a docker image locally using the command
1
docker build --tag cra-docker:v1 . --build-arg REACT_APP_ENV="dev"

The --build-arg is just to send an arg during the buld process.

This command will build the docker image on your PC. Just make sure that docker is installed and running in the background.

  1. Once the build is complete,
1
docker run -p 5002:5002 cra-docker:v1

Now, open your browser on https://localhost:5002 to browse your react app from the Docker app instance.

Notes

Don’t use --silent in npm install

In some guides on Docker and npm, you will see people using the --silent command in the Dockerfile. But, I suggest you to not use it. The --silent option in npm install swallows all the warnings and errors while installing the dependencies.

If there is an issue in your app due to any external/internal dependency, you will waste quite a lot of your precious time in finding the problem.

npm ERR! missing script: start

Check your package.json file. It should have a “scripts” property with “start” child.

[Warning] One or more build-args [REACT_APP_ENV] were not consumed

The environment variable REACT_APP_ENV is just for your convenience to set a build environment like dev, staging, and production via the docker build step. You can ommit it or replace the variable altogether with something else.