Skip to content

Multi-stage builds with node #2305

@b23prodtm

Description

@b23prodtm

Problem

Describing the way how we can use multi-stage builds , my project Dockerfile typically looks like:

# Stage 1: Build Node.js application
FROM node:22-alpine AS node-build

# Set the working directory
WORKDIR /usr/local/project

# Copy package.json and package-lock.json (if available)
COPY package*.json ./

# Install dependencies
RUN yarn install

# Build the Node.js application (if needed)
# RUN yarn run build

# Stage 2: Build Apache application
FROM httpd:2.4

# Set the working directory
WORKDIR /usr/local/apache2/htdocs
COPY --from=node-build node_modules/ node_modules

COPY ./public-html ./

# Install necessary 
ENTRYPOINT ["apachectl", "-D", "FOREGROUND"]

Unfortunately, I'll see then a "File or directory not found" at the second stage of this build job.

Solution

# BEGIN - Multi-stage Build
# Stage 1: Install NodeJS dependencies
FROM node:22-alpine AS node-build

WORKDIR /usr/local/project

# Copy Node.js dependency files, Fixing global modules issue
COPY package.json yarn.lock ./
RUN corepack enable \
    && corepack prepare yarn@stable --activate \
    && yarn install --immutable \
    && yarn cache clean

# Copy only the modules into the image
COPY node_modules/ node_modules

# Stage 2: Build Apache application
FROM httpd:2.4

WORKDIR /usr/local/apache2/htdocs

# import build stage modules
COPY --from=node-build node_modules/ node_modules
# END - Multi-stage Build

Alternatives to Consider

Just file in a project with the node_modules installed in context, but it will not build on every attempt to build

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions