Skip to content

Commit

Permalink
Fix image optimization in standalone builds
Browse files Browse the repository at this point in the history
  • Loading branch information
FluxCapacitor2 committed Dec 9, 2023
1 parent 36e9d20 commit 072acb6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
29 changes: 20 additions & 9 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,42 +1,53 @@
FROM node:20-alpine AS base

# Install dependencies only when needed
FROM node:18-alpine AS deps
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY package.json package-lock.json* ./
RUN --mount=type=cache,target=/root/.npm npm_config_platform=linux npm_config_arch=x64 npm_config_libc=glibc npm ci
RUN npm rebuild --platform=linux --arch=x64 --libc=musl sharp
COPY package.json package-lock.json ./
RUN npm ci
RUN npm install --os=linuxmusl --cpu=x64 sharp

# Rebuild the source code only when needed
FROM node:18-alpine AS builder
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN --mount=type=cache,target=/app/.next/cache npm run build

# Production image, copy all the files and run next
FROM node:18-slim AS runner
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
RUN npm install --os=linuxmusl --cpu=x64 sharp

COPY --from=builder /app/public ./public

# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown nextjs:nodejs .next

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 80
EXPOSE 3000

ENV PORT 80
ENV PORT 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"

CMD ["node", "server.js"]
# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
CMD ["node", "server.js"]
5 changes: 5 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ const nextConfig = {
"gray-matter",
"mdast-util-find-and-replace",
],
outputFileTracingIncludes: {
// This is a workaround to force nft to trace Sharp binaries,
// which will cause them to be included in the Docker image.
"/": ["./node_modules/@img/**"],
},
},
output: "standalone",
images: {
Expand Down

0 comments on commit 072acb6

Please sign in to comment.