Search code examples
reactjsdockerdeploymentcreate-react-app

Building Create React App for production in Docker Container


I am having a problem with creating a docker image for my CRA application. Here is my Dockerfile that I use for the production environment:

# base image
FROM node:10.13.0
# set working directory
WORKDIR /usr/src/app

# install and cache app dependencies
COPY package.json yarn.lock ./
RUN yarn

COPY . ./
# RUN yarn cache clean 
RUN yarn build

# Stage 2 - the production environment
FROM nginx:latest
# COPY build /usr/share/nginx/html
COPY ./build /var/www
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

The docker build process runs successfully up to the 8th step where it returns the following error: Step 8/11 : COPY ./build /var/www lstat build: no such file or directory

From my understanding the error tells me that the build folder was not created after all, therefore it cannot be moved.


Solution

  • This Dockerfile uses multi-stage build. 8th step - COPY ./build /var/www fails because, it is trying to copy build directory from nginx image (2nd stage, and not from the 1st stage where yarn build is run) to /var/www, which doesn't exist.

    To get it working, specify that build directory should be copied from the first stage (where yarn build is run). For this, make the following changes:

    1. Name the base stage by changing the 1st line to FROM node:10.13.0 AS base (can use any name instead of base here).
    2. Change COPY ./build /var/www to COPY --from=base ./build /var/www to say that we want to copy build directory from 1st stage and not from the 2nd stage.