dshimizu/blog

アルファ版

kubeadmを使ってさくらのVPS×3台でマスター1台、ノード2台のk8sクラスターを作成してみた

TL;DR

kubeadmを使ってさくらのVPS3台でのk8sシングルマスタークラスターを作成してみたのでメモ書き。 基本的にドキュメントに書かれているコマンドをベースにすればOKだが、少し違うのは、ドキュメントではマスター兼ワーカーが1台、ノード1台の2台クラスターとなっていると思われるが、この記事ではマスター1台、ノード2台の3台クラスターとするところ。

K8s関連のコンポーネントを利用するためにさくらのVPSにL2スイッチとプライベートネットワークを追加しているがネットワーク回りをあまり理解できておらず、正しいことをやっているのか自身がない。

k8sシングルマスタークラスター構築手順

環境

  • プラットフォーム さくらのVPS 3台
  • VPSは2つのNICを持たせる。1つはデフォルトで割り当てられているインターネットに接続されるネットワーク。もう1つはAPIサーバ等のローカル通信用のプライベートネットワーク。それとは別にコンテナ用のネットワークセグメントを利用する。
    • グローバルIP (デフォルトで割り当てられているIP)
    • 10.1.0.0/24 (プライベートネットワーク)
  • OS: Ubuntu 18.04
  • kubernatis: 1.17.1
  • Docker: 19.03.5

事前準備

さくらのVPSのローカルネットワークの設定

さくらのVPSはデフォルトだとグローバルIPが割り当てられており、インターネットを介した通信を行う形となるが、別途L2スイッチを作成してさくらのVPSを接続させてローカル通信を行うことができる。 そのため、k8s用にローカルネットワークを作成して、3台のVPSを接続させておく。

手順は下記を参照のこと。

Dockerのインストール

3台のサーバにDockerをインストールする。

$ sudo apt-get update
$ sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo apt-key fingerprint 0EBFCD88
$ sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
$ sudo apt-get update
$ sudo apt-get install docker-ce docker-ce-cli containerd.io
kubeadmのインストール

3台のサーバにkubeadmをインストールする必要がある。

curlとaptのhttps通信をサポートするためのパッケージをインストールする。

$ sudo apt-get update && sudo apt-get install -y apt-transport-https curl

k8sリポジトリGnuPG 公開鍵を登録する。

$ % curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
OK

APTリポジトリを登録する。

$ sudo sh -c "cat </etc/apt/sources.list.d/kubernetes.list
deb https://apt.kubernetes.io/ kubernetes-xenial main
EOF"

パッケージリストを更新する。

$ sudo apt-get update

kubelet kubeadm kubectlのパッケージをインストールする。

$ sudo apt-get install -y kubelet kubeadm kubectl

apt upgradeでパッケージが意図せず更新されないようにバージョンを固定する。

$ sudo apt-mark hold kubelet kubeadm kubectl

k8sの設定

kubeadmが使用するkubeletのパラメータ設定

3台のサーバ全てで/var/lib/kubelet/kubeadm-flags.envを編集する。 KUBELET_KUBEADM_ARGS--node-ip=xxx.xxx.xxx.xxxを付与する。 node-ipは各サーバのプライベートIPを指定する。

KUBELET_KUBEADM_ARGS="--cgroup-driver=cgroupfs --network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.1 --resolv-conf=/run/systemd/resolve/resolv.conf --node-ip=10.1.0.XXX"

設定を反映する。

$ sudo systemctl daemon-reload && sudo systemctl restart kubelet
マスターノードの初期化

以下を実行する。 init移行はオプション。 --pod-network-cidrは後述のPodネットワーク・アドオンでFlannelを使う場合のアドレスレンジとして10.244.0.0/16が必須であるため、付与している。 --apiserver-advertise-addressAPIサーバのアドレスを明示的に指定している。

$ sudo kubeadm init --apiserver-advertise-address=10.1.0.129 --pod-network-cidr=10.244.0.0/16

以下のような出力が得られる。 最後のほうの情報をメモしておく。

W0121 05:37:12.660117   12512 validation.go:28] Cannot validate kube-proxy config - no validator is available
W0121 05:37:12.660166   12512 validation.go:28] Cannot validate kubelet config - no validator is available
[init] Using Kubernetes version: v1.17.1
[preflight] Running pre-flight checks
        [WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver. The recommended driver is "systemd". Please follow the guide at https://kubernetes.io/docs/setup/cri/
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [***-***-*****.vs.sakura.ne.jp kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 10.1.0.129]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [***-***-*****.vs.sakura.ne.jp localhost] and IPs [10.1.0.129 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [***-***-*****.vs.sakura.ne.jp localhost] and IPs [10.1.0.129 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
W0121 05:37:15.962126   12512 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[control-plane] Creating static Pod manifest for "kube-scheduler"
W0121 05:37:15.963418   12512 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 34.505362 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.17" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node ***-***-*****.vs.sakura.ne.jp as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node ***-***-*****.vs.sakura.ne.jp as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: a****k.2**************7
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes control-plane has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 10.1.0.129:6443 --token a****k.2**************7 \
    --discovery-token-ca-cert-hash sha256:7**************************************************************f

kubeadm join の部分はワーカーノードの追加で必要となるのでメモしておく。 忘れても24時間以内なら以下で確認できる。

$ sudo kubeadm token list
TOKEN                     TTL         EXPIRES                USAGES                   DESCRIPTION                                                EXTRA GROUPS
a****k.2**************7   23h         2020-MM-DDTHH:mm:ssSZ   authentication,signing                                                        system:bootstrappers:kubeadm:default-node-token

ハッシュ値は以下で算出できる。

$ openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'
7e72d2fff35716f8cbc4c6c0e066afce4ff19c4326d4c6aaf9a9d9d452f0063f

24時間を過ぎた場合は新しくtokenとハッシュ値を生成する必要がある。

まずはk8sを操作する(コマンドを実行する)ための定義ファイルをコピーする。

$ mkdir -p $HOME/.kube
$ sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
$ sudo chown $(id -u):$(id -g) $HOME/.kube/config

または以下でも良い(が、ファイルパーミッションの調整が必要かもしれない)。

$ export KUBECONFIG=/etc/kubernetes/admin.conf
Podネットワークアドオンのインストール

Podが通信できるようにするためのネットワーク・アドオンというものをインストールする必要がある。 ネットワーク・アドオンは複数あっていずれか一つをインストールする必要がある。

ここではFlannelというものを使う。 特に他のネットワーク・アドオンと比較したりはしていないので良し悪しは不明。

Flannelのymlを取得する。

$ wget https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

インストールする。

$ sudo kubectl apply -f kube-flannel.yml
podsecuritypolicy.policy/psp.flannel.unprivileged created
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.apps/kube-flannel-ds-amd64 created
daemonset.apps/kube-flannel-ds-arm64 created
daemonset.apps/kube-flannel-ds-arm created
daemonset.apps/kube-flannel-ds-ppc64le created
daemonset.apps/kube-flannel-ds-s390x created
コントロールプレーンノードの隔離

マスターはマスターのみの役割とさせておくためここでは実施しない。

クラスターへのノードの追加

追加するノードとなるサーバへもdockerとkube*コマンド(少なくともkubeadmとkubectl)とDockerをインストールする。 手順は上記を参照のこと。

追加するノード上で以下を実行する。

$ sudo kubeadm join 10.1.0.129:6443 --token a****k.2**************7 --discovery-token-ca-cert-hash sha256:7**************************************************************f
W0121 05:41:41.389375   21207 join.go:346] [preflight] WARNING: JoinControlPane.controlPlane settings will be ignored when control-plane flag is not set.
[preflight] Running pre-flight checks
        [WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver. The recommended driver is "systemd". Please follow the guide at https://kubernetes.io/docs/setup/cri/
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[kubelet-start] Downloading configuration for the kubelet from the "kubelet-config-1.17" ConfigMap in the kube-system namespace
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...

This node has joined the cluster:
* Certificate signing request was sent to apiserver and a response was received.
* The Kubelet was informed of the new secure connection details.

Run 'kubectl get nodes' on the control-plane to see this node join the cluster.

状態を確認する。

$ kubectl get node
NAME          STATUS   ROLES    AGE     VERSION
Hostname01    Ready    master   6m39s   v1.17.0
Hostname02    Ready       11s     v1.17.0

追加する2つ目のノードでも同様に以下を実行する。

$ sudo kubeadm join 10.1.0.129:6443 --token a****k.2**************7 --discovery-token-ca-cert-hash sha256:7**************************************************************f
W0121 05:43:24.389375   21207 join.go:346] [preflight] WARNING: JoinControlPane.controlPlane settings will be ignored when control-plane flag is not set.
[preflight] Running pre-flight checks
        [WARNING IsDockerSystemdCheck]: detected "cgroupfs" as the Docker cgroup driver. The recommended driver is "systemd". Please follow the guide at https://kubernetes.io/docs/setup/cri/
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[kubelet-start] Downloading configuration for the kubelet from the "kubelet-config-1.17" ConfigMap in the kube-system namespace
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...

This node has joined the cluster:
* Certificate signing request was sent to apiserver and a response was received.
* The Kubelet was informed of the new secure connection details.

Run 'kubectl get nodes' on the control-plane to see this node join the cluster.

ノードの状態を確認する。

$ kubectl get nodes
NAME          STATUS   ROLES    AGE     VERSION
Hostname01    Ready    master   8m55s   v1.17.1
Hostname02    Ready       2m27s   v1.17.1
Hostname03    Ready       3s      v1.17.1

これでクラスタが完成した。

Podをデプロイする
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-testest-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx-testest
  template:
    metadata:
      labels:
        app: nginx-testest
    spec:
      containers:
      - name: nginx-container
        image: nginx:1.15.9
        ports:
        - containerPort: 80

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  labels:
    app: nginx
spec:
  selector:
    app: nginx
  type: NodePort
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
    nodePort: 30080
$ kubectl apply -f nginx.yml
service/nginx-service created
deployment.apps/nginx-deployment created

マスターを除いた2台のノードへ分散して配置されていることを確認する。

$ kubectl get pods -o wide
NAME                                 READY   STATUS    RESTARTS   AGE   IP           NODE          NOMINATED NODE   READINESS GATES
nginx-deployment-65888895f5-5xpvb    1/1     Running   0          48s   10.244.2.2   Hostname02               
nginx-deployment-65888895f5-8ck5x    1/1     Running   0          48s   10.244.2.3   Hostname02               
nginx-deployment-65888895f5-tl5xc    1/1     Running   0          48s   10.244.1.2   Hostname03               

curlとかwgetでノードのグローバルIP:30080へhttpアクセスして正常に通信できれば完了。 たまに応答不能になるのがネットワークの問題なのかパフォーマンスの問題なのかわからないので調べたい。

まとめ

kubeadmを利用してマスター1台、ノード2台のkubernetesクラスタを構築したのでその時の手順をメモ書き程度に書いた。 kubeadmはk8sの構築は手軽に行えるが、k8sを構成するコンポーネントへの理解を深めるにはもう少しいろいろいじっていく必要があると感じた。

参考