Бессерверные контейнеры против бессерверного Next.js SSR GCP App Engine

Шаг 0: проверьте резюме

GCP App Engine

Давайте просто начнем с нуля с новым проектом, новым репозиторием:

Открываем новое рабочее пространство в ide, клонируем проект, инициализируем приложение Next.js (см. руководство по GCP Cloud Run ).
Теперь давайте просто откроем документ о создании нового приложения.
Включение API, так как это новый проект.
Документ классный, но мне больше нравится документ по CLI.

gcloud config set project nextgcp-361410
Updated property [core/project].

gcloud app create
You are creating an app for project [nextgcp-361410].
WARNING: Creating an App Engine application for a project is irreversible and the region
cannot be changed. More information about regions is at
<https://cloud.google.com/appengine/docs/locations>.

Please choose the region where you want your App Engine application located:
Please enter your numeric choice:  11

Creating App Engine application in project [nextgcp-361410] and region [europe-west]....done.                      
Success! The app is now created. Please use `gcloud app deploy` to deploy your first app.

Вход в полноэкранный режим Выйти из полноэкранного режима

Да! Теперь добавим app.yaml из ссылки, минимальную рабочую версию:

runtime: nodejs16
Вход в полноэкранный режим Выход из полноэкранного режима

и cloudbuild.yaml :

steps:
  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    entrypoint: 'bash'
    args: ['-c', 'gcloud config set app/cloud_build_timeout 1600 && gcloud app deploy']
timeout: '1600s'
Войти в полноэкранный режим Выйти из полноэкранного режима

У меня есть cloudbuild.yaml из документа deploy to app engine doc
Включение API :

Разрешения учетной записи службы в настройках Cloud Build :

Триггер как для Cloud Run (вам может понадобиться нажать на Manage Repositories, затем на точки справа от имени репозитория и Add Trigger).

Давайте зафиксируем, запустим и проверим. У меня ошибка:

ERROR: (gcloud.app.deploy) PERMISSION_DENIED: You do not have permission to act as 'nextgcp-361410@appspot.gserviceaccount.com'
- '@type': type.googleapis.com/google.rpc.ResourceInfo
  description: You do not have permission to act as this service account.
  resourceName: nextgcp-361410@appspot.gserviceaccount.com
  resourceType: serviceAccount
Войдите в полноэкранный режим Выйти из полноэкранного режима

Поэтому я пойду в IAM
И добавлю роль Service Account User в учетную запись cloudbuild.
До :

После

Сработало, отлично!

Хорошо, почти

Давайте запустим приложение на порту 8080, package.json :

{
  "name": "nextgcp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start -p 8080",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "12.2.5",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "eslint": "8.23.0",
    "eslint-config-next": "12.2.5"
  }
}

Входим в полноэкранный режим Выход из полноэкранного режима

Commit — push — build, не так плохо, но не так быстро:


Проверка журналов в Cloud Shell :

gcloud app logs tail -s default
Вход в полноэкранный режим Выход из полноэкранного режима

Похоже, приложение не было создано:

2022-09-03 11:12:56 default[20220903t110848]  "GET / HTTP/1.1" 500
2022-09-03 11:12:56 default[20220903t110848]  ready - started server on 0.0.0.0:8080, url: http://localhost:8080
2022-09-03 11:12:57 default[20220903t110848]  info  - SWC minify release candidate enabled. https://nextjs.link/swcmin
2022-09-03 11:12:57 default[20220903t110848]  {"severity": "WARNING", "message": "App is listening on port 8080. We recommend your app listen on the port defined by the PORT environment variable to take advantage of an NGINX layer on port 8080."}nError: Could not find a production build in the '/workspace/.next' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id
Войти в полноэкранный режим Выйти из полноэкранного режима

Действительно, давайте проверим руководство по созданию приложений Node.js
и улучшим cloudbuild.yaml :

steps:
- name: node
  entrypoint: yarn
  args: ['install']
- name: node
  entrypoint: yarn
  args: ['run', 'build']
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  entrypoint: 'bash'
  args: ['-c', 'gcloud config set app/cloud_build_timeout 1600 && gcloud app deploy']
timeout: '1600s'

Войти в полноэкранный режим Выход из полноэкранного режима

Commit — push — build :

Почти готово, отображение пользовательского домена:

И наконец:

Успех!
Если у вас есть опыт работы на GCP и вы умеете составлять конфигурационные файлы и крутить ручки, то вам будет проще выбрать App Engine, в противном случае рассмотрите Cloud Run.

Оцените статью
devanswers.ru
Добавить комментарий