Deploying to a Kubernetes Cluster

Kubernetes has become the most popular way to deploy, run and manage containers in production. Google Cloud Platform, Microsoft Azure and Amazon Web Services and many more companies provide managed Kubernetes environment.

Kubernetes は、本番環境でコンテナーを展開、実行、管理する最も一般的な方法になりました。Google Cloud Platform、Microsoft Azure、Amazon Web Services など、多くの企業がマネージド Kubernetes 環境を提供しています。

The official API Platform distribution contains a built-in Helm (the k8s package manager) chart to deploy in a wink on any of these platforms.

公式の API プラットフォーム ディストリビューションには、組み込みの Helm (k8s パッケージ マネージャー) チャートが含まれており、これらのプラットフォームのいずれかにウィンクでデプロイできます。

This guide is based on Helm 3.

このガイドは Helm 3 に基づいています。

If you want to deploy API Platform on a local Kubernetes cluster, check out our Minikube tutorial!

API Platform をローカルの Kubernetes クラスターにデプロイする場合は、Minikube チュートリアルをご覧ください。

Preparing Your Cluster and Your Local Machine

  1. Create a Kubernetes cluster on your preferred Cloud provider or install Kubernetes locally on your server, for example with kubeadm
    好みのクラウド プロバイダーに Kubernetes クラスターを作成するか、kubeadm などを使用して、サーバーに Kubernetes をローカルにインストールします。
  2. Install Helm 3 locally following their documentation
    ドキュメントに従って Helm 3 をローカルにインストールします。
  3. Be sure to be connected to the right Kubernetes cluster kubectl config view Details e.g. for Google Cloud running: gcloud config get-value core/project
    適切な Kubernetes クラスター kubectl 構成ビューに接続されていることを確認してください。 Google Cloud の実行: gcloud config get-value core/project

Working-Dir: Your local installation of api-platform. Default /api-platform/

Working-Dir: api-platform のローカル インストール。デフォルト /api-platform/

Creating and Publishing the Docker Images

Example with the Google Container Registry and Google Cloud Platform

Change the name "test-api-platform" to your Google project ID (not the project name). Quickstart Google Cloud If you do not have gcloud yet, install it with these command.

「test-api-platform」という名前を (プロジェクト名ではなく) Google プロジェクト ID に変更します。クイックスタート Google Cloud まだ gcloud を持っていない場合は、次のコマンドでインストールします。

curl https://sdk.cloud.google.com | bash

1. Build the PHP and Caddy Docker images and tag them

Versioning: The 0.1.0 is the version. This value should be the same as the attribute appVersion in Chart.yaml. Infos for Google Container pulling and pushing

バージョン管理: 0.1.0 はバージョンです。この値は、Google Container のプルとプッシュの Chart.yaml.Infos の属性 appVersion と同じである必要があります。

docker build -t gcr.io/test-api-platform/php:0.1.0 -t gcr.io/test-api-platform/php:latest api --target api_platform_php
docker build -t gcr.io/test-api-platform/caddy:0.1.0 -t gcr.io/test-api-platform/caddy:latest api --target api_platform_caddy
docker build -t gcr.io/test-api-platform/pwa:0.1.0 -t gcr.io/test-api-platform/pwa:latest pwa --target api_platform_pwa_prod

2. Push your images to your Docker registry

gcloud auth configure-docker
docker push gcr.io/test-api-platform/php
docker push gcr.io/test-api-platform/caddy
docker push gcr.io/test-api-platform/pwa

Optional push the version images:

オプションでバージョン イメージをプッシュします。

docker push gcr.io/test-api-platform/php:0.1.0 
docker push gcr.io/test-api-platform/caddy:0.1.0 
docker push gcr.io/test-api-platform/pwa:0.1.0

The result should look similar to these images.

結果は、これらの画像のようになります。

Example of Google Images - Overview Example of Google Caddy Image - Details

Deploying with Helm 3

1. Check the Helm version

helm version

If you are using version 2.x follow this guide to migrate Helm to v3

バージョン 2.x を使用している場合は、このガイドに従って Helm を v3 に移行します

2. Firstly you need to update helm dependencies by running

helm dependency update ./helm/api-platform

This will create a folder helm/api-platform/charts/ and add all dependencies there. Actual this is bitnami/postgresql, a file postgresql-[VERSION].tgz is created.

これにより、フォルダー helm/api-platform/charts/ が作成され、そこにすべての依存関係が追加されます。実際には、これは bitnami/postgresql であり、ファイル postgresql-[VERSION].tgz が作成されます。

3. Optional: If you made changes to the Helm chart, check if its format is correct

helm lint ./helm/api-platform

4. Deploy your API to the container

helm upgrade main ./helm/api-platform --namespace=default --create-namespace --wait \
    --install \
    --set "php.image.repository=gcr.io/test-api-platform/php" \
    --set php.image.tag=latest \
    --set "caddy.image.repository=gcr.io/test-api-platform/caddy" \
    --set caddy.image.tag=latest \
    --set "pwa.image.repository=gcr.io/test-api-platform/pwa" \
    --set pwa.image.tag=latest \
    --set php.appSecret='!ChangeMe!' \
    --set postgresql.postgresqlPassword='!ChangeMe!' \
    --set postgresql.persistence.enabled=true \
    --set "corsAllowOrigin=^https?:\/\/[a-z]*\.mywebsite.com$"

The " are necessary for Windows. Use ^ on Windows instead of \ to split commands into multiple lines. You can add the parameter --dry-run to check upfront if anything is correct. Replace the values with the image parameters from the stage above. The parameter php.appSecret is the AppSecret from ./.env Fill the rest of the values with the correct settings. For available options see /helm/api-platform/values.yaml. If you want a test deploy you can set corsAllowOrigin='*'

Windows では " が必要です。Windows では \ の代わりに ^ を使用して、コマンドを複数の行に分割します。パラメーター --dry-run を追加して、何かが正しいかどうかを前もって確認できます。値を上の段階の画像パラメーターに置き換えます。パラメータ php.appSecret は、./.env からの AppSecret です。残りの値に正しい設定を入力します。使用可能なオプションについては、/helm/api-platform/values.yaml を参照してください。テスト デプロイが必要な場合は、corsAllowOrigin= を設定できます。 '*'

After a successful installation, there is a message at the end. You can copy these commands and execute them to set a port-forwarding and get access on your local machine to the deploy. See image below.

インストールが正常に完了すると、最後にメッセージが表示されます。これらのコマンドをコピーして実行すると、ポート転送を設定し、ローカル マシンでデプロイにアクセスできます。下の画像を参照してください。

Deploy Result

If you prefer to use a managed DBMS like Heroku Postgres or Google Cloud SQL (recommended):

Heroku Postgres や Google Cloud SQL などのマネージド DBMS を使用する場合 (推奨):

helm upgrade api-platform ./helm/api-platform \
    # ...
    --set postgresql.enabled=false \
    --set postgresql.url=pgsql://username:password@host/database?serverVersion=13

Finally, build the pwa (client and admin) JavaScript apps and deploy them on a static site hosting service.

最後に、pwa (クライアントおよび管理者) JavaScript アプリをビルドし、それらを staticsite ホスティング サービスにデプロイします。

Access the container

You can access the php container of the pod with the following command. In this example the symfony console is called.

次のコマンドでポッドの php コンテナーにアクセスできます。この例では、symfony コンソールが呼び出されます。

CADDY_PHP_POD=$(kubectl --namespace=default get pods -l app.kubernetes.io/name=api-platform -o jsonpath="{.items[0].metadata.name}")
kubectl --namespace=default exec -it $CADDY_PHP_POD -c api-platform-php -- bin/console

Caution for system architecture

If the pods do not run, and you get the following error from google kubernetes engine logs, there is probably a problem with the system architecture. standard_init_linux.go:211: exec user process caused "exec format error Build the images with the same system architecture as the cluster runs. Example: Building with Mac M1 with arm64 leads to problems. Most cluster will run with x86_64. Solution: https://blog.jaimyn.dev/how-to-build-multi-architecture-docker-images-on-an-m1-mac/

Pod が実行されず、Google kubernetes エンジン ログから次のエラーが発生する場合は、システム アーキテクチャに問題がある可能性があります。例: Mac M1 で arm64 を使用してビルドすると問題が発生します. ほとんどのクラスターは x86_64 で実行されます. on-an-m1-mac/

Updates

There are 2 main upgrade strategies.

主なアップグレード戦略は 2 つあります。

Change the version in the attribut "appVersion" in Chart.yaml and tag the images with this version. You can upgrade with the same command from the installation and pass all parameters.

Chart.yaml の属性「appVersion」でバージョンを変更し、このバージョンでイメージにタグを付けます。インストールから同じコマンドでアップグレードし、すべてのパラメーターを渡すことができます。

2. Use :latest tags

Infos about best practices for tagging images for kubernetes You have to use the *.image.pullPolicy=Always see the last 3 parameters.

kubernetes のイメージにタグを付けるためのベスト プラクティスに関する情報 *.image.pullPolicy=Always see the last 3 parameters. を使用する必要があります。

helm upgrade api-platform ./helm/api-platform --namespace=default \
--set "php.image.repository=gcr.io/test-api-platform/php" \
--set php.image.tag=latest \
--set "caddy.image.repository=gcr.io/test-api-platform/caddy" \
--set caddy.image.tag=latest \
--set "pwa.image.repository=gcr.io/test-api-platform/pwa" \
--set pwa.image.tag=latest \
--set php.appSecret='!ChangeMe!' \
--set postgresql.postgresqlPassword='!ChangeMe!' \
--set postgresql.persistence.enabled=true \
--set "corsAllowOrigin=^https?://[a-z\]*\.mywebsite.com$" \
--set php.image.pullPolicy=Always \
--set caddy.image.pullPolicy=Always \
--set pwa.image.pullPolicy=Always

GitHub Actions Example for deployment

You can find a complete deploy command for GKE on the demo project:

GKE の完全なデプロイ コマンドは、デモ プロジェクトにあります。

Symfony Messenger

Running Pods with the Messenger Component to consume queues requires additions to the Helm chart.

Messenger コンポーネントを使用して Pod を実行してキューを使用するには、Helm チャートに追加する必要があります。

Start by creating a new template for the queue-worker-deployment. The deployment.yaml can be used as template, the caddy container and all unused ENV variables should be removed.

queue-worker-deployment の新しいテンプレートを作成することから始めます。 deployment.yaml はテンプレートとして使用できます。キャディ コンテナーと未使用の ENV 変数はすべて削除する必要があります。

Add the following lines under containers to overwrite the command.

コンテナーの下に次の行を追加して、コマンドを上書きします。

command:
{{ range .Values.queue_worker.command }}
    - {{ . | quote }}
{{ end }}
args:
{{ range .Values.queue_worker.commandArgs }}
    - {{ . | quote }}
{{ end }}

Here is an example on how to use it from your values.yaml:

以下は、values.yaml から使用する方法の例です。

command: ['bin/console']
commandArgs: ['messenger:consume', 'async', '--memory-limit=100M']

The readinessProbe and the livenessProble can not use the default docker-healthcheck but should test if the command is running.

readinessProbe と livenessProble はデフォルトの docker-healthcheck を使用できませんが、コマンドが実行されているかどうかをテストする必要があります。

readinessProbe:
    exec:
        command: ["/bin/sh", "-c", "/bin/ps -ef | grep messenger:consume | grep -v grep"]
        initialDelaySeconds: 120
        periodSeconds: 3