【Kubernetes】Raspberry Piでクラスタ構築してみよう

# クラスタ構築をしてみる

Kubernetesを業務で使用していますが、まだまだKubernetesの理解が足りないことを日々感じます。
少しずつ
なので今回はRaspberry Piを使用してクラスタ構築を行うことにしました。

## 参考にした記事
下記をそのまま参考にさせていただきました！
最高の記事ありがとうございます！

[Raspberry PiでおうちKubernetes構築【論理編】](https://qiita.com/go_vargo/items/29f6d832ea0a289b4778#sd%E3%81%B8%E3%81%AEos%E3%82%A4%E3%83%A1%E3%83%BC%E3%82%B8%E6%9B%B8%E8%BE%BC%E3%81%BF-by-macos)
[Raspberry PiでおうちKubernetes構築【物理編】](https://qiita.com/go_vargo/items/d1271ab60f2bba375dcc)

## 準備したもの
- Raspberry Pi 4

下記で準備してるものとほぼ変わらないです！
[Raspberry PiでおうちKubernetes構築【物理編】](https://qiita.com/go_vargo/items/d1271ab60f2bba375dcc)


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/148392/557499e3-05a2-e200-6f47-69283a3658ef.png)


## 実施手順
- Raspberry PiにOSインストール
- Host名変更
- Dcokerインストール
- Kuberntesインストール


## Raspberry PiにOSインストール

### Raspberry Pi OSイメージのダウンロード
下記ページに遷移し、`Raspbian Buster Lite`のzipをダウンロードしました。
[Raspbian](https://www.raspberrypi.org/downloads/raspbian/)


### SDカードへOSを書き込む
SDカードをさした後、SDカードの情報が表示されることを確認します。

```
$ diskutil list
...
...
/dev/disk2 (external, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     FDisk_partition_scheme                        *31.5 GB    disk2
   1:             Windows_FAT_32 boot                    45.9 MB    disk2s1
   2:                      Linux                         2.9 GB     disk2s2
```

#### アンマウントする
ディスクユーティリティで、**装置**の名前を確認してから、下記コマンドを実行します。

```
$ sudo diskutil umount /dev/disk3s1
Volume NO NAME on disk3s1 unmounted
```

```
$ sudo dd bs=1m if=2019-09-26-raspbian-buster-lite.img of=/dev/rdisk3 conv=sync
2144+0 records in
2144+0 records out
2248146944 bytes transferred in 177.293786 secs (12680348 bytes/sec)
```

#### sshでログインできるようにする

```
$ cd /Volumes/boot
$ touch ssh
```

```
$ vim /Volumes/boot/cmdline.txt

# 追加したコード
cgroup_enable=cpuset cgroup_memory=memory　cgroup_memory=1
```

※下記記事では、`rootwait quiet init=/usr/lib/raspi-config/init_resize.sh`の部分も追記していましたが、`Raspberry Pi 4`ではすでに記載がありました！
[Raspberry Pi cgroupsの設定 by MacOS](https://qiita.com/go_vargo/items/29f6d832ea0a289b4778#raspberry-pi-cgroups%E3%81%AE%E8%A8%AD%E5%AE%9A-by-macos)


## Host名変更

```
# ログインする
$ slogin pi@raspberrypi.local

# パスワードを変更する
$ sudo passwd pi

# apt-getを更新する
$ sudo apt-get -y update
$ sudo apt-get -y upgrade

# おまじないらしい....
$ sudo dphys-swapfile swapoff
$ sudo dphys-swapfile uninstall
$ sudo update-rc.d dphys-swapfile remove
```

### hostnameを変更する

```
$ sudo vi /etc/hostname

# 変更前
raspberrypi

# 変更後
k8sraspberrypi
```

### hostを書き換える

```
pi@raspberrypi:~ $ vi /etc/hosts
127.0.0.1	localhost
::1		localhost ip6-localhost ip6-loopback
ff02::1		ip6-allnodes
ff02::2		ip6-allrouters

-127.0.1.1  raspberrypi
+127.0.1.1  k8sraspberrypi
```

`sudo reboot`

### 最終確認
もろもろ設定が終わると、下記のようにログインできるはず！

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/148392/d3a077c1-b581-468a-c18a-3d118b10c35d.png)


## Dockerインストール
下記をそのまま実行！
[Dockerインストール](https://qiita.com/go_vargo/items/29f6d832ea0a289b4778#docker%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB)

## Kubernetesインストール
下記をそのまま実行！
[Kubernetesインストール](https://qiita.com/go_vargo/items/29f6d832ea0a289b4778#kubernetes%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB)


## Masterのノードを構築
### イニシャライズ

``` 
pi@sanoraspberrypi:~ $ sudo kubeadm init --pod-network-cidr=[IP]/24
W1215 06:25:08.829509    4530 validation.go:28] Cannot validate kube-proxy config - no validator is available
W1215 06:25:08.830023    4530 validation.go:28] Cannot validate kubelet config - no validator is available
[init] Using Kubernetes version: v1.17.0
[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 [sanoraspberrypi kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.13.5]
[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 [sanoraspberrypi localhost] and IPs [192.168.13.5 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [sanoraspberrypi localhost] and IPs [192.168.13.5 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"
W1215 06:25:49.080787    4530 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[control-plane] Creating static Pod manifest for "kube-scheduler"
W1215 06:25:49.084560    4530 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 39.006587 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 sanoraspberrypi as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node sanoraspberrypi as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[kubelet-check] Initial timeout of 40s passed.
[bootstrap-token] Using token: fidfhg.q9a7vktyif5ji05i
[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!
```
[CIDR表記とは](https://wa3.i-3-i.info/word11990.html)


#### swapのエラー対応
詳細のエラーは、取って置くのを忘れてしまったが、swapに関するエラーがでたので、下記で対応しました。

`swapoff -a`
[[ERROR Swap]: running with swap on is not supported. Please disable swap](https://github.com/kubernetes/kubeadm/issues/610)

下記を実行

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


下記コマンドを実行すると、`kube-proxy`などが作成されていることがわかります。

```
pi@sanoraspberrypi:~ $ kubectl get pods --all-namespaces
NAMESPACE     NAME                                      READY   STATUS    RESTARTS   AGE
kube-system   coredns-6955765f44-2dhr2                  0/1     Pending   0          15m
kube-system   coredns-6955765f44-tpr45                  0/1     Pending   0          15m
kube-system   etcd-sanoraspberrypi                      1/1     Running   0          15m
kube-system   kube-apiserver-sanoraspberrypi            1/1     Running   0          15m
kube-system   kube-controller-manager-sanoraspberrypi   1/1     Running   0          15m
kube-system   kube-proxy-zmgzv                          1/1     Running   0          15m
kube-system   kube-scheduler-sanoraspberrypi            1/1     Running   0          15m
```

### flannelを構築

```
pi@sanoraspberrypi:~ $ kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/2140ac876ef134e0ed5af15c65e414cf26827915/Documentation/kube-flannel.yml
podsecuritypolicy.policy/psp.flannel.unprivileged created
clusterrole.rbac.authorization.k8s.io/flannel configured
clusterrolebinding.rbac.authorization.k8s.io/flannel unchanged
serviceaccount/flannel unchanged
configmap/kube-flannel-cfg configured
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
```
[Creating a single control-plane cluster with kubeadm](https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/#pod-network)



## Workerノードを構築

`kubeadm init`コマンドを実行した際に、出力された`join`コマンドをここで実行する。

```
$ kubeadm join [出力されたIP]:6443 --token fidfhg.q9a7vktyif5ji05i \
--discovery-token-ca-cert-hash sha256:5e4179404ae86e68d72f28759b51c7a9a9b328331f121e13c38a03d630ca2722

```

## 確認
`kubectl get node`で3つnodeが確認できれば問題ありません。


## シャットダウン
`sudo shutdown -h now`

## 最終形
こんな感じでつなぎました！
本当はラック使いたかったww
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/148392/e49b1d93-afd0-31b5-3a23-921d45c5a080.png)

## 学んだこと
### Masterノードの存在
普段GKEを触っていると、Masterノードを感がる必要がないため、Masterノードから構築していくのは非常に新鮮だった。GKEを使うと非常に楽なんだが、ここら辺を理解するのにはこういう積み重ねをしていくしかないと改めて感じました！