この記事ではNext.js13をCloudRunにデプロイすることを想定しています。
Next.jsのstandalone機能を使うと通常のビルドと比較して小さいサイズになります。
経験上、だいたい半分ぐらいのビルドサイズになるので必ず使います。
const nextConfig = {
...
output: "standalone",
...
};
next.config.js Options: output | Next.js
Next.js automatically traces which files are needed by each page to allow for easy deployment of your application. Learn how it works here.
目次
ビルドするDockerFile
node:19.1のbuilderでビルドしますがnode:19.1のままだとイメージサイズが大きくなるので、node:19.1-slimでデプロイします。
FROM node:19.1 AS builder
WORKDIR /app
COPY package.json ./
COPY yarn.lock ./
RUN yarn install --frozen-lockfile --production
COPY . .
RUN npx prisma generate
RUN yarn build
FROM node:19.1-slim AS runner
# FROM gcr.io/distroless/nodejs:18 AS runner
WORKDIR /app
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/.next/standalone ./
CMD ["node", "server.js"]
prismaを使用している場合
Next.jsでPrismaを使っている場合はca-certificatesをインストールする必要があります。
FROM node:19.1 AS builder
RUN apt-get update && apt-get install -y ca-certificates
WORKDIR /app
COPY package.json ./
COPY yarn.lock ./
RUN yarn install --frozen-lockfile --production
COPY . .
RUN npx prisma generate
RUN yarn build
FROM node:19.1-slim AS runner
# FROM gcr.io/distroless/nodejs:18 AS runner
WORKDIR /app
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
CMD ["node", "server.js"]
コメント