やったこと
StatefulSet を使ってみます。
確認環境
$ k version
Client Version: version.Info{Major:"1", Minor:"16", GitVersion:"v1.16.2", GitCommit:"c97fe5036ef3df2967d086711e6c0c405941e14b", GitTreeState:"clean", BuildDate:"2019-10-15T19:18:23Z", GoVersion:"go1.12.10", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.3", GitCommit:"1e11e4a2108024935ecfcb2912226cedeafd99df", GitTreeState:"clean", BuildDate:"2020-10-14T12:41:49Z", GoVersion:"go1.15.2", Compiler:"gc", Platform:"linux/amd64"}
調査
StatefulSetは下記の1つ以上の項目を要求するアプリケーションにおいて最適です。
- 安定した一意のネットワーク識別子
- 安定した永続ストレージ
- 規則的で安全なデプロイとスケーリング
- 規則的で自動化されたローリングアップデート
first-stateful.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: my-statefulset
spec:
serviceName: nginx
replicas: 2 # by default is 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx # .spec.selector.matchLabelsの値と一致する必要があります
spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx-container
image: nginx:1.17
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes:
- ReadWriteOnce
storageClassName: "my-storage-class"
resources:
requests:
storage: 1Gi
$ k apply -f first-stateful.yaml
statefulset.apps/my-statefulset created
$ k get statefulsets
NAME READY AGE
my-statefulset 2/2 12m
$ k get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
my-statefulset-0 1/1 Running 0 11m 10.1.0.180 docker-desktop <none> <none>
my-statefulset-1 1/1 Running 0 11m 10.1.0.181 docker-desktop <none> <none>
$ k get pv
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
pvc-0ec2bcbb-1a20-46b0-8930-5fe48601a180 1Gi RWO Delete Bound default/www-my-statefulset-1 hostpath 12m
pvc-dc6cf56f-2e32-4d53-ad5e-9fa0fd9bc365 1Gi RWO Delete Bound default/www-my-statefulset-0 hostpath 12m
$ k get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
www-my-statefulset-0 Bound pvc-dc6cf56f-2e32-4d53-ad5e-9fa0fd9bc365 1Gi RWO hostpath 12m
www-my-statefulset-1 Bound pvc-0ec2bcbb-1a20-46b0-8930-5fe48601a180 1Gi RWO hostpath 12m
永続ボリュームの動作を確認
# ファイルを設置する
$ k exec -it my-statefulset-0 -- ls /usr/share/nginx/html
$ k exec -it my-statefulset-0 -- touch /usr/share/nginx/html/hoge
$ k exec -it my-statefulset-0 -- ls /usr/share/nginx/html
hoge
# Pod を削除する
$ k delete pod my-statefulset-0
pod "my-statefulset-0" deleted
$ k get pods
NAME READY STATUS RESTARTS AGE
my-statefulset-0 1/1 Running 0 47s
my-statefulset-1 1/1 Running 0 16m
# my-statefulset-0 でファイルがあることを確認する
$ k exec -it my-statefulset-0 -- ls /usr/share/nginx/html
hoge