GCP gkeのメモ2(gceでpythonサンプルアプリをビルドし、google cloud registoryにpush/pullしてgkeでも動かす)

GCRを業務で扱うことになったのでやってみる。

GCRってのはgoogle container registoryっていうdocker image置き場。
自分のプロジェクトの中でのみ公開したいときに使うみたい。

ビルドはローカルPCのdockerでやってイメージ作ってから、GCRへ認証を通しておいてdocker pushすることでイメージ作れる。
GCRに作ったイメージはGKEのポッドに展開して動かせる。

GCR(google container registory)はGAR(google artifact registory)に移ってくのかも?

Container Registry のクイックスタート  |  Container Registry のドキュメント  |  Google Cloud

まぁええ。やってみよ。
参考にさせてもらったページは、先にcloud source repositoriesへ登録してるところもあったから、ついでにやってみた。

普段使ってるGCPのプロジェクトとは別枠でやってみた。

仮想マシン作成

マーケットプレースから流用して仮想マシン作る。
vcpuとメモリは予算に応じて。自分は4コア16GBメモリHDD50GBで作った。
無料枠やからこれぐらいでええ。ディスクを多くとったのは後でdocker入れたいから。
ファイアウォールで80と443のポート開けとく設定も入れとく。

起動してコマンドライン使えるまで1分。
めちゃ楽。

aptしてgit入れる

rootユーザになって以下を動かす。

apt autoremove
apt clean
apt update
apt upgrade

保留のパッケージが残ることもあるけど、更新対象がなくなるまで動かす。
全部で2回動かせばいい。
途中で確認メッセージが出ることあるけど、全部「承認」とか「OK」でええ。

2回目のapt upgradeまでやるとこんな感じ。

root@ubuntu22:~# apt autoremove
:(中略)
root@ubuntu22:~# apt clean
:(中略)
root@ubuntu22:~# apt update
:(中略)
root@ubuntu22:~# apt upgrade
:(中略)
root@ubuntu22:~# apt autoremove
:(中略)
root@ubuntu22:~# apt clean
:(中略)
root@ubuntu22:~# apt upgrade
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
The following packages have been kept back:
  libglib2.0-0 libglib2.0-bin libglib2.0-data
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.
root@ubuntu22:~# 

後で使うのでgoogle cloud SDKが紐づいているか確認する。

gavannitsales@ubuntu22:~$ gcloud config list
[core]
account = 225919338029-compute@developer.gserviceaccount.com
disable_usage_reporting = True
project = fourth-elixir-383118

Your active configuration is: [default]
gavannitsales@ubuntu22:~$ 

普通にgit入れる。

root@ubuntu22:~# apt install git
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
git is already the newest version (1:2.34.1-1ubuntu1.8).
git set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.
root@ubuntu22:~# 

git使う初期化しとく。

git config --global user.email "sales@gavann-it.com"
git config --global user.name "sales"

サンプルアプリを動かす

pythonのサンプルアプリを準備する。

参考にさせてもらったページ。
作者さんありがとう。

【GCP入門編・第4回】すぐ出来なくても大丈夫!サンプルアプリで Google Compute Engine (GCE) の動作練習! | 株式会社トップゲート
GCP の Google App Engine 向けのサンプルアプリケーションを Google Compute Engine のインスタンス上で動作させてみよう。

developmentしてくところは、たぶんcloud source repositoriesのことかな。
gcr使う前に、source repositoriesってサービスもやってみる。

cloud source repositoryはgitリポジトリで、push/pullできる。

gitからサンプルをとってくる。

gavannitsales@ubuntu22:~$ mkdir sample
gavannitsales@ubuntu22:~$ cd sample
gavannitsales@ubuntu22:~/sample$ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
Cloning into 'python-docs-samples'...
remote: Enumerating objects: 95977, done.
remote: Counting objects: 100% (1728/1728), done.
remote: Compressing objects: 100% (932/932), done.
remote: Total 95977 (delta 894), reused 1478 (delta 751), pack-reused 94249
Receiving objects: 100% (95977/95977), 205.77 MiB | 38.10 MiB/s, done.
Resolving deltas: 100% (57057/57057), done.
Updating files: 100% (4376/4376), done.
gavannitsales@ubuntu22:~/sample$ 

gitローカルリポジトリを構成

必要な個所を抜き出してgit initしてローカルリポジトリ作る。

後で気づいたけど、requirements.txtが入ってない。
gitした元ソースのあるフォルダ近辺を見たらtutorialのフォルダがあって、そこにrequirements.txtが入ってたのでコピーして設置する必要がある。

gavannitsales@ubuntu22:~/sample$ cp -rf ./python-docs-samples/appengine/standard/flask/hello_world/ ./hello_world
gavannitsales@ubuntu22:~/sample$ cd hello_world/
gavannitsales@ubuntu22:~/sample/hello_world$ git init .
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint: 
hint:   git config --global init.defaultBranch <name>
hint: 
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint: 
hint:   git branch -m <name>
Initialized empty Git repository in /home/gavannitsales/sample/hello_world/.git/
gavannitsales@ubuntu22:~/sample/hello_world$ git add .
gavannitsales@ubuntu22:~/sample/hello_world$ git commit -m "Initial Commit" 
[master (root-commit) 2f88308] Initial Commit
 5 files changed, 98 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 README.md
 create mode 100644 app.yaml
 create mode 100644 main.py
 create mode 100644 main_test.py
gavannitsales@ubuntu22:~/sample/hello_world$ 

source repositoriesへpushして登録

ssh認証鍵登録が必要らしい。
gceで動いてるubuntu22のssh鍵をコピペしてssh認証鍵を登録。
2つあるうち、1つめを使った。

gvis-gke-memo02

ssh鍵を登録したところ。

gvis-gke-memo02

source repositoriesへpushするにはどうしたらいいか書いてある。

gvis-gke-memo02

cloud repositoryをremoteとして追加してみる。

gavannitsales@ubuntu22:~/sample/hello_world$ git remote add google ssh://gavannitsales@gmail.com@source.developers.google.com:2022/p/fourth-elixir-383118/r/hello-world
gavannitsales@ubuntu22:~/sample/hello_world$ 

ローカルリポジトリをcloud repositoryへ登録する。

gavannitsales@ubuntu22:~/sample/hello_world$ git push --all google
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 4 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (7/7), 1.55 KiB | 1.55 MiB/s, done.
Total 7 (delta 2), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (2/2)
To ssh://gmail.com@source.developers.google.com:2022/p/fourth-elixir-383118/r/hello-world
 * [new branch]      master -> master
gavannitsales@ubuntu22:~/sample/hello_world$

はい、入ったー。

gvis-gke-memo02

すぐにこれはいらんけど、扱い方はイメージできた。
GCRでも似たようなことやる。

source repositoriesからpullしてとってくる

入った結果をpullしてみると、VMからはスコープ外って怒られた。
なんやねん、取れへんのかいな。

gavannitsales@ubuntu22:~$ mkdir sampleClone
gavannitsales@ubuntu22:~$ cd sampleClone
gavannitsales@ubuntu22:~/sampleClone$
gavannitsales@ubuntu22:~/sampleClone$ gcloud source repos clone hello-world --project=fourth-elixir-383118
ERROR: (gcloud.source.repos.clone) PERMISSION_DENIED: Request had insufficient authentication scopes.
- '@type': type.googleapis.com/google.rpc.ErrorInfo
  domain: googleapis.com
  metadata:
    method: google.devtools.sourcerepo.v1.SourceRepo.GetRepo
    service: sourcerepo.googleapis.com
  reason: ACCESS_TOKEN_SCOPE_INSUFFICIENT

If you are in a compute engine VM, it is likely that the specified scopes during VM creation are not enough to run this command.
See https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam for more information about access scopes.
See https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#changeserviceaccountandscopes for how to update access scopes of the VM.
gavannitsales@ubuntu22:~/sampleClone$ 

メッセージあるURLを見るとアクセススコープをgceのvmに対して変更必要らしい。

Create a VM that uses a user-managed service account  |  Compute Engine Documentation  |  Google Cloud

vm編集するから、OSいっかいとめなアカン。
何をつけなアカンのか調べるのじゃまくさいから、スコープ全部つけたった。

gvis-gke-memo02

アクセススコープ変更したし、再チャレンジ!!

gavannitsales@ubuntu22:~/sampleClone$ gcloud source repos clone hello-world --project=fourth-elixir-383118
Cloning into '/home/gavannitsales/sampleClone/hello-world'...
remote: Total 7 (delta 2), reused 7 (delta 2)
Receiving objects: 100% (7/7), done.
Resolving deltas: 100% (2/2), done.
Project [fourth-elixir-383118] repository [hello-world] was cloned to [/home/gavannitsales/sampleClone/hello-world].
gavannitsales@ubuntu22:~/sampleClone$ 

おお、clone行けた。
diffで確認してみよか。

gavannitsales@ubuntu22:~/sampleClone$ diff -r --exclude=.git hello-world/ ../sample/hello_world/
gavannitsales@ubuntu22:~/sampleClone$ 

.gitのフォルダを除いて比較すると一致してますな。

pipで必要モジュール集めてサンプルアプリ起動

次にhello-worldアプリを起動してみる。
まずはpythonとpipとgunicorn入れる。

gavannitsales@ubuntu22:~/sampleClone/hello-world$ sudo apt install python-pip gunicorn
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
:(中略)
update-alternatives: using /usr/bin/g++ to provide /usr/bin/c++ (c++) in auto mode
Setting up build-essential (12.9ubuntu3) ...
Processing triggers for man-db (2.10.2-1) ...
Processing triggers for libc-bin (2.35-0ubuntu3.1) ...
Scanning processes...                                                                                          
Scanning linux images...                                                                                       

Running kernel seems to be up-to-date.

No services need to be restarted.

No containers need to be restarted.

No user sessions are running outdated binaries.

No VM guests are running outdated hypervisor (qemu) binaries on this host.
gavannitsales@ubuntu22:~/sampleClone/hello-world$

pipを更新して、requirements.txtにあるパッケージを入れてく。

gavannitsales@ubuntu22:~/sampleClone/hello-world$ pip install --upgrade pip
Command 'pip' not found, but can be installed with:
apt install python3-pip
Please ask your administrator.
gavannitsales@ubuntu22:~/sampleClone/hello-world$ 

ありゃ、python3入れろやぁって怒られた。
入れてからもう1回やってみるとOK。

gavannitsales@ubuntu22:~/sampleClone/hello-world$ sudo apt install python3-pip
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
:(中略)
Processing triggers for man-db (2.10.2-1) ...
Scanning processes...                                                                                          
Scanning linux images...                                                                                       

Running kernel seems to be up-to-date.

No services need to be restarted.

No containers need to be restarted.

No user sessions are running outdated binaries.

No VM guests are running outdated hypervisor (qemu) binaries on this host.
gavannitsales@ubuntu22:~/sampleClone/hello-world$ pip install --upgrade pip
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pip in /usr/lib/python3/dist-packages (22.0.2)
Collecting pip
  Downloading pip-23.1.2-py3-none-any.whl (2.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 13.9 MB/s eta 0:00:00
Installing collected packages: pip
  WARNING: The scripts pip, pip3 and pip3.10 are installed in '/home/gavannitsales/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-23.1.2
gavannitsales@ubuntu22:~/sampleClone/hello-world$ 

requirements.txtにあるパッケージを入れる。

元のパッケージのtutorialフォルダのREADME.mdを読んでみたら同じフォルダにrequirements.txtがあるのでコピーして使わせてもらった。

gavannitsales@ubuntu22:~/sample/python-docs-samples/appengine/standard/flask/tutorial$ cat README.md 
:(中略)
This sample shows how to use [Flask](http://flask.pocoo.org/) to handle
requests, forms, templates, and static files on Google App Engine Standard.

Before running or deploying this application, install the dependencies using
[pip](http://pip.readthedocs.io/en/stable/):

    pip install -t lib -r requirements.txt

For more information, see the [App Engine Standard README](../../README.md)
gavannitsales@ubuntu22:~/sample/python-docs-samples/appengine/standard/flask/tutorial$ cat requirements.txt 
Flask==1.1.4; python_version < '3.0'
Flask==2.1.0; python_version > '3.0'
Werkzeug==1.0.1; python_version < '3.0'
gavannitsales@ubuntu22:~/sample/python-docs-samples/appengine/standard/flask/tutorial$ cp -p requirements.txt ~/sampleClone/hello-world/
gavannitsales@ubuntu22:~/sampleClone/hello-world$ sudo pip install -r requirements.txt 
Ignoring Flask: markers 'python_version < "3.0"' don't match your environment
Ignoring Werkzeug: markers 'python_version < "3.0"' don't match your environment
Collecting Flask==2.1.0
  Downloading Flask-2.1.0-py3-none-any.whl (95 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 95.2/95.2 KB 2.4 MB/s eta 0:00:00
Requirement already satisfied: click>=8.0 in /usr/lib/python3/dist-packages (from Flask==2.1.0->-r requirements.txt (line 2)) (8.0.3)
Collecting Werkzeug>=2.0
  Downloading Werkzeug-2.3.2-py3-none-any.whl (242 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 242.2/242.2 KB 7.9 MB/s eta 0:00:00
Collecting itsdangerous>=2.0
  Downloading itsdangerous-2.1.2-py3-none-any.whl (15 kB)
Requirement already satisfied: Jinja2>=3.0 in /usr/lib/python3/dist-packages (from Flask==2.1.0->-r requirements.txt (line 2)) (3.0.3)
Collecting MarkupSafe>=2.1.1
  Downloading MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (25 kB)
Installing collected packages: MarkupSafe, itsdangerous, Werkzeug, Flask
  Attempting uninstall: MarkupSafe
    Found existing installation: MarkupSafe 2.0.1
    Not uninstalling markupsafe at /usr/lib/python3/dist-packages, outside environment /usr
    Can't uninstall 'MarkupSafe'. No files were found to uninstall.
Successfully installed Flask-2.1.0 MarkupSafe-2.1.2 Werkzeug-2.3.2 itsdangerous-2.1.2
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
gavannitsales@ubuntu22:~/sampleClone/hello-world$ 

起動して、gceのvmホストが持ってる外部IPアドレスへブラウザで接続してみる。

gavannitsales@ubuntu22:~/sampleClone/hello-world$ sudo gunicorn -b 0.0.0.0:80 main:app
[2023-04-28 23:38:44 +0000] [2345] [INFO] Starting gunicorn 20.1.0
[2023-04-28 23:38:44 +0000] [2345] [INFO] Listening at: http://0.0.0.0:80 (2345)
[2023-04-28 23:38:44 +0000] [2345] [INFO] Using worker: sync
[2023-04-28 23:38:44 +0000] [2346] [INFO] Booting worker with pid: 2346

はい見えた~。

gvis-gke-memo02

見えたのはええけど、アプリでなんかタイムアウト起こしてる。
せやから最初の1回目のブラウザ表示遅いんやな。
今はpythonのアプリ動いたらええから放置。

gvis-gke-memo02

docker入れる

次のステップでdocker使い始めるみたいやから、gceのvmにdokcer入れる。

gavannitsales@ubuntu22:~$ sudo apt-get install ca-certificates curl gnupg lsb-release 
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
lsb-release is already the newest version (11.1.0ubuntu4).
lsb-release set to manually installed.
ca-certificates is already the newest version (20211016ubuntu0.22.04.1).
ca-certificates set to manually installed.
curl is already the newest version (7.81.0-1ubuntu1.10).
curl set to manually installed.
gnupg is already the newest version (2.2.27-3ubuntu2.1).
gnupg set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
gavannitsales@ubuntu22:~$ 
gavannitsales@ubuntu22:~$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
gavannitsales@ubuntu22:~$ echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
gavannitsales@ubuntu22:~$ sudo apt-get update 
Hit:1 http://us-central1.gce.archive.ubuntu.com/ubuntu jammy InRelease
Get:2 http://us-central1.gce.archive.ubuntu.com/ubuntu jammy-updates InRelease [119 kB]                   
Get:3 http://us-central1.gce.archive.ubuntu.com/ubuntu jammy-backports InRelease [108 kB]                     
Get:4 https://download.docker.com/linux/ubuntu jammy InRelease [48.9 kB]                                      
Get:5 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]                                
Get:6 https://download.docker.com/linux/ubuntu jammy/stable amd64 Packages [16.7 kB]
Fetched 402 kB in 1s (554 kB/s)                                     
Reading package lists... Done
gavannitsales@ubuntu22:~$ sudo apt-get install docker-ce
:(中略)
Setting up docker-ce (5:23.0.5-1~ubuntu.22.04~jammy) ...
Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /lib/systemd/system/docker.service.
Created symlink /etc/systemd/system/sockets.target.wants/docker.socket → /lib/systemd/system/docker.socket.
Processing triggers for man-db (2.10.2-1) ...
Processing triggers for libc-bin (2.35-0ubuntu3.1) ...
Scanning processes...                                                                                          
Scanning candidates...                                                                                         
Scanning linux images...                                                                                       

Running kernel seems to be up-to-date.

Restarting services...
Service restarts being deferred:
 systemctl restart networkd-dispatcher.service
 systemctl restart unattended-upgrades.service

No containers need to be restarted.

No user sessions are running outdated binaries.

No VM guests are running outdated hypervisor (qemu) binaries on this host.
gavannitsales@ubuntu22:~$

一般ユーザでdocker使うおまじないも入れて、いったんログアウトしてから再ログインする。

gavannitsales@ubuntu22:~$ sudo usermod -aG docker gavannitsales

追加できてるか確認し、hello-worldできるか確認。
あ、ここのhello-worldはpythonでローカルに作ったのとは別モノ。

gavannitsales@ubuntu22:~$ groups gavannitsales
gavannitsales : gavannitsales adm dialout cdrom floppy audio dip video plugdev netdev lxd ubuntu google-sudoers docker
gavannitsales@ubuntu22:~$ 
gavannitsales@ubuntu22:~$ sudo docker run hello-world 
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete 
Digest: sha256:4e83453afed1b4fa1a3500525091dbfca6ce1e66903fd4c01ff015dbcb1ba33e
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

gavannitsales@ubuntu22:~$ 

インターネット経由でイメージ取得してエラーなしなのでOK。
コンテナ削除とイメージ削除できるかも確認。

gavannitsales@ubuntu22:~$ docker ps -a
CONTAINER ID   IMAGE         COMMAND    CREATED              STATUS                          PORTS     NAMES
420dd58ee25f   hello-world   "/hello"   About a minute ago   Exited (0) About a minute ago             distracted_bassi
gavannitsales@ubuntu22:~$ docker rm 420dd58ee25f
420dd58ee25f
gavannitsales@ubuntu22:~$ docker images 
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
hello-world   latest    feb5d9fea6a5   19 months ago   13.3kB
gavannitsales@ubuntu22:~$ docker rmi feb5d9fea6a5
Untagged: hello-world:latest
Untagged: hello-world@sha256:4e83453afed1b4fa1a3500525091dbfca6ce1e66903fd4c01ff015dbcb1ba33e
Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412
Deleted: sha256:e07ee1baac5fae6a26f30cabfe54a36d3402f96afda318fe0a96cec4ca393359
gavannitsales@ubuntu22:~$ 

Dockerfile作る

サンプルフォルダの作成から。
cloud source repositoriesの登録で使ったフォルダをコピーする。

gavannitsales@ubuntu22:~$ cp -pR sampleClone/ GCRsample
gavannitsales@ubuntu22:~$ cd GCRsample/hello-world
gavannitsales@ubuntu22:~/GCRsample/hello-world$ ls
README.md  app.yaml  main.py  main_test.py  requirements.txt
gavannitsales@ubuntu22:~/GCRsample/hello-world$ 

同じフォルダにDockerfile作る。

vi Dockerfile

FROM library/ubuntu:trusty
LABEL description="Hello World Application"
RUN apt-get update && \
    apt-get -y install python gunicorn python-flask
RUN mkdir /srv/hello-world
COPY . /srv/hello-world
WORKDIR /srv/hello-world
EXPOSE 8000
ENTRYPOINT ["/usr/bin/gunicorn", "-b", ":8000", "main:app"]

ビルドする

ペーストしてるとわからんけど、dockerがバージョン23になってから、ビルドの画面の文字の流れ方変わったなぁ。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ docker build -t hello-world-container .
[+] Building 35.8s (10/10) FINISHED                                                                            
 => [internal] load build definition from Dockerfile                                                      0.0s
 => => transferring dockerfile: 334B                                                                      0.0s
 => [internal] load .dockerignore                                                                         0.1s
 => => transferring context: 2B                                                                           0.0s
 => [internal] load metadata for docker.io/library/ubuntu:trusty                                          0.7s
 => [1/5] FROM docker.io/library/ubuntu:trusty@sha256:64483f3496c1373bfd55348e88694d1c4d0c9b660dee6bfef5  4.2s
 => => resolve docker.io/library/ubuntu:trusty@sha256:64483f3496c1373bfd55348e88694d1c4d0c9b660dee6bfef5  0.0s
 => => sha256:512123a864da5e2a62949e65b67106292c5c704eff90cac2b949fc8d7ac1e58e 189B / 189B                0.1s
 => => sha256:64483f3496c1373bfd55348e88694d1c4d0c9b660dee6bfef5e12f43b9933b30 1.20kB / 1.20kB            0.0s
 => => sha256:881afbae521c910f764f7187dbfbca3cc10c26f8bafa458c76dda009a901c29d 945B / 945B                0.0s
 => => sha256:13b66b487594a1f2b75396013bc05d29d9f527852d96c5577cc4f187559875d0 3.31kB / 3.31kB            0.0s
 => => sha256:2e6e20c8e2e69fa5c3fcc310f419975cef5fbeb6f7f2fe1374071141281b6a06 70.69MB / 70.69MB          0.9s
 => => sha256:0551a797c01db074ab0233ceb567e66b8ebdcb9de9a2e7baa36d57dfbca463a3 72.66kB / 72.66kB          0.1s
 => => extracting sha256:2e6e20c8e2e69fa5c3fcc310f419975cef5fbeb6f7f2fe1374071141281b6a06                 2.8s
 => => extracting sha256:0551a797c01db074ab0233ceb567e66b8ebdcb9de9a2e7baa36d57dfbca463a3                 0.0s
 => => extracting sha256:512123a864da5e2a62949e65b67106292c5c704eff90cac2b949fc8d7ac1e58e                 0.0s
 => [internal] load build context                                                                         0.0s
 => => transferring context: 34.15kB                                                                      0.0s
 => [2/5] RUN apt-get update &&     apt-get -y install python gunicorn python-flask                      29.9s
 => [3/5] RUN mkdir /srv/hello-world                                                                      0.4s 
 => [4/5] COPY . /srv/hello-world                                                                         0.1s 
 => [5/5] WORKDIR /srv/hello-world                                                                        0.0s 
 => exporting to image                                                                                    0.5s 
 => => exporting layers                                                                                   0.5s 
 => => writing image sha256:5de507c26f8a19e551cf039c5805c670d0efc75a9ce373d8b64eca6502bc79fd              0.0s 
 => => naming to docker.io/library/hello-world-container                                                  0.0s
gavannitsales@ubuntu22:~/GCRsample/hello-world$                       

コンテナ動くか確認

ビルドした結果使ってコンテナ動かす。
常用してるgcpのプロジェクトではcompose使ってるからdocker単体ではほぼ使わん。久しぶりにdocker runした。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ docker run -p 80:8000 hello-world-container
2023-04-29 21:05:05 [1] [INFO] Starting gunicorn 17.5
2023-04-29 21:05:05 [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
2023-04-29 21:05:05 [1] [INFO] Using worker: sync
2023-04-29 21:05:05 [11] [INFO] Booting worker with pid: 11
2023-04-29 21:05:52 [1] [CRITICAL] WORKER TIMEOUT (pid:11)
2023-04-29 21:05:52 [1] [CRITICAL] WORKER TIMEOUT (pid:11)
2023-04-29 21:05:52 [14] [INFO] Booting worker with pid: 14

はい見えた。

gvis-gke-memo02

GCR(Container Registory)への登録

次にGCRやってく。
参考にさせてもらったページ。作者さんありがとう。

【GCP入門編・第8回】 Container Registry での Docker イメージの使用方法! | 株式会社トップゲート
Container Registry に自分で作成したコンテナイメージを登録し、 Google Container Engine にデプロイする方法を解説します。

このページ少し内容が古いからアレンジが必要。

さっき、ローカルで作ったdockerのイメージがあることを確認。

pythonでhello worldって表示するだけなんやけど245MBあって、けっこうデカいなぁ。ついでにdockerのバージョンは23を再確認。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ docker images 
REPOSITORY              TAG       IMAGE ID       CREATED          SIZE
hello-world-container   latest    5de507c26f8a   19 minutes ago   245MB
gavannitsales@ubuntu22:~/GCRsample/hello-world$ docker -v
Docker version 23.0.5, build bc4487a
gavannitsales@ubuntu22:~/GCRsample/hello-world$ 

これをGCRにpushしてく。

非推奨について(gcloud docker)

dockerのバージョン18.3以降はgcloud dockerがサポートされず。
非推奨の予告にあった。

非推奨の予告  |  Container Registry のドキュメント  |  Google Cloud

pushしてくときの方法が参考にしたページとは変わってて、gcrに登録するために公式ページ参考にした。

イメージの push と pull  |  Container Registry のドキュメント  |  Google Cloud

同じようなことをしている方がいて、これも参考にさせてもらった。
作者さんありがとう。

ビルドしたdockerイメージをGoogle Container Registryにpushする - Qiita
Docker Engine 18.03から手順が変わっているようで、少しハマったので個人の備忘として。公式ナレッジ…

こっからやってみる。

GCRのための認証(gcloud auth login)

gcpの認証しとく。
ブラウザで認証画面開けってあるから、認証コードをコピーして貼り付ける。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ gcloud auth login

You are running on a Google Compute Engine virtual machine.
It is recommended that you use service accounts for authentication.

You can run:

  $ gcloud config set account `ACCOUNT`

to switch accounts if necessary.

Your credentials may be visible to others with access to this
virtual machine. Are you sure you want to authenticate with
your personal account?

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

Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fsdk.cloud.google.com%2Fauthcode.html&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=5kI8tuy5M5tkgodbf44G5EXt6DSVcN&prompt=consent&access_type=offline&code_challenge=n1FnysifOhZJ4q1NT1koimVlQ9q0ig3wDP5qlpXFRqk&code_challenge_method=S256

Enter authorization code: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

You are now logged in as [gavannitsales@gmail.com].
Your current project is [fourth-elixir-383118].  You can change this setting by running:
  $ gcloud config set project PROJECT_ID
gavannitsales@ubuntu22:~/GCRsample/hello-world$

docker認証ヘルパーに登録(gcloud auth configure-docker)

gcloudをdocker認証ヘルパーに登録しとく。
再実行したいときは、jsonファイル削除しておいてもええ。
削除しとかない場合はwarning出るけど無視しといてもええ。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ gcloud auth configure-docker
Adding credentials for all GCR repositories.
WARNING: A long list of credential helpers may cause delays running 'docker build'. We recommend passing the registry name to configure only the registry you are using.
After update, the following will be written to your Docker config file located at 
[/home/gavannitsales/.docker/config.json]:
 {
  "credHelpers": {
    "gcr.io": "gcloud",
    "us.gcr.io": "gcloud",
    "eu.gcr.io": "gcloud",
    "asia.gcr.io": "gcloud",
    "staging-k8s.gcr.io": "gcloud",
    "marketplace.gcr.io": "gcloud"
  }
}

Do you want to continue (Y/n)?  

Docker configuration file updated.
gavannitsales@ubuntu22:~/GCRsample/hello-world$ ls -l /home/gavannitsales/.docker
total 8
drwx------ 5 gavannitsales gavannitsales 4096 Apr 29 20:53 buildx
-rw------- 1 gavannitsales gavannitsales  204 Apr 29 21:28 config.json
gavannitsales@ubuntu22:~/GCRsample/hello-world$

ローカルイメージにタグ付けする。
今はv1.0とかつけとく。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ docker tag hello-world-container gcr.io/fourth-elixir-383118/hello-world-container:v1.0
gavannitsales@ubuntu22:~/GCRsample/hello-world$ docker images 
REPOSITORY                                          TAG       IMAGE ID       CREATED       SIZE
hello-world-container                               latest    5de507c26f8a   2 hours ago   245MB
gcr.io/fourth-elixir-383118/hello-world-container   v1.0      5de507c26f8a   2 hours ago   245MB
gavannitsales@ubuntu22:~/GCRsample/hello-world$

GCRに登録(docker push)

次にpushしてgcrに登録する。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ docker push gcr.io/fourth-elixir-383118/hello-world-container:v1.0
The push refers to repository [gcr.io/fourth-elixir-383118/hello-world-container]
5f70bf18a086: Pushed 
76587561c5b7: Pushed 
16c5158656f7: Pushed 
fdbd8112be4a: Pushed 
83109fa660b2: Layer already exists 
30d3c4334a23: Layer already exists 
f2fa9f4cf8fd: Layer already exists 
v1.0: digest: sha256:fe215a34dc5b5ea4cc1f22c809798e507562daaf9085e1a8304d91d515758554 size: 1779
gavannitsales@ubuntu22:~/GCRsample/hello-world$

ここまで行けたら登録結果が見える。
おお、行けたやん。

gvis-gke-memo02

GCRに登録するとバケットがcloud storageに自動で作られる。

docker imagesってやったときに見える内容に似てる。

gvis-gke-memo02

ローカルのimagesからいったん作ったイメージを削除し、さっきpushしたイメージをpullして動かしてみる。

 gavannitsales@ubuntu22:~/hoge$ docker images 
 REPOSITORY                                          TAG       IMAGE ID       CREATED       SIZE
 hello-world-container                               latest    5de507c26f8a   2 hours ago   245MB
 gcr.io/fourth-elixir-383118/hello-world-container   v1.0      5de507c26f8a   2 hours ago   245MB
 gavannitsales@ubuntu22:~/hoge$ docker rmi gcr.io/fourth-elixir-383118/hello-world-container:v1.0
 Untagged: gcr.io/fourth-elixir-383118/hello-world-container:v1.0
 Untagged: gcr.io/fourth-elixir-383118/hello-world-container@sha256:fe215a34dc5b5ea4cc1f22c809798e507562daaf9085e1a8304d91d515758554
 gavannitsales@ubuntu22:~/hoge$ docker images 
 REPOSITORY              TAG       IMAGE ID       CREATED       SIZE
 hello-world-container   latest    5de507c26f8a   2 hours ago   245MB
 gavannitsales@ubuntu22:~/hoge$ 
 gavannitsales@ubuntu22:~/hoge$ 
 gavannitsales@ubuntu22:~/hoge$ docker pull gcr.io/fourth-elixir-383118/hello-world-container:v1.0
 v1.0: Pulling from fourth-elixir-383118/hello-world-container
 Digest: sha256:fe215a34dc5b5ea4cc1f22c809798e507562daaf9085e1a8304d91d515758554
 Status: Downloaded newer image for gcr.io/fourth-elixir-383118/hello-world-container:v1.0
 gcr.io/fourth-elixir-383118/hello-world-container:v1.0
 gavannitsales@ubuntu22:~/hoge$ docker images 
 REPOSITORY                                          TAG       IMAGE ID       CREATED       SIZE
 hello-world-container                               latest    5de507c26f8a   2 hours ago   245MB
 gcr.io/fourth-elixir-383118/hello-world-container   v1.0      5de507c26f8a   2 hours ago   245MB
 gavannitsales@ubuntu22:~/hoge$ 
 gavannitsales@ubuntu22:~/hoge$ docker run -p 80:8000 gcr.io/fourth-elixir-383118/hello-world-container:v1.0
 2023-04-29 22:52:54 [1] [INFO] Starting gunicorn 17.5
 2023-04-29 22:52:54 [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
 2023-04-29 22:52:54 [1] [INFO] Using worker: sync
 2023-04-29 22:52:54 [11] [INFO] Booting worker with pid: 11

同じようにブラウザで表示できた。

gvis-gke-memo02

GKEで動かす

GCRに登録したアプリをGKEで動かしてみる。

クラスタ作成甘くない

まずはクラスタ作成して接続。

gavannitsales@ubuntu22:~/gcloud$ gcloud config set project fourth-elixir-383118
Updated property [core/project].
gavannitsales@ubuntu22:~/gcloud$ 
gavannitsales@ubuntu22:~/gcloud$ gcloud config set compute/zone us-central1-c
Updated property [compute/zone].
gavannitsales@ubuntu22:~/gcloud$ 
gavannitsales@ubuntu22:~/gcloud$ gcloud container clusters create nariCluster --num-nodes=3
Default change: VPC-native is the default mode during cluster creation for versions greater than 1.21.0-gke.1500. To create advanced routes based clusters, please pass the `--no-enable-ip-alias` flag
Default change: During creation of nodepools or autoscaling configuration changes for cluster versions greater than 1.24.1-gke.800 a default location policy is applied. For Spot and PVM it defaults to ANY, and for all other VM kinds a BALANCED policy is used. To change the default values use the `--location-policy` flag.
Note: Your Pod address range (`--cluster-ipv4-cidr`) can accommodate at most 1008 node(s).
Creating cluster hello-world in us-central1-c... Cluster is being deployed...⠛       

なんでか知らんけど、クラスタ作ったときにwarning出てgoogle-cloud-sdk-gke-gcloud-auth-pluginあらへんって怒られたからインストールしようとした。

 # apt-get update && apt-get install google-cloud-cli-gke-gcloud-auth-plugin
 …
 Reading package lists... Done
 Building dependency tree
 Reading state information... Done
 E: Unable to locate package google-cloud-cli-gke-gcloud-auth-plugin

同じようなこと悩んでるときの対処方法がgithubにあった。

Unable to use KubeCTL with Google Cloud CLI: gke-gcloud-auth-plugin is not installed · Issue #6778 · actions/runner-images
Description During the last few days, suddenly all pipelines started to fail when trying to run kubectl commands. The er...

apt-getの参照先追加したらええみたいやったから、対処してみた。

root@ubuntu22:~# apt-get update 
Hit:1 http://us-central1.gce.archive.ubuntu.com/ubuntu jammy InRelease
Hit:2 http://us-central1.gce.archive.ubuntu.com/ubuntu jammy-updates InRelease                                
Hit:3 http://us-central1.gce.archive.ubuntu.com/ubuntu jammy-backports InRelease                              
Hit:5 https://download.docker.com/linux/ubuntu jammy InRelease                                                
Hit:4 https://packages.cloud.google.com/apt kubernetes-xenial InRelease                                       
Get:6 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]                                     
Fetched 110 kB in 1s (135 kB/s)    
Reading package lists... Done
W: https://apt.kubernetes.io/dists/kubernetes-xenial/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.
root@ubuntu22:~# 
root@ubuntu22:~# 
root@ubuntu22:~# cat /etc/apt/sources.list.d/
docker.list      kubernetes.list  
root@ubuntu22:~# cat /etc/apt/sources.list.d/kubernetes.list 
deb https://apt.kubernetes.io/ kubernetes-xenial main
root@ubuntu22:~# echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main
root@ubuntu22:~# cat /etc/apt/sources.list.d/kubernetes.list 
deb https://apt.kubernetes.io/ kubernetes-xenial main
root@ubuntu22:~# curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
100  1210  100  1210    0     0   8948      0 --:--:-- --:--:-- --:--:--  8962
OK
root@ubuntu22:~#
root@ubuntu22:~# sudo apt-get install google-cloud-sdk-gke-gcloud-auth-plugin
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  google-cloud-sdk-gke-gcloud-auth-plugin
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 3129 kB of archives.
After this operation, 11.0 MB of additional disk space will be used.
Get:1 https://packages.cloud.google.com/apt cloud-sdk/main amd64 google-cloud-sdk-gke-gcloud-auth-plugin amd64 428.0.0-0 [3129 kB]
Fetched 3129 kB in 0s (17.5 MB/s)                                
Selecting previously unselected package google-cloud-sdk-gke-gcloud-auth-plugin.
(Reading database ... 101371 files and directories currently installed.)
Preparing to unpack .../google-cloud-sdk-gke-gcloud-auth-plugin_428.0.0-0_amd64.deb ...
Unpacking google-cloud-sdk-gke-gcloud-auth-plugin (428.0.0-0) ...
Setting up google-cloud-sdk-gke-gcloud-auth-plugin (428.0.0-0) ...
Scanning processes...                                                                                          
Scanning linux images...                                                                                       

Running kernel seems to be up-to-date.

No services need to be restarted.

No containers need to be restarted.

No user sessions are running outdated binaries.

No VM guests are running outdated hypervisor (qemu) binaries on this host.
root@ubuntu22:~# 

クラスタ作成やりなおし

気を取り直してクラスタ作りなおし。
何回も打鍵めんどうやから、.shに書いた。

クラスタは作るのに5分ぐらい待つ。
Pod起動がうまく行って検証するまで3回ぐらいクラスタ作り直した。

gavannitsales@ubuntu22:~$ cat connectGcloud.sh 
gcloud config set project fourth-elixir-383118
gcloud config set compute/zone us-central1-a
gcloud projects describe fourth-elixir-383118

gavannitsales@ubuntu22:~$ 
gavannitsales@ubuntu22:~$ sh ./connectGcloud.sh 
Updated property [core/project].
Updated property [compute/zone].
createTime: '2023-04-08T18:24:56.947Z'
lifecycleState: ACTIVE
name: gvis-7502
projectId: fourth-elixir-383118
projectNumber: '225919338029'
gavannitsales@ubuntu22:~$ 
gavannitsales@ubuntu22:~$ cat makeGke.sh 
gcloud container clusters create narigke --num-nodes=3

gavannitsales@ubuntu22:~$ sh ./makeGke.sh 
Default change: VPC-native is the default mode during cluster creation for versions greater than 1.21.0-gke.1500. To create advanced routes based clusters, please pass the `--no-enable-ip-alias` flag
Default change: During creation of nodepools or autoscaling configuration changes for cluster versions greater than 1.24.1-gke.800 a default location policy is applied. For Spot and PVM it defaults to ANY, and for all other VM kinds a BALANCED policy is used. To change the default values use the `--location-policy` flag.
Note: Your Pod address range (`--cluster-ipv4-cidr`) can accommodate at most 1008 node(s).
Creating cluster narigke in us-central1-a... Cluster is being health-checked (master is healthy)...done.      
Created 
https://container.googleapis.com/v1/projects/fourth-elixir-383118/zones/us-central1-a/clusters/narigke
. To inspect the contents of your cluster, go to: https://console.cloud.google.com/kubernetes/workload_/gcloud/us-central1-a/narigke?project=fourth-elixir-383118 kubeconfig entry generated for narigke. NAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUS narigke us-central1-a 1.25.7-gke.1000 34.71.84.23 e2-medium 1.25.7-gke.1000 3 RUNNING gavannitsales@ubuntu22:~$

クラスタの認証情報取得して接続

認証情報取得して、作ったクラスタに接続する。

gavannitsales@ubuntu22:~$ gcloud container clusters get-credentials narigke
Fetching cluster endpoint and auth data.
kubeconfig entry generated for narigke.
gavannitsales@ubuntu22:~$ 

Pod起動

Podを起動する。

クラスタ作ってすぐ実行したらcouldn't get resource list for metrics.k8s.io/v1beta1: the server is currently unable to handle the requestって表示されることあるけど起動はできる。

gavannitsales@ubuntu22:~$ kubectl run hello-world --image=gcr.io/fourth-elixir-383118/hello-world-container:v1.0 --port=8000
pod/hello-world created
gavannitsales@ubuntu22:~$ kubectl get pod
NAME          READY   STATUS    RESTARTS   AGE
hello-world   1/1     Running   0          10m
gavannitsales@ubuntu22:~$ 

GKEでワークロード画面確認すると、起動した。

gvis-gke-memo02

外部接続のためにロードバランス

Pod起動の次はservice作成して外部接続できるようにする。
コンテナのポート8000を、ポート80で公開する。
LoadBalancer Ingressって書いてあるIPアドレスをブラウザで開いてみる。

gavannitsales@ubuntu22:~/GCRsample/hello-world$ kubectl expose pod/hello-world --port=80 --target-port=8000 --type=LoadBalancer
service/hello-world exposed
gavannitsales@ubuntu22:~/GCRsample/hello-world$ kubectl describe service/hello-world
Name:                     hello-world
Namespace:                default
Labels:                   run=hello-world
Annotations:              cloud.google.com/neg: {"ingress":true}
Selector:                 run=hello-world
Type:                     LoadBalancer
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.112.5.155
IPs:                      10.112.5.155
LoadBalancer Ingress:     35.232.237.56
Port:                     <unset>  80/TCP
TargetPort:               8000/TCP
NodePort:                 <unset>  30641/TCP
Endpoints:                10.108.2.8:8000
Session Affinity:         None
External Traffic Policy:  Cluster
Events:
  Type    Reason                Age   From                Message
  ----    ------                ----  ----                -------
  Normal  EnsuringLoadBalancer  19s   service-controller  Ensuring load balancer
gavannitsales@ubuntu22:~/GCRsample/hello-world$ 

サービス公開できた。
エンドポイントってあるところをブラウザで開いてみる。

gvis-gke-memo02

はい、表示できた。

gvis-gke-memo02

ログの見え方

ポッドのログ見ると「イベント」ってところにコンテナとかロードバランサの作成・削除が見える。
何度か作り直すとわかるんやけど、外部接続するIPアドレスはコロコロ変わる。

gvis-gke-memo02

ローカルで動かしたときに見えたログはPodのログ画面で見える。
ログはjson形式で冗長な上、表示遅い。
内容がcriticalのものはええけど、infoのものでも左端の赤い表示になるのは気に入らんなぁ。

gvis-gke-memo02
タイトルとURLをコピーしました