🏃

Next.js SSR を Cloud Run で公開する手順

2024/03/28に公開

🎯目的

Next.js SSR を Cloud Run に公開できるようにする

💡前提

🏃手順

1. Next.js プロジェクトを編集

まずは、下記の手順に従いプロジェクトを作成してください。
https://zenn.dev/taiyou/articles/bee72ea562de4f

next.config.js を編集

References

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
+    output: 'standalone',
};

export default nextConfig;
Dockerfile を作成する

References

FROM node:18-alpine AS base

# Install dependencies only when needed
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 yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi


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

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN yarn build

# If using npm comment out above and use below instead
# RUN npm run build

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

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 3000

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

# 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"]

2. GitHub リポジトリを作成し、pushする

GitHub リポジトリを作成し、pushする

3. GitHub Actions の YAML ファイルを作成する

以下の記事を参考にして、デプロイをしようとしたところ、デプロイが行えなかったので GitHub Actions を用いて、Google Cloud SDK でデプロイします。
https://zenn.dev/google_cloud_jp/articles/nextjs-on-cloudrun

.github/workflows/deploy-cloud-run-prod.yaml
name: Deploy to Cloud Run

on:
  push:
    branches:
      - master
      - main

env:
  PROJECT_ID: ${{ secrets.CLOUD_RUN_PROJECT_NAME }}
  REGION: asia-northeast1
  # project-name but it can be anything you want
  REPO_NAME: cdp-admin
jobs:
  build-and-deploy:
    name: Setup, Build, and Deploy
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      # Authenticate with Google Cloud
      - id: "auth"
        uses: "google-github-actions/auth@v2"
        with:
          credentials_json: "${{ secrets.CLOUD_RUN_SERVICE_ACCOUNT }}"

      # Setup gcloud CLI/SDK
      - name: Set up Cloud SDK
        uses: google-github-actions/setup-gcloud@v2

      - name: Authorize Docker push
        run: gcloud auth configure-docker

      - name: Build and tag the docker image
        run: |-
          docker build . --tag gcr.io/$PROJECT_ID/$REPO_NAME:$GITHUB_SHA

      - name: Push the image to the Google Container Registry (GCR)
        run: |-
          docker push gcr.io/$PROJECT_ID/$REPO_NAME:$GITHUB_SHA

      - name: Deploy
        run: |-
          gcloud run deploy $REPO_NAME \
          --region $REGION \
          --image gcr.io/$PROJECT_ID/$REPO_NAME:$GITHUB_SHA \
          --platform "managed" \
          --port 3000 \
          --allow-unauthenticated \
          --quiet

4. Google Cloud サービスアカウントキーを作成する

JSONファイルのアカウントキーを作成し、ダウンロードする。
https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=ja

5. GitHub リポジトリに secrets 情報を登録する

シークレット情報 説明
CLOUD_RUN_PROJECT_NAME プロジェクト名
CLOUD_RUN_SERVICE_ACCOUNT 「4. Google Cloud サービスアカウントキーを作成する」で作成した JSON のアカウントキーをコピペ

6. リリース

GitHub リポジトリに push し、リリースを開始する。

📝補足

独自ドメインで公開する

WIP

🔗APPENDIX

https://zenn.dev/google_cloud_jp/articles/nextjs-on-cloudrun

https://zenn.dev/ossamoon/articles/8b784b2f6aaeb2

https://zenn.dev/tokku5552/articles/run-and-sql-nextjs

https://github.com/e-roy/next-cloud-run-app/tree/main

https://github.com/librarylai/next-deploy-gcp/tree/main

Discussion