2018年8月23日木曜日

raspberry pi(kubernetesの導入方法)



<材料一式>
Raspberry Pi 3 Model B                   : 3台
ヒートシンク                                   : 3セット
microSDカード 16GB                       : 2枚
microSDカード 32GB                       : 1枚(家にあった余り物)
4段積層式 Raspberry Pi 3 ケース       : 1セット
4ポート USB 充電器                          : 1台
microUSB ケーブル                      : 4本 
平麺LANケーブル                            : 4本
コンパクト無線親機 (WMR-433W)     : 1台
5ポートのHUB                                 : 1台

<OS> 
Raspbian stretch lite
<マシン名一覧>
Master:raspberrypi-1
node1: raspberrypi-2
node2: raspberrypi-3


◻️OSの導入方法について

1)まずは、SD Card Formatterを使ってSDカードのフォーマット行うが
詳細については、割愛する。


2)マウント先を調べる
$ diskutil list

(今回、上記の調査で、disk3であることが分かった)

3)ディスクをアンマウントを行う。
$ diskutil unmountDisk /dev/disk3

4)ディスクイメージを置いた場所に移動する
$ cd /Users/user名/Desktop

5)OSの書き込みを行う。
$ sudo dd bs=1m if=2018-06-27-raspbian-stretch-lite.img of=/dev/rdisk3 conv=sync


◻️SSHの設定

1)インストール先のSDカードに移動する。
$ cd /Volumes/boot

2)以下のからファイルを作成しないとsshが無効の状態になるので必ず行うこと。
$ touch ssh



◻️cgroupの設定

1)以下を修正する。


$ cd /Volumes/boot
$ vi cmdline.txt

2)修正対象のファイルにペーストを行う。

dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=PARTUUID=4d3ee428-02 rootfstype=ext4 cgroup_enable=cpuset cgroup_enable=memory cgroup_memory=1 elevator=deadline fsck.repair=yes rootwait quiet init=/usr/lib/raspi-config/init_resize.sh

赤文字が追加する内容
オレンジ色の箇所は、元の記載内容に合わせた方が良いかも。

◻️raspberry piにログインする
以下の方法で該当するraspberry piにログインする。
$ ssh pi@192.168.xx.xx

接続方法は、端末によって異なるが
今回は、OSXを使用しているのでTerminalから接続している。


◻️OSのアップデート
$ sudo apt-get upgrade
$ sudo apt-get install rpi-update



◻️raspi-configの設定
以下を実施を行う
$ sudo raspi-config

◻️raspi-configを実行する。

4 Localisation Options の設定  
  I1 Change Locale の設定  
     ->en_GB.UTF-8 UTF-8のチェックを外し(Spaceキー),ja_JP.EUC-JP
         EUC-JP とja_JP.UTF-8 UTF-8 にチェック  
     ->Default localeをja_JP.UTF-8に設定
  I2 Change Timezone で Asia/Tokyo に設定
7 Advanced Options の設定  

  A1 Expand Filesystem を実行して,SDカードの全容量を
  使用できるように設定     
  A3 Memory Split で,GPUに割り当てるメモリを最小の16MBに設定



◻️ホスト名の変更

1)各ホストごとに、ホスト名の変更を行う。
sudo vi /etc/hostname
raspberrypi-1.local(masterの場合)

2)ホスト名と該当するホストのIPを追記する。
sudo vi /etc/hosts
192.168.XX.X   raspberrypi-1.local(masterの場合)

3)固定IPの設定を行う。

vi /etc/dhcpcd.conf
=====以下に、設定対象の値を入力する==================
# Example static IP configuration:
interface eth0
static ip_address=192.168.13.4/24
static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.13.99

static domain_name_servers=192.168.1.200 8.8.8.8 fd51:42f8:caae:d92e::1

4)再起動を行う
sudo reboot


◼︎各ホスト毎のログイン(実施対象:master/node1/node2)
各ホスト毎にログインを行う。

$ slogin user@raspberrypi-1.local(masterのログイン方法)


◼︎rootのパスワードを設定
$ sudo passwd root

◼︎スワップを切ることで、SDカードの寿命を伸ばせるので実施してみる
$ sudo dphys-swapfile swapoff
$ sudo dphys-swapfile uninstall
$ sudo update-rc.d dphys-swapfile remove



◼︎dockerの導入を行う(実施対象:master,node1,node2)

1)必要なパッケージ類を導入する
$ sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
$ curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | sudo apt-key add -

2)リポジトリの追加
$ echo "deb [arch=armhf] https://download.docker.com/linux/$(. /etc/os-release; echo "$ID") \
     $(lsb_release -cs) stable" | \
$ sudo tee /etc/apt/sources.list.d/docker.list

3)インストールを実行する。
$ sudo apt-get update
$ sudo apt-get install docker-ce


◼︎kubeadmのインストール(実施対象:master,node1,node2)

1)リポジトリの追加
$ curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg|sudo apt-key add -
$ echo "deb http://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee /etc/apt/sources.list.d/kube.list

2)インストールを行う
$ sudo apt-get update
$ sudo apt-get install kubelet kubeadm kubectl

上記で、導入するとkubeadmのversionが11.x.xになり動作が不安定になったので

導入方法を変更する。



$ apt-get install kubelet=1.8.14-00 kubeadm=1.8.14-00 kubectl=1.8.14-00 kubernetes-cni=0.5.1-00




◼︎Masterの設定(実施対象:master)

1)以下を実施する。
sudo kubeadm init --pod-network-cidr=10.244.0.0/16


注意:ホスト名に”アンダーバー”がついた名前で実行すると、名前を変えろとエラーが
表示されて実行できない。

NG)raspberrypi_1  
OK)raspberrypi-1

pi@raspberrypi-1:~ $ sudo kubeadm init --pod-network-cidr=10.244.0.0/16

ポイント:以下の表示が出ていれば成功
******************************************************
[init] using Kubernetes version: v1.11.2
[preflight] running pre-flight checks
I0823 14:17:28.295169    3241 kernel_validator.go:81] Validating kernel version
I0823 14:17:28.295805    3241 kernel_validator.go:96] Validating kernel config
[WARNING SystemVerification]: docker version is greater than the most recently validated version. Docker version: 18.06.1-ce. Max validated version: 17.03
[preflight/images] Pulling images required for setting up a Kubernetes cluster
[preflight/images] This might take a minute or two, depending on the speed of your internet connection
[preflight/images] You can also perform this action in beforehand using 'kubeadm config images pull'
[kubelet] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[preflight] Activating the kubelet service
[certificates] Generated ca certificate and key.
[certificates] Generated apiserver certificate and key.
[certificates] apiserver serving cert is signed for DNS names [raspberrypi-1.local kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.XX.X]
[certificates] Generated apiserver-kubelet-client certificate and key.
[certificates] Generated sa key and public key.
[certificates] Generated front-proxy-ca certificate and key.
[certificates] Generated front-proxy-client certificate and key.
[certificates] Generated etcd/ca certificate and key.
[certificates] Generated etcd/server certificate and key.
[certificates] etcd/server serving cert is signed for DNS names [raspberrypi-1.local localhost] and IPs [127.0.0.1 ::1]
[certificates] Generated etcd/peer certificate and key.
[certificates] etcd/peer serving cert is signed for DNS names [raspberrypi-1.local localhost] and IPs [192.168.XX.X 127.0.0.1 ::1]
[certificates] Generated etcd/healthcheck-client certificate and key.
[certificates] Generated apiserver-etcd-client certificate and key.
[certificates] valid certificates and keys now exist in "/etc/kubernetes/pki"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/admin.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/kubelet.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/controller-manager.conf"
[kubeconfig] Wrote KubeConfig file to disk: "/etc/kubernetes/scheduler.conf"
[controlplane] wrote Static Pod manifest for component kube-apiserver to "/etc/kubernetes/manifests/kube-apiserver.yaml"
[controlplane] wrote Static Pod manifest for component kube-controller-manager to "/etc/kubernetes/manifests/kube-controller-manager.yaml"
[controlplane] wrote Static Pod manifest for component kube-scheduler to "/etc/kubernetes/manifests/kube-scheduler.yaml"
[etcd] Wrote Static Pod manifest for a local etcd instance to "/etc/kubernetes/manifests/etcd.yaml"
[init] waiting for the kubelet to boot up the control plane as Static Pods from directory "/etc/kubernetes/manifests" 
[init] this might take a minute or longer if the control plane images have to be pulled
[apiclient] All control plane components are healthy after 180.014783 seconds
[uploadconfig] storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.11" in namespace kube-system with the configuration for the kubelets in the cluster
[markmaster] Marking the node raspberrypi-1.local as master by adding the label "node-role.kubernetes.io/master=''"
[markmaster] Marking the node raspberrypi-1.local as master by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "raspberrypi-1.local" as an annotation
[bootstraptoken] using token: gkl5zc.p4ymorryoqx1ohl9
[bootstraptoken] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstraptoken] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstraptoken] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstraptoken] creating the "cluster-info" ConfigMap in the "kube-public" namespace
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes master 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/

You can now join any number of machines by running the following on each node
as root:

  kubeadm join 192.168.XX.X:6443 --token XXXXX.p4ymorryoqx1ohl9 --discovery-token-ca-cert-hash sha256:XXXXXXXXXXXXXXXXXXXXXXXX
*******************************************************************:

ポイント:上記、赤文字の箇所は、後ほど必要になるので控えておくこと!!


2)上記、kubeadm init で表示されたメッセージに従う
$ mkdir -p $HOME/.kube
$ sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
$ sudo chown $(id -u):$(id -g) $HOME/.kube/config


3)falnnel のデプロイを行う。
$ kubectl apply -f <(curl -s https://raw.githubusercontent.com/coreos/flannel/v0.9.1/Documentation/kube-flannel.yml |sed 's/amd64/arm/g')

ポイント:成功すれば、以下の表示が出る。
*****************************:
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.extensions/kube-flannel-ds created
*******************************


◼︎nodeのセットアップ(実施対象:node1/node2)

1)rootでログインを行う。
$ sudo su -

2)kubeadm init を実行した時に表示されたメッセージに従い
コマンドを入力して、masterに参加する。

$ kubeadm join 192.168.xx.x:6443 --token XXXXX.p4ymorryoqx1ohl9 --discovery-token-ca-cert-hash sha256:XXXXXXXXXXXXXXXXXXXXXXXX


ポイント:成功すれば、以下のようなメッセージが表示される。
******************************
[preflight] running pre-flight checks
[WARNING RequiredIPVSKernelModulesAvailable]: the IPVS proxier will not be used, because the following required kernel modules are not loaded: [ip_vs ip_vs_rr ip_vs_wrr ip_vs_sh] or no builtin kernel ipvs support: map[nf_conntrack_ipv4:{} ip_vs:{} ip_vs_rr:{} ip_vs_wrr:{} ip_vs_sh:{}]
you can solve this problem with following methods:
 1. Run 'modprobe -- ' to load missing kernel modules;
2. Provide the missing builtin kernel ipvs support

I0823 14:42:35.630114    4950 kernel_validator.go:81] Validating kernel version
I0823 14:42:35.630592    4950 kernel_validator.go:96] Validating kernel config
[WARNING SystemVerification]: docker version is greater than the most recently validated version. Docker version: 18.06.1-ce. Max validated version: 17.03
[discovery] Trying to connect to API Server "192.168.xx.x:6443"
[discovery] Created cluster-info discovery client, requesting info from "https://192.168.xx.x:6443"
[discovery] Requesting info from "https://192.168.xx.x:6443" again to validate TLS against the pinned public key
[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server "192.168.xx.x:6443"
[discovery] Successfully established connection with API Server "192.168.xx.x:6443"
[kubelet] Downloading configuration for the kubelet from the "kubelet-config-1.11" ConfigMap in the kube-system namespace
[kubelet] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[preflight] Activating the kubelet service
[tlsbootstrap] Waiting for the kubelet to perform the TLS Bootstrap...
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "raspberrypi-3.local" as an annotation

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

Run 'kubectl get nodes' on the master to see this node join the cluster.
*********************************************************


3)接続状況を確認してみる。
各nodeが表示されていればOKかと思われる。

pi@raspberrypi-1:~ $ kubectl get node

NAME                  STATUS    ROLES     AGE       VERSION
raspberrypi-1.local   Ready     master    21m       v1.11.2
raspberrypi-2.local   Ready     <none>    6m        v1.11.2
raspberrypi-3.local   Ready     <none>    3m        v1.11.2

注意:raspberrypi-3.localがNot Readyになっていたが数分放置後にreadyに
変更された。




2018年8月5日日曜日

prometheus&grafana install for docker(mac)

1)docker fileを作成する。

vi docker-compose_gra.yml
============= docker-compose_gra.yml ===========================
version: '3'
services:
  prometheus:
    image: prom/prometheus:v2.2.0
    container_name: prometheus
    volumes:
      - ./prometheus.yml:/Users/User_Home/prometheus/prometheus.yml
      - ./prometheus-data:/prometheus
    ports:
      - 9090:9090
  grafana:
    image: grafana/grafana:5.1.2
    container_name: grafana
    volumes:
      - ./grafana-data:/var/lib/grafana
    ports:

      - 3000:3000
================================================================

◾️ポイント:
/Users/User_Home/は、個人でフォルダを生成する


2)prometheus.ymlを作成する。

vi prometheus.yml
======================== prometheus.yml =====================================
global:
  scrape_interval:     15s # By default, scrape targets every 15 seconds.
  # Attach these labels to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
    monitor: 'codelab-monitor'
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'
    # Override the global default and scrape targets from this job every 5 seconds.
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:9090']
=============================================================================


2)ファイルの実行を行う
docker-compose -f docker-compose_gra.yml up -d


参考ページ:

https://hakengineer.xyz/2018/05/12/post-1185/

kubernetes(pod数の増やし方)ダッシュボード編

kubernetesのダッシュボードからpod数を増やす方法について記載します。


podとは、コンテナの数を示す。


1)ダッシュボードの画面(Overview)から対象のpodから赤枠を選ぶ



2)Scaleを選択する。


3)増やしたいpod数を入力する
(今回、5つにしてみました。)


4)以下のようにpod数が増えたのが確認できます。







kubernetes(wordpressを生成する)for Mac

1)mysqlのパスワードを設定する

kubectl create secret generic mysql-pass --from-literal=password=yourpassword


2)以下、wordpress用(wordpress-deployment.yaml)のymlファイルを生成する

*****wordpress-deployment.yaml******
apiVersion: v1
kind: Service
metadata:
  name: wordpress
  labels:
    app: wordpress
spec:
  ports:
    - port: 80
  selector:
    app: wordpress
    tier: frontend
  type: LoadBalancer
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: wp-pv-claim
  labels:
    app: wordpress
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi
---
apiVersion: apps/v1 #  for k8s versions before 1.9.0 use apps/v1beta2  and before 1.8.0 use extensions/v1beta1
kind: Deployment
metadata:
  name: wordpress
  labels:
    app: wordpress
spec:
  selector:
    matchLabels:
      app: wordpress
      tier: frontend
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: wordpress
        tier: frontend
    spec:
      containers:
      - image: wordpress:4.8-apache
        name: wordpress
        env:
        - name: WORDPRESS_DB_HOST
          value: wordpress-mysql
        - name: WORDPRESS_DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-pass
              key: password
        ports:
        - containerPort: 80
          name: wordpress
        volumeMounts:
        - name: wordpress-persistent-storage
          mountPath: /var/www/html
      volumes:
      - name: wordpress-persistent-storage
        persistentVolumeClaim:
          claimName: wp-pv-claim
****************************************


3)以下、wordpress用(mysql-wordpress-pd.yml)のymlファイルを生成する

**** mysql-wordpress-pd ****************

apiVersion: v1
kind: Service
metadata:
  name: wordpress-mysql
  labels:
    app: wordpress
spec:
  ports:
    - port: 3306
  selector:
    app: wordpress
    tier: mysql
  clusterIP: None
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pv-claim
  labels:
    app: wordpress
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi
---
apiVersion: apps/v1 # for k8s versions before 1.9.0 use apps/v1beta2  and before 1.8.0 use extensions/v1beta1
kind: Deployment
metadata:
  name: wordpress-mysql
  labels:
    app: wordpress
spec:
  selector:
    matchLabels:
      app: wordpress
      tier: mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: wordpress
        tier: mysql
    spec:
      containers:
      - image: mysql:5.6
        name: mysql
        env:
        - name: Pass@1234
          valueFrom:
            secretKeyRef:
              name: mysql-pass
              key: password
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:
      - name: mysql-persistent-storage
        persistentVolumeClaim:
          claimName: mysql-pv-claim
***********************************************


ポイント:
「---」で区切ることにより、それぞれの設定ファイルを一箇所に書くことができる。




4)mysqlを立ち上げる
kubectl apply -f mysql-deployment.yaml

5)wordpressを立ち上げる
kubectl create -f wordpress-deployment.yaml


6)ダッシュボードでも生成されたのが確認できる。




補足:初期インストールを行う場合、ブラウザ上で
127.0.0.1:80にすれば、初期画面に推移する。



◾️検証環境の削除
# 一気に削除する場合
$ kubectl delete all,pvc,secret --all
# 設定ファイルを使って削除する場合
kubectl delete -f wordpress-deployment.yaml
kubectl delete -f mysql-deployment.yaml



kubernetes(ダッシュボードの設定) for Mac

docker (kubernetes)をインストール


dockerアプリからpreferencesを開き、kubernetesを有効にする








以下を実行する。
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/master/src/deploy/recommended/kubernetes-dashboard.yaml


$ kubectl proxy


もし、以下の表示が出ていた場合、別で8001ポートを使用している場合があるので
検索にヒットしたら消すこと!

iMac:~ hidenari$ kubectl proxy
F0804 20:52:47.305893    5825 proxy.go:154] listen tcp 127.0.0.1:8001: bind: address already in use


以下のコマンドで検索を行う
$ sudo lsof -i -P | grep "LISTEN"


以下のコマンドで対象のポートを消すことができる。
$ kill -9 [消したいポート番号]


対象のポートを消したら、以下を再考すること
$ kubectl proxy


以下のアドレスがダッシュボードのアドレスになる。
http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/

ダッシュボードの画面




削除:
$ kubectl delete -f kubernetes-dashboard.yaml





1)アカウント用の設定ファイルを作成する
vi kube-system

*******kube-system************
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kube-system
***************************************


2)上記で生成したファイルを実行する。
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}')


3)表示された “token:” をコピーする。



4)以下のアドレスに移動する。
http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/

5)Tokenを選択して、"Enter token"に上記の赤枠をペーストする。




2018年8月4日土曜日

Helm (docker)

Deis が開発した Kubernetes のパッケージマネージメントツール がHelm 

Rancher2.0

KubernetesをGUI上で一括で管理できる。

  -google,aws等のクラウドなどとも連携可能。


<導入例>raspberry piをベースに検討しているので、現状未検証。


sudo docker run -d --restart=unless-stopped -p 80:80 -p 443:443 rancher/server:preview

Lambda + SSM Run Commandで、数十台のEC2のuserdata結果を一括確認する

コードを1枚貼って、テストイベントを実行するだけで、 全台の確認結果が返ってくる手順です。 [ゴール] Nameタグが web-* / api-* / batch-* のEC2すべてに確認コマンドを流し、 NGの台だけ を結果に表示します。確認対象のuserdata(Ubu...