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 headaches 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.
    npm i -g create-react-app@latest
  2. Create a new React app.
    npm create-react-app dockerized-react-app
    cd dockerized-react-app
    npm start
  3. In the dockerized-react-app folder create a file named Dockerfile
    touch Dockerfile
  4. In the Dockerfile, add the following code
    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 dynamically generated files and dependencies.

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

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

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

  6. Once the build is complete:
    docker run -p 5002:5002 cra-docker:v1
  7. Now, open your browser on https://localhost:5002 to browse the 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 devstaging, and production via the docker build step. You can omit it or replace the variable altogether with something else.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.