Build a NextJS Project running into docker and its taking long time to run

Hi All, this is my first post here. If this is not the correct place for this topic, move it please.

I have a very project in NextJS (frontend) when yarn build is run its taking too much time and my image size is around 2 gb i want to reduce this build size also my docker install dependencies each time if i not made any changes into the it takes around 50 mintes to complete so please suggest how i can optimize my docker file.

below is my docker file

# Stage 1: Build
FROM node:20-alpine AS builder


# Install dependencies
# Install dependencies
RUN apk add --no-cache build-base cairo-dev pango-dev jpeg-dev giflib-dev librsvg-dev




WORKDIR /app


# Copy package.json and install dependencies
COPY package.json .npmrc ./
ENV NODE_OPTIONS="--max-old-space-size=8192"
RUN yarn install --frozen-lockfile --test --verbose


# Build the project
COPY . .
RUN yarn build


# Stage 2: Runtime
FROM node:20-alpine AS runner


# Install runtime dependencies required by the canvas library
# Install runtime dependencies required by the canvas library
RUN apk add --no-cache cairo pango jpeg giflib librsvg




WORKDIR /app
ENV NODE_ENV=test


# Copy necessary files from the build stage
COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/webpack.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json


# Ensure shared libraries are in the correct path
# RUN ldconfig


EXPOSE 3000
CMD ["npm", "start"]

I edited your post. Please, click on the pencil icon in the top right corner of your post to see the changes and use code blocks next time as described here: How to format your forum posts

I read your post multiple times, but it is difficult to understand it without punctuation.

In general, if you want to optimize the image size and build time, you can check the documentation:

If the required runtime dependencies are large, the image will be large.

And if you copy everthing into the builder stage, if enything changes in the project folder the stage will be rebuilt and it takes time. o you can copy only the files you need or use a .dockerignore file like .gitignore