今回はGCPのCloud Runにアプリケーションをデプロイします。
Cloud Runを選んだのは、Clud RunがWebSocketに対応しており、いざSubscriptionが必要となったときも実装しようと思えば実現できなくはないためです。
Apollo Serverの公式ドキュメントには、Herokuをはじめ、AWS LambdaなどのFaaSにデプロイする方法が紹介されています。
DBはHerokuのPostgresを使用します。
セットアップ方法は以下を参考にしてください。
GitHub ActionsでCI/CDパイプラインを用意し、デプロイとマイグレーションを自動化します。
以下の記事を参考にさせていただきました。
package.json
のscriptsにマイグレーション用のスクリプトを追加します。
package.json
"scripts": {
"dev": "ts-node-dev --respawn src/index.ts",
"build": "tsc -p tsconfig.json",
"start": "cp schema.graphql dist/ && node dist/src/index.js",
"format": "prettier --write $PWD/'src/**/*.{js,ts}'",
"lint": "eslint 'src/**/*.{js,ts}'",
"clean": "rm -rf dist",
"graphql:codegen": "graphql-codegen --config codegen.yml",
"prisma:studio": "prisma studio",
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy"
},
開発中はprisma migrate dev
を使用していましたが、ステージング環境や本番環境に対してマイグレーションを行いたいときはprisma migrate deploy
コマンドを使用します。
以下のワークフローを追加します。
.github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
env:
GCP_REGION: ${{ secrets.GCP_REGION }}
GCP_PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
SERVICE_NAME: ${{ secrets.SERVICE_NAME }}
PORT: ${{ secrets.PORT }}
IMAGE: asia.gcr.io/${{ secrets.GCP_PROJECT_ID }}/${{ secrets.SERVICE_NAME }}:${{ github.sha }}
jobs:
deploy-to-cloud-run:
runs-on: ubuntu-latest
steps:
- name: checkout the repository
uses: actions/checkout@v2
- name: set up Cloud SDK
uses: google-github-actions/setup-gcloud@master
with:
project_id: ${{ secrets.GCP_PROJECT_ID }}
service_account_key: ${{ secrets.GCP_SA_KEY }}
export_default_credentials: true
- name: configure docker to use the gcloud cli
run: gcloud auth configure-docker --quiet
- name: build a docker image
run: docker build . -t $IMAGE
- name: push the docker image
run: docker push $IMAGE
- name: Deploy to Cloud Run
run: |
gcloud run deploy $SERVICE_NAME \
--image $IMAGE \
--port $PORT \
--project $GCP_PROJECT_ID \
--region $GCP_REGION \
--platform=managed \
--allow-unauthenticated \
--quiet
migration:
runs-on: ubuntu-latest
steps:
- name: checkout the repository
uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14.x'
- name: Create .env file
run: |
touch .env
echo DATABASE_URL=${{ secrets.DATABASE_URL }} >> .env
- name: migrate
run: |
yarn install
yarn prisma:deploy
これでmainにpushされるたびにデプロイ・マイグレーションが自動で行われるようになりました。