【Kubernetes】Service
マイクロサービス間の分離のためにロードバランサーやネーミング、ディスカバリの機能を提供
Servive と Pod の紐付けは Label で行なう Service を定義して k8s を起動すると、その定義に基づいて各 Endpoints にトラフィックを分散するための仮想 IP アドレス Cluster IP を作成
通常は内部通信のみ
Service オブジェクトを再作成しない限り変更されない
LoadBalancer を指定すると、クラスタの外部からもアクセス可能な External IP を作成できる
Service オブジェクト
名前のついた Label セレクタを作る仕組み
Deployment と Service の作成
Deployment
code:shell
$ kubectl run alpaca-prod --image=kuard-amd64:1 --replicas=3 --port=8080 --labels="ver=1,app=alpaca,env=prod"
code:shell
$ kubectl run bandicoot-prod --image=kuard-amd64:1 --replicas=2 --port=8080 --labels="ver=1,app=bandicoot,env=prod"
Service
code:shell
$ kubectl expose deployment alpaca-prod
code:shell
$ kubectl expose deployment bandicoot-prod
デフォルトは ClusterIP
NodePort にする場合には --type=NodePort を指定
Service の確認
code:shell
$ kubectl get services -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
alpaca-prod ClusterIP 10.104.126.37 <none> 8080/TCP 73s app=alpaca,env=prod,ver=1
bandicoot-prod ClusterIP 10.102.134.153 <none> 8080/TCP 43s app=bandicoot,env=prod,ver=1
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 43h <none>
kubernetes という Service はアプリケーションから Kubernetes の API に接続し通信するために、自動的に作成されたもの
### Service DNS
- Kubernetes DNS Service
- この DNS サーバは、クラスタ内ではレプリケーションされた Service として動作
- システムコンポーネントとしてインストールされる
- 1 or 複数の DNS サーバがクラスタ内で動作
- DNS サービスはこれらのレプリカを管理する Kubernetes の Deployment として動作
`
$ kubectl get deployments --namespace=kube-system kube-dns
`
- DNS サーバをロードバランシングするための Services も動く
`
$ kubectl get services --namespace=kube-system kube-dns
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kube-dns ClusterIP 10.96.0.10 <none> 53/UDP,53/TCP,9153/TCP 31m
`
- クラスタでの DNS Service が 10.96.0.10 という IP アドレスを持っている
- /etc/resolv.conf 参照
### Readiness probe
- 追加
`
readinessProbe:
httpGet:
path: /ready
port: 8080
periodSeconds: 2
initialDelaySeconds: 0
failureThreshold: 3
successThreshold: 1
`
- 定義を変更すると Pod の再作成が行われる
- 確認
- proxy 設定
`
$ set -x ALPACA_POD (kubectl get pods -l app=alpaca -o jsonpath='{.items0.metadata.name}' ) `
- port-foawrd
`
$ kubectl port-forward $ALPACA_POD 48858:8080
`
- watch
`
$ kubectl get endpoints alpaca-prod --watch
NAME ENDPOINTS AGE
alpaca-prod 10.1.0.29:8080,10.1.0.30:8080,10.1.0.31:8080 29m
`
クラスタ外からの流入
NodePort
外部からのアクセスを受け入れる際の Service 拡張
Service の変更
code:shell
$ kubectl edit service alpaca-prod
ClusterIP => NodePort に変更
確認
code:shell
$ kubectl describe service alpaca-prod
Name: alpaca-prod
Namespace: default
Labels: app=alpaca
env=prod
ver=1
Annotations: <none>
Selector: app=alpaca,env=prod,ver=1
Type: NodePort
IP: 10.104.126.37
LoadBalancer Ingress: localhost
Port: <unset> 8080/TCP
TargetPort: 8080/TCP
NodePort: <unset> 30073/TCP
Endpoints: 10.1.0.29:8080,10.1.0.30:8080,10.1.0.31:8080
Session Affinity: None
External Traffic Policy: Cluster
Events: <none>
クラウド
--type=LoadBalancer
サンプル