GKEを使う - 限定公開クラスタとCloud NATでPodから外部ネットワークにアクセスする

Cloud NATを使って外部ネットワークにアクセスするまで。
内容としては前回の続きですが、今回も最後に削除をします。

Kubernetes クラスタを作る

限定公開クラスタを作成のコマンドを実行します。
以下のドキュメントのパブリック エンドポイントへ無制限にアクセス可能な限定公開クラスタの作成を選択しました。
ドキュメント:https://cloud.google.com/kubernetes-engine/docs/how-to/private-clusters

1
2
3
4
5
6
7
8
9
$ gcloud container clusters create test-cluster \
--preemptible \
--machine-type=e2-micro \
--disk-size=10 \
--enable-autoscaling --num-nodes=2 --max-nodes=3 \
--no-enable-master-authorized-networks \
--enable-ip-alias \
--enable-private-nodes \
--master-ipv4-cidr 172.16.0.32/28

ノードを確認します。

1
2
3
4
$ kubectl get node
NAME STATUS ROLES AGE VERSION
gke-test-cluster-default-pool-6121dab1-cw9m Ready <none> 22s v1.20.10-gke.1600
gke-test-cluster-default-pool-6121dab1-t8t4 Ready <none> 22s v1.20.10-gke.1600

外部ネットワークにアクセスできるようにする

限定公開クラスタは外部との通信はできません。そこでCloud NATを利用して外部ネットワークにアクセスできるようにします。
まず外部IPを取得します。

1
gcloud compute addresses create ip-test-001 --region=asia-northeast1

取得したIPアドレスを確認します。

1
2
3
$ gcloud compute addresses list
NAME ADDRESS/RANGE TYPE PURPOSE NETWORK REGION SUBNET STATUS
ip-test-001 34.146.196.91 EXTERNAL asia-northeast1 RESERVED

ルーターを作成します。
ドキュメント:https://cloud.google.com/nat/docs/using-nat

1
gcloud compute routers create test-nat-router --network=default

Cloud NAT を作成します。

1
2
3
4
5
gcloud compute routers nats create test-nat-config \
--router=test-nat-router \
--region=asia-northeast1 \
--nat-all-subnet-ip-ranges \
--nat-external-ip-pool=ip-test-001

Podからcurlを実行して外部ネットワークにアクセスできることを確認します。
inet-ip.infoは自身のIPアドレスを教えてくれます。

1
2
3
4
$ kubectl run --rm -it curl --image=curlimages/curl --restart=Never -- /bin/curl inet-ip.info  
curl: (3) URL using bad/illegal format or missing URL
34.146.196.91
pod "curl" deleted

掃除

Cloud NAT を削除します。

1
gcloud compute routers nats delete test-nat-config --router=test-nat-router

ルーターを削除します。

1
gcloud compute routers delete test-nat-router

IPアドレスを解放します。

1
gcloud compute addresses delete ip-test-001

Kubernetess クラスタを削除します。

1
gcloud container clusters delete test-cluster