react-server675fbba4
react-serverfilespackagescreate-react-servertemplatesDockerfile.yarn
packages/create-react-server/templates/Dockerfile.yarn1.6 KiB2270f718
# Define build argument for port with default value
ARG PORT=3000

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

# Set working directory
WORKDIR /app

# Copy package files
COPY package.json yarn.lock ./

# Install yarn globally
RUN --mount=type=cache,target=/root/.npm \
  if grep -q "\"packageManager\":" "package.json"; then \
  corepack enable && corepack prepare; \
  else \
  npm install -g yarn; \
  fi

# Install dependencies
RUN --mount=type=cache,target=/usr/local/share/.cache/yarn \
  yarn install --frozen-lockfile

# Copy source files and .react-server directory
COPY . .

# Build the application
RUN yarn build

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

# Forward the build argument
ARG PORT
ENV PORT=$PORT

# Set working directory
WORKDIR /app

# Copy package files
COPY --from=builder /app/package.json /app/yarn.lock ./

# Install yarn globally
RUN --mount=type=cache,target=/root/.npm \
  if grep -q "\"packageManager\":" "package.json"; then \
  corepack enable && corepack prepare; \
  else \
  npm install -g yarn; \
  fi

# Copy built files and .react-server from builder stage
COPY --from=builder /app/package.json /app/yarn.lock ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/.react-server ./.react-server

# Prune dev dependencies
RUN --mount=type=cache,target=/usr/local/share/.cache/yarn \
  yarn install --production --frozen-lockfile

# Run as non-root user
RUN addgroup -g 1001 -S nodejs && \
  adduser -S nodejs -u 1001 && \
  chown -R nodejs:nodejs /app
USER nodejs

# Expose the port your app runs on
EXPOSE ${PORT}

# Start the application
CMD ["yarn", "start", "--host"]