【初心者向けハンズオン】GKE(Google Kuberenetes Engine)にJavaアプリデプロイ ~Step1:Kubernetesクラスタ作成~

1. はじめに

本記事では、Google CloudのKubernetesクラスタ上にSpring Bootで構築したアプリを動作させるハンズオンをご紹介します。以前、オンプレのKubernetesにてSpring Bootアプリをデプロイする方法を紹介しましたが、実際はクラウドサービスを使うケースが多いかと思います。オンプレとクラウドでやることは大きく変わらないですが、微妙に違う点がありますので紹介させていただきます。今回はStep1としてGoogle CloudでKubernetesクラスタを作成して操作する方法をご説明します。

クラウドではなくオンプレで構築したいという方は、下記を参考に作ってみて下さい。
【初心者向けハンズオン】KubernetesでJava(Spring Boot)アプリデプロイ ~Step1:DBコンテナ作成~

2. ハンズオン構成

作業端末:Windows11
Kubernetesクラスタ:GKE (Google Kubernetes Engine)

3. Google Cloudにおけるkubernetesクラスタ作成

3.1 新規プロジェクト作成
Google Cloud Consoleにログインしてください。
https://console.cloud.google.com
ログインできたら、プロジェクトを新規作成します。

※アカウント作成がまだの方は、下記を参考に作成してください。
https://cloud.google.com/iam/docs/service-accounts-create


プロジェクトを新規作成します。


作成したプロジェクトを選択します。


3.2 kubernetesクラスタ作成
検索ウィンドウにGKEと入力すると、Kubernetes Engineの項目が出てくるのでクリックします。


「有効にする」をクリックします。


「クラスタ」をクリックします。


クラスター名を入力して、「作成」をクリックします。


下記の通りステータスが正常なっていれば成功です。

4. CLIツールインストール・設定

4.1 gcloud CLIインストール
WindowsユーザはPowerShellを管理者権限で実行して下さい。


下記コマンドを実行して、gcloud CLIのインストーラを起動してください。

(New-Object Net.WebClient).DownloadFile("https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe", "$env:Temp\GoogleCloudSDKInstaller.exe")
& $env:Temp\GoogleCloudSDKInstaller.exe


インストーラが起動されたらGUIでインストールを進めていきます。「Next」をクリックしてください。


「I Agree」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


「Install」をクリックします。


「Next」をクリックします。


「Finish」をクリックします。


コマンドプロンプトが起動します。Google Cloudにサインインしてよいか聞かれるので「Y」応答してください。


Google Cloudのアカウントを選択してください。


「次へ」をクリックします。


「許可」をクリックします。


下記の通り認証が完了したら成功です。


コマンドプロンプトが表示されます。「Y」応答してGoogle Cloudアカウントにログインします。

Welcome to the Google Cloud CLI! Run "gcloud -h" to get the list of available commands.
---
Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

You must sign in to continue. Would you like to sign in (Y/n)?  


先ほど作成したプロジェクトを指定して下さい。

Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsqlservice.login+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=8Ud8riv1DiRIweFwfVK3UEtOIu9wPb&access_type=offline&code_challenge=Y_9Oe3rKpVjloAaIimkxPB9Fsg3GIhW7Ts7ncFkw_E4&code_challenge_method=S256

You are signed in as: [XXXXXX.XXXXXX@gmail.com].

Pick cloud project to use:
 [1] able-brace-443820-j5
 [2] quizappproject-444000
 [3] Enter a project ID
 [4] Create a new project
Please enter numeric choice or text value (must exactly match list item):2


デフォルトゾーンの選択をします。「Y」応答してください。

Your current project has been set to: [quizappproject-444000].

Do you want to configure a default Compute Region and Zone? (Y/n)?  Y


下記の通りゾーンの選択を求められます。

Which Google Compute Engine zone would you like to use as project default?
If you do not specify a zone via a command line flag while working with Compute Engine resources, the default is
assumed.
 [1] us-east1-b
 [2] us-east1-c
 [3] us-east1-d
~~Omission~~
 [49] asia-east2-c
 [50] asia-northeast2-a
Did not print [78] options.
Too many options [128]. Enter "list" at prompt to print choices fully.
Please enter numeric choice or text value (must exactly match list item):


使いたいzoneに対応した番号を入力してエンターを押します。

Please enter numeric choice or text value (must exactly match list item):  7

Your project default Compute Engine zone has been set to [us-central1-c].
You can change it by running [gcloud config set compute/zone NAME].

Your project default Compute Engine region has been set to [us-central1].
You can change it by running [gcloud config set compute/region NAME].

Created a default .boto configuration file at [C:\Users\user\.boto]. See this file and
gsutil tool  |  Cloud Storage  |  Google Cloud
for more information about configuring Google Cloud Storage. The Google Cloud CLI is configured and ready to use! * Commands that require authentication will use XXXXXX,XXXXXX@gmail.com by default * Commands will reference project `quizappproject-444000` by default * Compute Engine commands will use region `us-central1` by default * Compute Engine commands will use zone `us-central1-c` by default Run `gcloud help config` to learn how to change individual settings This gcloud configuration is called [default]. You can create additional configurations if you work with multiple accounts and/or projects. Run `gcloud topic configurations` to learn more. Some things to try next: * Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command. * Run `gcloud topic --help` to learn about advanced features of the CLI like arg files and output formatting * Run `gcloud cheat-sheet` to see a roster of go-to `gcloud` commands. C:\Users\user\AppData\Local\Google\Cloud SDK>


以上でインストールは完了です。続いて、PowerShellを管理者権限で起動してください。
gcloud –versionでコマンドが実行できるかどうか確認します。実行ポリシーの変更が聞かれたら「Y」応答してください。

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

新機能と改善のために最新の PowerShell をインストールしてください!https://aka.ms/PSWindows

PS C:\Windows\system32> gcloud --version
gcloud : このシステムではスクリプトの実行が無効になっているため、ファイル C:\Users\user\AppData\Local\Google\Cloud SDK
\google-cloud-sdk\bin\gcloud.ps1 を読み込むことができません。詳細については、「about_Execution_Policies」(https://go.mi
crosoft.com/fwlink/?LinkID=135170) を参照してください。
発生場所 行:1 文字:1
+ gcloud --version
+ ~~~~~~
    + CategoryInfo          : セキュリティ エラー: (: ) []、PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
PS C:\Windows\system32> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

実行ポリシーの変更
実行ポリシーは、信頼されていないスクリプトからの保護に役立ちます。実行ポリシーを変更すると、about_Execution_Policies
のヘルプ トピック (https://go.microsoft.com/fwlink/?LinkID=135170)
で説明されているセキュリティ上の危険にさらされる可能性があります。実行ポリシーを変更しますか?
[Y] はい(Y)  [A] すべて続行(A)  [N] いいえ(N)  [L] すべて無視(L)  [S] 中断(S)  [?] ヘルプ (既定値は "N"): Y
PS C:\Windows\system32>


gcloud –versionコマンドをもう一度実行して下さい。下記の通りバージョンが確認できたら成功です。

PS C:\Windows\system32> gcloud --version
Google Cloud SDK 511.0.0
bq 2.1.13
core 2025.02.18
gcloud-crc32c 1.0.0
gsutil 5.33
PS C:\Windows\system32>


Google Cloudアカウントにログインしてください。gcloud auth loginコマンドを実行するとGUI画面が開いてログインアカウントを聞かれるので、選択して進めて下さい。

PS C:\Windows\system32> gcloud auth login
Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsqlservice.login+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=Y3Ynus402zBF61OrxSTy9bkvhVt39I&access_type=offline&code_challenge=h4OEWn6mtVJzNwRwdUfPnGqaz9PIEY1aKYywRafVlak&code_challenge_method=S256


You are now logged in as [XXXXXX.XXXXXXX@gmail.com].
Your current project is [quizappproject-444000].  You can change this setting by running:
  $ gcloud config set project PROJECT_ID
PS C:\Windows\system32>


コンポーネントを最新状態にアップデートしておきます。

PS C:\Windows\system32> gcloud components update
To help improve the quality of this product, we collect anonymized usage data and anonymized stacktraces when crashes
are encountered; additional information is available at <https://cloud.google.com/sdk/usage-statistics>. This data is
handled in accordance with our privacy policy <https://cloud.google.com/terms/cloud-privacy-notice>. You may choose to
opt in this collection now (by choosing 'Y' at the below prompt), or at any time in the future by running the following
command:

    gcloud config set disable_usage_reporting false

Do you want to opt-in (y/N)?  y

Beginning update. This process may take several minutes.

All components are up to date.
PS C:\Windows\system32>


4.2 GKE操作用のプラグインインストール
GKEを操作するためのプラグインをインストールします。

PS C:\Windows\system32> gcloud components install gke-gcloud-auth-plugin

Restarting command:
  $ gcloud components install gke-gcloud-auth-plugin

PS C:\Windows\system32>


「Y」応答してしばらく待つと、Update Doneが表示されます。

Your current Google Cloud CLI version is: 511.0.0
Installing components from version: 511.0.0

┌────────────────────────────────────────────────────────────────┐
│              These components will be installed.               │
├────────────────────────────────────────────┬─────────┬─────────┤
│                    Name                    │ Version │   Size  │
├────────────────────────────────────────────┼─────────┼─────────┤
│ gke-gcloud-auth-plugin (Platform Specific) │  0.5.10 │ 3.6 MiB │
└────────────────────────────────────────────┴─────────┴─────────┘

For the latest full release notes, please visit:
  https://cloud.google.com/sdk/release_notes

Once started, canceling this operation may leave your SDK installation in an inconsistent state.

Do you want to continue (Y/n)?  Y

Performing in place update...

╔════════════════════════════════════════════════════════════╗
╠═ Downloading: gke-gcloud-auth-plugin                      ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Downloading: gke-gcloud-auth-plugin (Platform Specific)  ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gke-gcloud-auth-plugin                       ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gke-gcloud-auth-plugin (Platform Specific)   ═╣
╚════════════════════════════════════════════════════════════╝

Performing post processing steps...done.

Update done!

続行するには何かキーを押してください . . .


4.3 kubectlインストール
続いてkubectlをインストールします。kubectlとは、ご存じの通りKubernetes クラスターを管理するためのコマンドラインツールとなります。

PS C:\Windows\system32> gcloud components install kubectl

Restarting command:
  $ gcloud components install kubectl

PS C:\Windows\system32>


「Y」応答して待ってください。Update Doneの文字列が出てきたら完了です。

Your current Google Cloud CLI version is: 511.0.0
Installing components from version: 511.0.0

┌───────────────────────────────────────────────────┐
│        These components will be installed.        │
├─────────────────────────────┬─────────┬───────────┤
│             Name            │ Version │    Size   │
├─────────────────────────────┼─────────┼───────────┤
│ kubectl                     │  1.30.5 │   < 1 MiB │
│ kubectl (Platform Specific) │  1.30.9 │ 109.3 MiB │
└─────────────────────────────┴─────────┴───────────┘

For the latest full release notes, please visit:
  https://cloud.google.com/sdk/release_notes

Once started, canceling this operation may leave your SDK installation in an inconsistent state.

Do you want to continue (Y/n)?  Y

Performing in place update...

╔════════════════════════════════════════════════════════════╗
╠═ Downloading: kubectl                                     ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Downloading: kubectl (Platform Specific)                 ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: kubectl                                      ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: kubectl (Platform Specific)                  ═╣
╚════════════════════════════════════════════════════════════╝

Performing post processing steps...done.

Update done!

続行するには何かキーを押してください . . .


GKEアクセスをするための認証情報を取得します。

PS C:\Windows\system32> gcloud container clusters get-credentials quizapp-cluster --region=us-central1
Fetching cluster endpoint and auth data.
kubeconfig entry generated for quizapp-cluster.
PS C:\Windows\system32> 


kubectlコマンドが実行できるか確認してみてください。試しにnamespaceを取得してみましょう。下記の通りデフォルトで作成されているnamespaceが表示されれば成功です。

PS C:\Windows\system32> kubectl get ns
NAME                          STATUS   AGE
default                       Active   72m
gke-gmp-system                Active   69m
gke-managed-cim               Active   70m
gke-managed-filestorecsi      Active   70m
gke-managed-system            Active   69m
gke-managed-volumepopulator   Active   69m
gmp-public                    Active   69m
kube-node-lease               Active   72m
kube-public                   Active   72m
kube-system                   Active   72m

4. まとめ

Google CloudにおけるKubernetesクラスタ作成、および操作用ツールのインストールについては以上となります。こんなに簡単にKubernetesクラスタを作成して使えるのはありがたいですね。Step2ではDBコンテナ作成をご紹介するので、引き続き実践してみて下さい。
【初心者向けハンズオン】GKE(Google Kuberenetes Engine)にJavaアプリデプロイ ~Step2:DBコンテナ作成~

5. 参考文献

コメント