とりあえずKubenetesのページにある内容をローカルにて試してみたいと思います。
一部、内容変えてます(Ingressの設定と動作確認)。
前提
- Mac上
- minikubeがインストールされ、実行されている
準備
Ingressアドオンの有効化
minikube addons enable ingress
以下のコマンドで有効化を確認します。
minikube addons list
kubectl get pods -n kube-system でも確認できます。
やることの確認
参考する記事で実現する内容は以下のような内容のようです。
- web podとserviceをデプロイ
- web2 podをserviceをデプロイ
- Ingressをデプロイし、/でwebに、/v2でweb2にアクセスするように設定
図式化すると下記のような感じ。
Web(1) PodとServiceの作成
デプロイ
準備されたイメージを利用してDeploymentを作成し、そのままexpose(Serviceの作成)。
kubectl create deployment web --image=gcr.io/google-samples/hello-app:1.0
kubectl expose deployment web --type=NodePort --port=8080
動作確認
以下のコマンドを実行すると勝手にWebが開くと思います。
minikube service web
私の環境では下記のような内容が表示されました(Versionが1.0となってるところがミソ?)。
Hello, world!
Version: 1.0.0
Hostname: web-84fb9498c7-nwh2n
Ingressの作成
ではIngressを作成してみます。
容易されたYamlもあるのですが、少しカスタムしてみます。
host名で利用してるhello-world.infoが実在するもののようなので、.localに変更するだけですが。。。
yamlの作成と記述
作業場はどこでもいいのですが、yamlを生成。
生成
touch example-ingress.yaml
記述
以下のように記述します。
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: hello-world.local
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 8080
Yamlを適用(実際にIngressを作成)
kubectl apply -f ./example-ingress.yaml
動作確認
Ingressの名前解決がhost名ベースみたいなので、/etc/hostsにhost名を記述します。
sudo vi /etc/hosts
以下を追加。
127.0.0.1 hello-world.local
記事ではkubectl get ingressで取得できるIPを設定していますが、うまくいきませんでした(なお、addressが取得できまでには少々時間がかかるみたいです)。
Ingressとホストを連携。
minikube tunnel
tunnelコマンドはServiceのtypeがLoadBlancerだったり、Ingress経由でホストにアクセスできるようになるみたい。
以下にアクセスして確認。
先程のwebと同じ内容が表示されればOK。
Web2 PodとServiceの作成
別のPodを起動して公開します。
基本webと同じですが、表示されるVersionが2.0になってるみたいです。
kubectl create deployment web2 --image=gcr.io/google-samples/hello-app:2.0
kubectl expose deployment web2 --port=8080 --type=NodePort
IngressのYamlを編集
- path: /v2 以下を追加します。
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: hello-world.local
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 8080
- path: /v2
pathType: Prefix
backend:
service:
name: web2
port:
number: 8080
内容の反映
編集したものを反映します。
kubectl apply -f ./example-ingress.yaml
動作確認
動作確認してみます。
minikube tunnel
以下でアクセスしてみます。
http://hello-world.local/
http://hello-world.local/v2
/でアクセス
Hello, world!
Version: 1.0.0
Hostname: web-84fb9498c7-nwh2n
/v2でアクセス
Versionが2.0.0になっていますね。Ingressがルーティングしてくれてるみたいです。
Hello, world!
Version: 2.0.0
Hostname: web2-7df4dcf77b-4rb72
片付け
動作確認終わったので片付けです。
kubectl delete ingress example-ingress
kubectl delete service web web2
kubectl delete deployment web web2