https://console.cloud.google.com/kubernetes
クラスタを作成する
GCPのコンソールからkubernetesを開く。
クラスタを作成をクリック。

リージョン選択。
asia-northeast1 が東京。割高。

ノードプールからマシンタイプを変更。
最低スペックでも e2-small 推奨。
e2-microだと動かないケースがある。

gcloud設定
gcloud container clusters get-credentials [cluster-name] --region=[region name] --project [project name]
gcloud container clusters get-credentials cluster-1 --region=asia-northeast1-a --project sample-project
クラスタ名とリージョン名、プロジェクト名は随時変更する。
Dockerイメージをbuildする
cloudbuild.yaml, Dockerfile, .gcloudignore の3ファイルが必要。
cloudbuild.yaml
steps: # docker build - name: 'gcr.io/cloud-builders/docker' args: ['build', '-t', 'gcr.io/$PROJECT_ID/example', '.'] # push built images to Container Registry images: ['gcr.io/$PROJECT_ID/example']
Dockerfile
FROM node:12
COPY utils /utils
COPY dist /dist
COPY routes /routes
COPY common /common
COPY service /service
COPY model /model
COPY repository /repository
COPY app.js .
COPY package*.json ./
RUN npm install
EXPOSE 3000
CMD node app.js
動作に必要なファイルをコピーする。
.gcloudignore
アップロード対象外ファイル。指定しない場合.gitignoreを使用したりと意図しない動作をするので必ず用意する。
.DS_Store
node_modules
*.ts
*.js.map
.vscode
.env
以下のコマンドでビルド。
gcloud builds submit --config=cloudbuild.yaml .
build後はcloud storageへアップロードされcontainer registoryへ保存される。
cloud storageは都度消さないと微量の課金が発生する。
https://console.cloud.google.com/gcr
k8sへdeployする
最低でもDeploymentとNodePortの2つが必要
Deployment
デプロイを管理する。Podを作成する。
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: exammple
labels:
app: exammple
spec:
replicas: 3
selector:
matchLabels:
app: exammple
template:
metadata:
labels:
app: exammple
annotations:
appVersion: v1.0
spec:
containers:
- name: exammple
image: gcr.io/xxxx-xxxx-284602/exammple
command:
ports:
- containerPort: 3000
replicas: 作成されるpodの数。
image: 任意のコンテナレジストリのイメージの場所を指定する。
NodePort
Webサービスへアクセスできるようにする。
service.yaml
kind: Service
apiVersion: v1
metadata:
name: example-service
spec:
type: NodePort
selector:
app: example
ports:
- protocol: TCP
port: 80
targetPort: 3000
type: LoadBalancer
loadBalancerIP: "35.xxx.xxx.9"
kubectl apply -f deployment.yaml --record
kubectl apply -f service.yaml
一度でデプロイした場合一度消すかバージョンを上げないと更新されない。
kubectl delete deployment example
kubectl apply -f deployment.yaml --record
# 動作確認
IPアドレスとポートが必要。
IPアドレスはおそらくVPCネットワークから。
https://console.cloud.google.com/networking/addresses/list
ポート番号は以下
kubectl describe service example-service Name: example-service Namespace: default Labels:Annotations: kubectl.kubernetes.io/last-applied-configuration: {"apiVersion":"v1","kind":"Service","metadata":{"an... Selector: app=example Type: NodePort IP: 10.0.3.136 Port: 80/TCP TargetPort: 3000/TCP NodePort: 31095/TCP Endpoints: 10.xx.xx.11:3000,10.xx.xx.12:3000,10.xx.xx.13:3000 Session Affinity: None External Traffic Policy: Cluster Events:
Public IP:NodePort でアクセス。
アクセスできたら成功。
参考
https://trueman-developer.blogspot.com/2019/02/kubernetesk8s.html#more