Home > Blockchain >  Dockerizing react for production not working
Dockerizing react for production not working

Time:07-26

I have created a Dockerfile and Docker-compose.yml for containerzing my create-react-app to production. My problem of understanding is how should I create the production build if the scripts that are needed to run the command are dev-dependencies? Also I can`t find anything on deployment docs.

 > [builder 7/7] RUN yarn build:
#13 0.507 yarn run v1.22.19
#13 0.556 $ react-scripts build
#13 0.579 /bin/sh: react-scripts: not found
#13 0.590 error Command failed with exit code 127.
#13 0.590 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
------
executor failed running [/bin/sh -c yarn build]: exit code: 127
ERROR: Service 'app' failed to build : Build failed
`docker-compose` process finished with exit code 1

package.json

{
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-i18next": "^11.17.2",
    "react-router-dom": "^6.3.0",
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",   <--- THIS WILL BE USED FOR PRODUCTION
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "react-scripts": "5.0.1",   <--- THIS WILL NOT BE INSTALLED WITH --production FLAG
    "tailwindcss": "^3.0.24",
    "typescript": "^4.6.3"
  }
}

Dockerfile

FROM node:18-alpine AS builder
ENV NODE_ENV production

# Add a work directory
WORKDIR /app

# Cache and Install dependencies
COPY package.json .
COPY yarn.lock .
RUN yarn install --production   <---- THIS DOES NOT INSTALL DEV DEPENENCIES

# Copy app files
COPY . .

# Build the app
RUN yarn build     <---- THIS CAUSES THE CRASHING

# ---------------------------------------------------

# Bundle static assets with nginx
FROM nginx:1.23.1-alpine AS production
ENV NODE_ENV production

# Copy built assets from builder
COPY --from=builder /app/build /usr/share/nginx/html

# Add your nginx.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Expose port
EXPOSE 80

# Start nginx
CMD ["nginx", "-g", "daemon off;"]

docker-compose.yml

version: "3.8"

services:
  app:
    container_name: my_app
    build:
      context: .
      target: production
      dockerfile: Dockerfile

CodePudding user response:

In the final image stage, you're only COPY --from=builder the /app/build directory but not any of the node_modules tree. It doesn't matter in the initial stage if you have development or production dependencies, since they're not going to be in the final image.

Since you do need the devDependencies at this point, I'd remove the yarn install --production option. If it makes a difference to your build environment you can set NODE_ENV=production after you install the dependencies.

RUN yarn install # not --production
COPY . .
# ENV NODE_ENV=production
RUN yarn build
  • Related