基于v1.10.4版本手動(dòng)搭建高可用kubernetes 集群

1. 組件版本和配置策略

組件版本

  • Kubernetes 1.10.4
  • Docker 18.03.1-ce
  • Etcd 3.3.7
  • Flanneld 0.10.0

插件

  • Coredns
  • Dashboard
  • Heapster (influxdb马绝、grafana)
  • Metrics-Server
  • EFK (elasticsearch博其、fluentd牌芋、kibana)

鏡像倉庫

  • docker registry
主要配置策略:

kube-apiserver:

  • 使用 keepalived 和 haproxy 實(shí)現(xiàn) 3 節(jié)點(diǎn)高可用揉抵;
  • 關(guān)閉非安全端口 8080 和匿名訪問;
  • 在安全端口 6443 接收 https 請(qǐng)求品洛;
  • 嚴(yán)格的認(rèn)證和授權(quán)策略 (x509树姨、token、RBAC)桥状;
  • 開啟 bootstrap token 認(rèn)證帽揪,支持 kubelet TLS bootstrapping;
  • 使用 https 訪問 kubelet岛宦、etcd台丛,加密通信;

kube-controller-manager:

  • 3 節(jié)點(diǎn)高可用砾肺;
  • 關(guān)閉非安全端口挽霉,在安全端口 10252 接收 https 請(qǐng)求;
  • 使用 kubeconfig 訪問 apiserver 的安全端口变汪;
  • 自動(dòng) approve kubelet 證書簽名請(qǐng)求 (CSR)侠坎,證書過期后自動(dòng)輪轉(zhuǎn);
  • 各 controller 使用自己的 ServiceAccount 訪問 apiserver裙盾;

kube-scheduler:

  • 3 節(jié)點(diǎn)高可用实胸;
  • 使用 kubeconfig 訪問 apiserver 的安全端口;

kubelet:

  • 使用 kubeadm 動(dòng)態(tài)創(chuàng)建 bootstrap token番官,而不是在 apiserver 中靜態(tài)配置庐完;
  • 使用 TLS bootstrap 機(jī)制自動(dòng)生成 client 和 server 證書,過期后自動(dòng)輪轉(zhuǎn)徘熔;
  • 在 KubeletConfiguration 類型的 JSON 文件配置主要參數(shù)门躯;
  • 關(guān)閉只讀端口,在安全端口 10250 接收 https 請(qǐng)求酷师,對(duì)請(qǐng)求進(jìn)行認(rèn)證和授權(quán)讶凉,拒絕匿名訪非授權(quán)訪問染乌;
  • 使用 kubeconfig 訪問 apiserver 的安全端口;

kube-proxy:

  • 使用 kubeconfig 訪問 apiserver 的安全端口懂讯;
  • 在 KubeProxyConfiguration 類型的 JSON 文件配置主要參數(shù)荷憋;
  • 使用 ipvs 代理模式;

集群插件:

  • DNS:使用功能褐望、性能更好的 coredns勒庄;
  • Dashboard:支持登錄認(rèn)證;
  • Metric:heapster譬挚、metrics-server锅铅,使用 https 訪問 kubelet 安全端口酪呻;
  • Log:Elasticsearch减宣、Fluend、Kibana玩荠;
  • Registry 鏡像庫:docker-registry漆腌、harbor;

2. 環(huán)境準(zhǔn)備

集群機(jī)器:
本文檔中的 etcd 集群阶冈、master 節(jié)點(diǎn)闷尿、worker 節(jié)點(diǎn)均使用這三臺(tái)機(jī)器。

  • kube-node1:192.168.16.237
  • kube-node2:192.168.16.238
  • kube-node3:192.168.16.239
  • uname -r: 4.17.12-1.el7.elrepo.x86_64
    設(shè)置永久主機(jī)名稱女坑,然后重新登錄:
$ sudo hostnamectl set-hostname kube-node1 # 將 kube-node1 替換為當(dāng)前主機(jī)名
  • 設(shè)置的主機(jī)名保存在 /etc/hostname 文件中填具;

修改每臺(tái)機(jī)器的 /etc/hosts 文件,添加主機(jī)名和 IP 的對(duì)應(yīng)關(guān)系:

$ grep kube-node /etc/hosts
192.168.16.237 kube-node1   kube-node1
192.168.16.238 kube-node2   kube-node2
192.168.16.239 kube-node3   kube-node3

添加 k8s 和 docker 賬戶

在每臺(tái)機(jī)器上添加 k8s 賬戶匆骗,可以無密碼 sudo:

$ sudo useradd -m k8s
$ sudo sh -c 'echo 123456 | passwd k8s --stdin' # 為 k8s 賬戶設(shè)置密碼
$ sudo visudo
$ sudo grep '%wheel.*NOPASSWD: ALL' /etc/sudoers
   %wheel   ALL=(ALL)   NOPASSWD: ALL
$ sudo gpasswd -a k8s wheel

在每臺(tái)機(jī)器上添加 docker 賬戶劳景,將 k8s 賬戶添加到 docker 組中,同時(shí)配置 dockerd 參數(shù):

$ sudo useradd -m docker
$ sudo gpasswd -a k8s docker
$ sudo mkdir -p  /etc/docker/
$ cat /etc/docker/daemon.json
{
    "registry-mirrors": ["https://hub-mirror.c.163.com", "https://docker.mirrors.ustc.edu.cn"],
    "max-concurrent-downloads": 20
}

無密碼 ssh 登錄其它節(jié)點(diǎn)

如果沒有特殊指明碉就,本文檔的所有操作均在 kube-node1 節(jié)點(diǎn)上執(zhí)行盟广,然后遠(yuǎn)程分發(fā)文件和執(zhí)行命令。

設(shè)置 kube-node1 可以無密碼登錄所有節(jié)點(diǎn)的 k8s 和 root 賬戶:

[k8s@kube-node1 k8s]$ ssh-keygen -t rsa
[k8s@kube-node1 k8s]$ ssh-copy-id root@kube-node1
[k8s@kube-node1 k8s]$ ssh-copy-id root@kube-node2
[k8s@kube-node1 k8s]$ ssh-copy-id root@kube-node3

[k8s@kube-node1 k8s]$ ssh-copy-id k8s@kube-node1
[k8s@kube-node1 k8s]$ ssh-copy-id k8s@kube-node2
[k8s@kube-node1 k8s]$ ssh-copy-id k8s@kube-node3

將可執(zhí)行文件路徑 /opt/k8s/bin 添加到 PATH 變量中

在每臺(tái)機(jī)器上添加環(huán)境變量:

$ sudo sh -c "echo 'PATH=/opt/k8s/bin:$PATH:$HOME/bin:$JAVA_HOME/bin' >>/root/.bashrc"
$ echo 'PATH=/opt/k8s/bin:$PATH:$HOME/bin:$JAVA_HOME/bin' >>~/.bashrc

安裝依賴包

在每臺(tái)機(jī)器上安裝依賴包:

$ sudo yum install -y epel-release
$ sudo yum install -y conntrack ipvsadm ipset jq sysstat curl iptables libseccomp
  • ipvs 依賴 ipset瓮钥;

關(guān)閉防火墻

在每臺(tái)機(jī)器上關(guān)閉防火墻:

$ sudo systemctl stop firewalld
$ sudo systemctl disable firewalld
$ sudo iptables -F && sudo iptables -X && sudo iptables -F -t nat && sudo iptables -X -t nat
$ sudo sudo iptables -P FORWARD ACCEPT

關(guān)閉 swap 分區(qū)

如果開啟了 swap 分區(qū)筋量,kubelet 會(huì)啟動(dòng)失敗(可以通過將參數(shù) --fail-swap-on 設(shè)置為 false 來忽略 swap on),故需要在每臺(tái)機(jī)器上關(guān)閉 swap 分區(qū):

$ sudo swapoff -a

為了防止開機(jī)自動(dòng)掛載 swap 分區(qū)碉熄,可以注釋 /etc/fstab 中相應(yīng)的條目:

$ sudo sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab

關(guān)閉 SELinux

關(guān)閉 SELinux桨武,否則后續(xù) K8S 掛載目錄時(shí)可能報(bào)錯(cuò) Permission denied

$ sudo setenforce 0
$ grep SELINUX /etc/selinux/config 
SELINUX=disabled
  • 修改配置文件,永久生效锈津;

關(guān)閉 dnsmasq

linux 系統(tǒng)開啟了 dnsmasq 后(如 GUI 環(huán)境)呀酸,將系統(tǒng) DNS Server 設(shè)置為 127.0.0.1,這會(huì)導(dǎo)致 docker 容器無法解析域名一姿,需要關(guān)閉它:

$ sudo service dnsmasq stop
$ sudo systemctl disable dnsmasq

設(shè)置系統(tǒng)參數(shù)

$ cat > kubernetes.conf <<EOF
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1
vm.swappiness=0
vm.overcommit_memory=1
vm.panic_on_oom=0
fs.inotify.max_user_watches=89100
EOF
$ sudo cp kubernetes.conf  /etc/sysctl.d/kubernetes.conf
$ sudo sysctl -p /etc/sysctl.d/kubernetes.conf
$ sudo mount -t cgroup -o cpu,cpuacct none /sys/fs/cgroup/cpu,cpuacct

加載內(nèi)核模塊

$ sudo modprobe br_netfilter
$ sudo modprobe ip_vs

設(shè)置系統(tǒng)時(shí)區(qū)

$ # 調(diào)整系統(tǒng) TimeZone
$ sudo timedatectl set-timezone Asia/Shanghai

$ # 將當(dāng)前的 UTC 時(shí)間寫入硬件時(shí)鐘
$ sudo timedatectl set-local-rtc 0

$ # 重啟依賴于系統(tǒng)時(shí)間的服務(wù)
$ sudo systemctl restart rsyslog 
$ sudo systemctl restart crond

創(chuàng)建目錄

在每臺(tái)機(jī)器上創(chuàng)建目錄:

$ sudo mkdir -p /opt/k8s/bin
$ sudo chown -R k8s /opt/k8s

$ sudo sudo mkdir -p /etc/kubernetes/cert
$ sudo chown -R k8s /etc/kubernetes

$ sudo mkdir -p /etc/etcd/cert
$ sudo chown -R k8s /etc/etcd/cert

$ sudo mkdir -p /var/lib/etcd && chown -R k8s /etc/etcd/cert

檢查系統(tǒng)內(nèi)核和模塊是否適合運(yùn)行 docker (僅適用于 linux 系統(tǒng))

$ curl https://raw.githubusercontent.com/docker/docker/master/contrib/check-config.sh > check-config.sh
$ bash ./check-config.sh

集群環(huán)境變量

后續(xù)的部署步驟將使用下面定義的全局環(huán)境變量七咧,請(qǐng)根據(jù)自己的機(jī)器跃惫、網(wǎng)絡(luò)情況修改:

#!/usr/bin/bash

# 生成 EncryptionConfig 所需的加密 key
ENCRYPTION_KEY=$(head -c 32 /dev/urandom | base64)

# 最好使用 當(dāng)前未用的網(wǎng)段 來定義服務(wù)網(wǎng)段和 Pod 網(wǎng)段

# 服務(wù)網(wǎng)段,部署前路由不可達(dá)艾栋,部署后集群內(nèi)路由可達(dá)(kube-proxy 和 ipvs 保證)
SERVICE_CIDR="10.254.0.0/16"

# Pod 網(wǎng)段爆存,建議 /16 段地址,部署前路由不可達(dá)蝗砾,部署后集群內(nèi)路由可達(dá)(flanneld 保證)
CLUSTER_CIDR="172.30.0.0/16"

# 服務(wù)端口范圍 (NodePort Range)
export NODE_PORT_RANGE="8400-9000"

# 集群各機(jī)器 IP 數(shù)組
export NODE_IPS=(192.168.16.237 192.168.16.238 192.168.16.239)

# 集群各 IP 對(duì)應(yīng)的 主機(jī)名數(shù)組
export NODE_NAMES=(kube-node1 kube-node2 kube-node3)

# kube-apiserver 的 VIP(HA 組件 keepalived 發(fā)布的 IP)
export MASTER_VIP=192.168.16.240

# kube-apiserver VIP 地址(HA 組件 haproxy 監(jiān)聽 8443 端口)
export KUBE_APISERVER="https://${MASTER_VIP}:8443"

# HA 節(jié)點(diǎn)先较,VIP 所在的網(wǎng)絡(luò)接口名稱
export VIP_IF="eth0"

# etcd 集群服務(wù)地址列表
export ETCD_ENDPOINTS="https://192.168.16.267:2379,https://192.168.16.238:2379,https://192.168.16.239:2379"

# etcd 集群間通信的 IP 和端口
export ETCD_NODES="kube-node1=https://192.168.16.237:2380,kube-node2=https://192.168.16.238:2380,kube-node3=https://192.168.16.239:2380"

# flanneld 網(wǎng)絡(luò)配置前綴
export FLANNEL_ETCD_PREFIX="/kubernetes/network"

# kubernetes 服務(wù) IP (一般是 SERVICE_CIDR 中第一個(gè)IP)
export CLUSTER_KUBERNETES_SVC_IP="10.254.0.1"

# 集群 DNS 服務(wù) IP (從 SERVICE_CIDR 中預(yù)分配)
export CLUSTER_DNS_SVC_IP="10.254.0.2"

# 集群 DNS 域名
export CLUSTER_DNS_DOMAIN="cluster.local."

# 將二進(jìn)制目錄 /opt/k8s/bin 加到 PATH 中
export PATH=/opt/k8s/bin:$PATH
  • 打包后的變量定義見 environment.sh,后續(xù)部署時(shí)會(huì)提示導(dǎo)入該腳本悼粮;

分發(fā)集群環(huán)境變量定義腳本

把全局變量定義腳本拷貝到所有節(jié)點(diǎn)的 /opt/k8s/bin 目錄:

source environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp environment.sh k8s@${node_ip}:/opt/k8s/bin/
    ssh k8s@${node_ip} "chmod +x /opt/k8s/bin/*"
  done

3. 創(chuàng)建 CA 證書和秘鑰

為確保安全闲勺,kubernetes 系統(tǒng)各組件需要使用 x509 證書對(duì)通信進(jìn)行加密和認(rèn)證。

CA (Certificate Authority) 是自簽名的根證書扣猫,用來簽名后續(xù)創(chuàng)建的其它證書菜循。

本文檔使用 CloudFlare 的 PKI 工具集 cfssl 創(chuàng)建所有證書缩功。

安裝 cfssl 工具集

sudo mkdir -p /opt/k8s/cert && sudo chown -R k8s /opt/k8s && cd /opt/k8s
wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
mv cfssl_linux-amd64 /opt/k8s/bin/cfssl

wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
mv cfssljson_linux-amd64 /opt/k8s/bin/cfssljson

wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
mv cfssl-certinfo_linux-amd64 /opt/k8s/bin/cfssl-certinfo

chmod +x /opt/k8s/bin/*
export PATH=/opt/k8s/bin:$PATH

創(chuàng)建根證書 (CA)

CA 證書是集群所有節(jié)點(diǎn)共享的杯聚,只需要?jiǎng)?chuàng)建一個(gè) CA 證書负间,后續(xù)創(chuàng)建的所有證書都由它簽名匈睁。

創(chuàng)建配置文件

CA 配置文件用于配置根證書的使用場景 (profile) 和具體參數(shù) (usage溯壶,過期時(shí)間芋酌、服務(wù)端認(rèn)證首尼、客戶端認(rèn)證耙替、加密等)时鸵,后續(xù)在簽名其它證書時(shí)需要指定特定場景胶逢。

cat > ca-config.json <<EOF
{
  "signing": {
    "default": {
      "expiry": "87600h"
    },
    "profiles": {
      "kubernetes": {
        "usages": [
            "signing",
            "key encipherment",
            "server auth",
            "client auth"
        ],
        "expiry": "87600h"
      }
    }
  }
}
EOF
  • signing:表示該證書可用于簽名其它證書,生成的 ca.pem 證書中 CA=TRUE饰潜;
  • server auth:表示 client 可以用該該證書對(duì) server 提供的證書進(jìn)行驗(yàn)證初坠;
  • client auth:表示 server 可以用該該證書對(duì) client 提供的證書進(jìn)行驗(yàn)證;

創(chuàng)建證書簽名請(qǐng)求文件

cat > ca-csr.json <<EOF
{
  "CN": "kubernetes",
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF
  • CN:Common Name囊拜,kube-apiserver 從證書中提取該字段作為請(qǐng)求的用戶名 (User Name)某筐,瀏覽器使用該字段驗(yàn)證網(wǎng)站是否合法;
  • O:Organization冠跷,kube-apiserver 從證書中提取該字段作為請(qǐng)求用戶所屬的組 (Group)南誊;
  • kube-apiserver 將提取的 User、Group 作為 RBAC 授權(quán)的用戶標(biāo)識(shí)蜜托;

生成 CA 證書和私鑰

cfssl gencert -initca ca-csr.json | cfssljson -bare ca
ls ca*

分發(fā)證書文件

將生成的 CA 證書抄囚、秘鑰文件、配置文件拷貝到所有節(jié)點(diǎn)/etc/kubernetes/cert 目錄下:

source /opt/k8s/bin/environment.sh # 導(dǎo)入 NODE_IPS 環(huán)境變量
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /etc/kubernetes/cert && chown -R k8s /etc/kubernetes"
    scp ca*.pem ca-config.json k8s@${node_ip}:/etc/kubernetes/cert
  done
  • k8s 賬戶需要有讀寫 /etc/kubernetes 目錄及其子目錄文件的權(quán)限橄务;

4.部署 kubectl 命令行工具

kubectl 是 kubernetes 集群的命令行管理工具幔托,本文檔介紹安裝和配置它的步驟。

kubectl 默認(rèn)從 ~/.kube/config 文件讀取 kube-apiserver 地址、證書重挑、用戶名等信息嗓化,如果沒有配置,執(zhí)行 kubectl 命令時(shí)可能會(huì)出錯(cuò):

$ kubectl get pods
The connection to the server localhost:8080 was refused - did you specify the right host or port?

本文檔只需要部署一次谬哀,生成的 kubeconfig 文件與機(jī)器無關(guān)刺覆。

下載和分發(fā) kubectl 二進(jìn)制文件

下載和解壓:

wget https://dl.k8s.io/v1.10.4/kubernetes-client-linux-amd64.tar.gz
tar -xzvf kubernetes-client-linux-amd64.tar.gz

分發(fā)到所有使用 kubectl 的節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kubernetes/client/bin/kubectl k8s@${node_ip}:/opt/k8s/bin/
    ssh k8s@${node_ip} "chmod +x /opt/k8s/bin/*"
  done

創(chuàng)建 admin 證書和私鑰

kubectl 與 apiserver https 安全端口通信,apiserver 對(duì)提供的證書進(jìn)行認(rèn)證和授權(quán)史煎。

kubectl 作為集群的管理工具谦屑,需要被授予最高權(quán)限。這里創(chuàng)建具有最高權(quán)限的 admin 證書篇梭。

創(chuàng)建證書簽名請(qǐng)求:

cat > admin-csr.json <<EOF
{
  "CN": "admin",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "system:masters",
      "OU": "4Paradigm"
    }
  ]
}
EOF
  • O 為 system:masters氢橙,kube-apiserver 收到該證書后將請(qǐng)求的 Group 設(shè)置為 system:masters;
  • 預(yù)定義的 ClusterRoleBinding cluster-admin 將 Group system:masters 與 Role cluster-admin 綁定恬偷,該 Role 授予所有 API的權(quán)限悍手;
  • 該證書只會(huì)被 kubectl 當(dāng)做 client 證書使用,所以 hosts 字段為空喉磁;

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
  -ca-key=/etc/kubernetes/cert/ca-key.pem \
  -config=/etc/kubernetes/cert/ca-config.json \
  -profile=kubernetes admin-csr.json | cfssljson -bare admin
ls admin*

創(chuàng)建 kubeconfig 文件

kubeconfig 為 kubectl 的配置文件谓苟,包含訪問 apiserver 的所有信息官脓,如 apiserver 地址协怒、CA 證書和自身使用的證書;

source /opt/k8s/bin/environment.sh
# 設(shè)置集群參數(shù)
kubectl config set-cluster kubernetes \
  --certificate-authority=/etc/kubernetes/cert/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=kubectl.kubeconfig

# 設(shè)置客戶端認(rèn)證參數(shù)
kubectl config set-credentials admin \
  --client-certificate=admin.pem \
  --client-key=admin-key.pem \
  --embed-certs=true \
  --kubeconfig=kubectl.kubeconfig

# 設(shè)置上下文參數(shù)
kubectl config set-context kubernetes \
  --cluster=kubernetes \
  --user=admin \
  --kubeconfig=kubectl.kubeconfig

# 設(shè)置默認(rèn)上下文
kubectl config use-context kubernetes --kubeconfig=kubectl.kubeconfig
  • --certificate-authority:驗(yàn)證 kube-apiserver 證書的根證書卑笨;
  • --client-certificate孕暇、--client-key:剛生成的 admin 證書和私鑰,連接 kube-apiserver 時(shí)使用赤兴;
  • --embed-certs=true:將 ca.pem 和 admin.pem 證書內(nèi)容嵌入到生成的 kubectl.kubeconfig 文件中(不加時(shí)妖滔,寫入的是證書文件路徑);

分發(fā) kubeconfig 文件

分發(fā)到所有使用 kubectl 命令的節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "mkdir -p ~/.kube"
    scp kubectl.kubeconfig k8s@${node_ip}:~/.kube/config
    ssh root@${node_ip} "mkdir -p ~/.kube"
    scp kubectl.kubeconfig root@${node_ip}:~/.kube/config
  done
  • 保存到用戶的 ~/.kube/config 文件桶良;

5.部署 etcd 集群

etcd 是基于 Raft 的分布式 key-value 存儲(chǔ)系統(tǒng)座舍,由 CoreOS 開發(fā),常用于服務(wù)發(fā)現(xiàn)陨帆、共享配置以及并發(fā)控制(如 leader 選舉曲秉、分布式鎖等)。kubernetes 使用 etcd 存儲(chǔ)所有運(yùn)行數(shù)據(jù)疲牵。

本文檔介紹部署一個(gè)三節(jié)點(diǎn)高可用 etcd 集群的步驟:

  • 下載和分發(fā) etcd 二進(jìn)制文件承二;
  • 創(chuàng)建 etcd 集群各節(jié)點(diǎn)的 x509 證書,用于加密客戶端(如 etcdctl) 與 etcd 集群纲爸、etcd 集群之間的數(shù)據(jù)流亥鸠;
  • 創(chuàng)建 etcd 的 systemd unit 文件,配置服務(wù)參數(shù);
  • 檢查集群工作狀態(tài)负蚊;

etcd 集群各節(jié)點(diǎn)的名稱和 IP 如下:

  • kube-node1:192.168.16.237
  • kube-node2:192.168.16.238
  • kube-node3:192.168.16.239

下載和分發(fā) etcd 二進(jìn)制文件

https://github.com/coreos/etcd/releases 頁面下載最新版本的發(fā)布包:

wget https://github.com/coreos/etcd/releases/download/v3.3.7/etcd-v3.3.7-linux-amd64.tar.gz
tar -xvf etcd-v3.3.7-linux-amd64.tar.gz

分發(fā)二進(jìn)制文件到集群所有節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp etcd-v3.3.7-linux-amd64/etcd* k8s@${node_ip}:/opt/k8s/bin
    ssh k8s@${node_ip} "chmod +x /opt/k8s/bin/*"
  done

創(chuàng)建 etcd 證書和私鑰

創(chuàng)建證書簽名請(qǐng)求:

cat > etcd-csr.json <<EOF
{
  "CN": "etcd",
  "hosts": [
    "127.0.0.1",
    "192.168.16.237",
    "192.168.16.238",
    "192.168.16.239"
  ],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF
  • hosts 字段指定授權(quán)使用該證書的 etcd 節(jié)點(diǎn) IP 或域名列表神妹,這里將 etcd 集群的三個(gè)節(jié)點(diǎn) IP 都列在其中;

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
    -ca-key=/etc/kubernetes/cert/ca-key.pem \
    -config=/etc/kubernetes/cert/ca-config.json \
    -profile=kubernetes etcd-csr.json | cfssljson -bare etcd
ls etcd*

分發(fā)生成的證書和私鑰到各 etcd 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /etc/etcd/cert && chown -R k8s /etc/etcd/cert"
    scp etcd*.pem k8s@${node_ip}:/etc/etcd/cert/
  done

創(chuàng)建 etcd 的 systemd unit 模板文件

source /opt/k8s/bin/environment.sh
cat > etcd.service.template <<EOF
[Unit]
Description=Etcd Server
After=network.target
After=network-online.target
Wants=network-online.target
Documentation=https://github.com/coreos

[Service]
User=k8s
Type=notify
WorkingDirectory=/var/lib/etcd/
ExecStart=/opt/k8s/bin/etcd \\
  --data-dir=/var/lib/etcd \\
  --name=##NODE_NAME## \\
  --cert-file=/etc/etcd/cert/etcd.pem \\
  --key-file=/etc/etcd/cert/etcd-key.pem \\
  --trusted-ca-file=/etc/kubernetes/cert/ca.pem \\
  --peer-cert-file=/etc/etcd/cert/etcd.pem \\
  --peer-key-file=/etc/etcd/cert/etcd-key.pem \\
  --peer-trusted-ca-file=/etc/kubernetes/cert/ca.pem \\
  --peer-client-cert-auth \\
  --client-cert-auth \\
  --listen-peer-urls=https://##NODE_IP##:2380 \\
  --initial-advertise-peer-urls=https://##NODE_IP##:2380 \\
  --listen-client-urls=https://##NODE_IP##:2379,http://127.0.0.1:2379 \\
  --advertise-client-urls=https://##NODE_IP##:2379 \\
  --initial-cluster-token=etcd-cluster-0 \\
  --initial-cluster=${ETCD_NODES} \\
  --initial-cluster-state=new
Restart=on-failure
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF
  • User:指定以 k8s 賬戶運(yùn)行家妆;
  • WorkingDirectory灾螃、--data-dir:指定工作目錄和數(shù)據(jù)目錄為 /var/lib/etcd,需在啟動(dòng)服務(wù)前創(chuàng)建這個(gè)目錄揩徊;
  • --name:指定節(jié)點(diǎn)名稱腰鬼,當(dāng) --initial-cluster-state 值為 new 時(shí),--name 的參數(shù)值必須位于 --initial-cluster 列表中塑荒;
  • --cert-file熄赡、--key-file:etcd server 與 client 通信時(shí)使用的證書和私鑰;
  • --trusted-ca-file:簽名 client 證書的 CA 證書齿税,用于驗(yàn)證 client 證書彼硫;
  • --peer-cert-file--peer-key-file:etcd 與 peer 通信使用的證書和私鑰凌箕;
  • --peer-trusted-ca-file:簽名 peer 證書的 CA 證書拧篮,用于驗(yàn)證 peer 證書;

為各節(jié)點(diǎn)創(chuàng)建和分發(fā) etcd systemd unit 文件

替換模板文件中的變量牵舱,為各節(jié)點(diǎn)創(chuàng)建 systemd unit 文件:

source /opt/k8s/bin/environment.sh
for (( i=0; i < 3; i++ ))
  do
    sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" etcd.service.template > etcd-${NODE_IPS[i]}.service 
  done
ls *.service
  • NODE_NAMES 和 NODE_IPS 為相同長度的 bash 數(shù)組串绩,分別為節(jié)點(diǎn)名稱和對(duì)應(yīng)的 IP;

分發(fā)生成的 systemd unit 文件:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/lib/etcd && chown -R k8s /var/lib/etcd" 
    scp etcd-${node_ip}.service root@${node_ip}:/etc/systemd/system/etcd.service
  done
  • 必須先創(chuàng)建 etcd 數(shù)據(jù)目錄和工作目錄;
  • 文件重命名為 etcd.service;

完整 unit 文件見:etcd.service

啟動(dòng) etcd 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable etcd && systemctl restart etcd &"
  done
  • etcd 進(jìn)程首次啟動(dòng)時(shí)會(huì)等待其它節(jié)點(diǎn)的 etcd 加入集群芜壁,命令 systemctl start etcd 會(huì)卡住一段時(shí)間礁凡,為正常現(xiàn)象慧妄。

檢查啟動(dòng)結(jié)果

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "systemctl status etcd|grep Active"
  done

確保狀態(tài)為 active (running)顷牌,否則查看日志,確認(rèn)原因:

$ journalctl -u etcd

驗(yàn)證服務(wù)狀態(tài)

部署完 etcd 集群后塞淹,在任一 etc 節(jié)點(diǎn)上執(zhí)行如下命令:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ETCDCTL_API=3 /opt/k8s/bin/etcdctl \
    --endpoints=https://${node_ip}:2379 \
    --cacert=/etc/kubernetes/cert/ca.pem \
    --cert=/etc/etcd/cert/etcd.pem \
    --key=/etc/etcd/cert/etcd-key.pem endpoint health
  done

預(yù)期輸出:

https://192.168.16.237:2379 is healthy: successfully committed proposal: took = 2.192932ms
https://192.168.16.238:2379 is healthy: successfully committed proposal: took = 3.546896ms
https://192.168.16.239:2379 is healthy: successfully committed proposal: took = 3.013667ms

輸出均為 healthy 時(shí)表示集群服務(wù)正常窟蓝。

6.# 部署 flannel 網(wǎng)絡(luò)

kubernetes 要求集群內(nèi)各節(jié)點(diǎn)(包括 master 節(jié)點(diǎn))能通過 Pod 網(wǎng)段互聯(lián)互通。flannel 使用 vxlan 技術(shù)為各節(jié)點(diǎn)創(chuàng)建一個(gè)可以互通的 Pod 網(wǎng)絡(luò)饱普。

flaneel 第一次啟動(dòng)時(shí)运挫,從 etcd 獲取 Pod 網(wǎng)段信息,為本節(jié)點(diǎn)分配一個(gè)未使用的 /24 段地址费彼,然后創(chuàng)建 flannedl.1(也可能是其它名稱滑臊,如 flannel1 等) 接口。

flannel 將分配的 Pod 網(wǎng)段信息寫入 /run/flannel/docker 文件箍铲,docker 后續(xù)使用這個(gè)文件中的環(huán)境變量設(shè)置 docker0 網(wǎng)橋雇卷。

下載和分發(fā) flanneld 二進(jìn)制文件

https://github.com/coreos/flannel/releases 頁面下載最新版本的發(fā)布包:

mkdir flannel
wget https://github.com/coreos/flannel/releases/download/v0.10.0/flannel-v0.10.0-linux-amd64.tar.gz
tar -xzvf flannel-v0.10.0-linux-amd64.tar.gz -C flannel

分發(fā) flanneld 二進(jìn)制文件到集群所有節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp  flannel/{flanneld,mk-docker-opts.sh} k8s@${node_ip}:/opt/k8s/bin/
    ssh k8s@${node_ip} "chmod +x /opt/k8s/bin/*"
  done

創(chuàng)建 flannel 證書和私鑰

flannel 從 etcd 集群存取網(wǎng)段分配信息,而 etcd 集群啟用了雙向 x509 證書認(rèn)證,所以需要為 flanneld 生成證書和私鑰关划。

創(chuàng)建證書簽名請(qǐng)求:

cat > flanneld-csr.json <<EOF
{
  "CN": "flanneld",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF
  • 該證書只會(huì)被 kubectl 當(dāng)做 client 證書使用小染,所以 hosts 字段為空;

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
  -ca-key=/etc/kubernetes/cert/ca-key.pem \
  -config=/etc/kubernetes/cert/ca-config.json \
  -profile=kubernetes flanneld-csr.json | cfssljson -bare flanneld
ls flanneld*pem

將生成的證書和私鑰分發(fā)到所有節(jié)點(diǎn)(master 和 worker):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /etc/flanneld/cert && chown -R k8s /etc/flanneld"
    scp flanneld*.pem k8s@${node_ip}:/etc/flanneld/cert
  done

向 etcd 寫入集群 Pod 網(wǎng)段信息

注意:本步驟只需執(zhí)行一次贮折。

source /opt/k8s/bin/environment.sh
etcdctl \
  --endpoints=${ETCD_ENDPOINTS} \
  --ca-file=/etc/kubernetes/cert/ca.pem \
  --cert-file=/etc/flanneld/cert/flanneld.pem \
  --key-file=/etc/flanneld/cert/flanneld-key.pem \
  set ${FLANNEL_ETCD_PREFIX}/config '{"Network":"'${CLUSTER_CIDR}'", "SubnetLen": 24, "Backend": {"Type": "vxlan"}}'
  • flanneld 當(dāng)前版本 (v0.10.0) 不支持 etcd v3裤翩,故使用 etcd v2 API 寫入配置 key 和網(wǎng)段數(shù)據(jù);
  • 寫入的 Pod 網(wǎng)段 ${CLUSTER_CIDR} 必須是 /16 段地址调榄,必須與 kube-controller-manager 的 --cluster-cidr 參數(shù)值一致踊赠;

創(chuàng)建 flanneld 的 systemd unit 文件

source /opt/k8s/bin/environment.sh
export IFACE=eth0
cat > flanneld.service << EOF
[Unit]
Description=Flanneld overlay address etcd agent
After=network.target
After=network-online.target
Wants=network-online.target
After=etcd.service
Before=docker.service

[Service]
Type=notify
ExecStart=/opt/k8s/bin/flanneld \\
  -etcd-cafile=/etc/kubernetes/cert/ca.pem \\
  -etcd-certfile=/etc/flanneld/cert/flanneld.pem \\
  -etcd-keyfile=/etc/flanneld/cert/flanneld-key.pem \\
  -etcd-endpoints=${ETCD_ENDPOINTS} \\
  -etcd-prefix=${FLANNEL_ETCD_PREFIX} \\
  -iface=${IFACE}
ExecStartPost=/opt/k8s/bin/mk-docker-opts.sh -k DOCKER_NETWORK_OPTIONS -d /run/flannel/docker
Restart=on-failure

[Install]
WantedBy=multi-user.target
RequiredBy=docker.service
EOF
  • mk-docker-opts.sh 腳本將分配給 flanneld 的 Pod 子網(wǎng)網(wǎng)段信息寫入 /run/flannel/docker 文件,后續(xù) docker 啟動(dòng)時(shí)使用這個(gè)文件中的環(huán)境變量配置 docker0 網(wǎng)橋每庆;
  • flanneld 使用系統(tǒng)缺省路由所在的接口與其它節(jié)點(diǎn)通信筐带,對(duì)于有多個(gè)網(wǎng)絡(luò)接口(如內(nèi)網(wǎng)和公網(wǎng))的節(jié)點(diǎn),可以用 -iface參數(shù)指定通信接口缤灵,如上面的 eth0 接口;
  • flanneld 運(yùn)行時(shí)需要 root 權(quán)限伦籍;

完整 unit 見 flanneld.service

分發(fā) flanneld systemd unit 文件到所有節(jié)點(diǎn)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp flanneld.service root@${node_ip}:/etc/systemd/system/
  done

啟動(dòng) flanneld 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable flanneld && systemctl restart flanneld"
  done

檢查啟動(dòng)結(jié)果

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "systemctl status flanneld|grep Active"
  done

確保狀態(tài)為 active (running),否則查看日志腮出,確認(rèn)原因:

$ journalctl -u flanneld

檢查分配給各 flanneld 的 Pod 網(wǎng)段信息

查看集群 Pod 網(wǎng)段(/16):

source /opt/k8s/bin/environment.sh
etcdctl \
  --endpoints=${ETCD_ENDPOINTS} \
  --ca-file=/etc/kubernetes/cert/ca.pem \
  --cert-file=/etc/flanneld/cert/flanneld.pem \
  --key-file=/etc/flanneld/cert/flanneld-key.pem \
  get ${FLANNEL_ETCD_PREFIX}/config

輸出:

{"Network":"172.30.0.0/16", "SubnetLen": 24, "Backend": {"Type": "vxlan"}}

查看已分配的 Pod 子網(wǎng)段列表(/24):

source /opt/k8s/bin/environment.sh
etcdctl \
  --endpoints=${ETCD_ENDPOINTS} \
  --ca-file=/etc/kubernetes/cert/ca.pem \
  --cert-file=/etc/flanneld/cert/flanneld.pem \
  --key-file=/etc/flanneld/cert/flanneld-key.pem \
  ls ${FLANNEL_ETCD_PREFIX}/subnets

輸出:

/kubernetes/network/subnets/172.30.81.0-24
/kubernetes/network/subnets/172.30.29.0-24
/kubernetes/network/subnets/172.30.39.0-24

查看某一 Pod 網(wǎng)段對(duì)應(yīng)的節(jié)點(diǎn) IP 和 flannel 接口地址:

source /opt/k8s/bin/environment.sh
etcdctl \
  --endpoints=${ETCD_ENDPOINTS} \
  --ca-file=/etc/kubernetes/cert/ca.pem \
  --cert-file=/etc/flanneld/cert/flanneld.pem \
  --key-file=/etc/flanneld/cert/flanneld-key.pem \
  get ${FLANNEL_ETCD_PREFIX}/subnets/172.30.81.0-24

輸出:

{"PublicIP":"192.168.16.237","BackendType":"vxlan","BackendData":{"VtepMAC":"12:21:93:9e:b1:eb"}}

驗(yàn)證各節(jié)點(diǎn)能通過 Pod 網(wǎng)段互通

各節(jié)點(diǎn)上部署 flannel 后帖鸦,檢查是否創(chuàng)建了 flannel 接口(名稱可能為 flannel0、flannel.0胚嘲、flannel.1 等):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh ${node_ip} "/usr/sbin/ip addr show flannel.1|grep -w inet"
  done

輸出:

inet 172.30.81.0/32 scope global flannel.1
inet 172.30.29.0/32 scope global flannel.1
inet 172.30.39.0/32 scope global flannel.1

在各節(jié)點(diǎn)上 ping 所有 flannel 接口 IP作儿,確保能通:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh ${node_ip} "ping -c 1 172.30.81.0"
    ssh ${node_ip} "ping -c 1 172.30.29.0"
    ssh ${node_ip} "ping -c 1 172.30.39.0"
  done

7.部署 master 節(jié)點(diǎn)

kubernetes master 節(jié)點(diǎn)運(yùn)行如下組件:

  • kube-apiserver
  • kube-scheduler
  • kube-controller-manager

kube-scheduler 和 kube-controller-manager 可以以集群模式運(yùn)行,通過 leader 選舉產(chǎn)生一個(gè)工作進(jìn)程慢逾,其它進(jìn)程處于阻塞模式立倍。

對(duì)于 kube-apiserver,可以運(yùn)行多個(gè)實(shí)例(本文檔是 3 實(shí)例)侣滩,但對(duì)其它組件需要提供統(tǒng)一的訪問地址,該地址需要高可用变擒。本文檔使用 keepalived 和 haproxy 實(shí)現(xiàn) kube-apiserver VIP 高可用和負(fù)載均衡君珠。

下載最新版本的二進(jìn)制文件

CHANGELOG頁面 下載 server tarball 文件。

wget https://dl.k8s.io/v1.10.4/kubernetes-server-linux-amd64.tar.gz
tar -xzvf kubernetes-server-linux-amd64.tar.gz
cd kubernetes
tar -xzvf  kubernetes-src.tar.gz

將二進(jìn)制文件拷貝到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp server/bin/* k8s@${node_ip}:/opt/k8s/bin/
    ssh k8s@${node_ip} "chmod +x /opt/k8s/bin/*"
  done

8. 部署高可用組件

本文檔講解使用 keepalived 和 haproxy 實(shí)現(xiàn) kube-apiserver 高可用的步驟:

  • keepalived 提供 kube-apiserver 對(duì)外服務(wù)的 VIP娇斑;
  • haproxy 監(jiān)聽 VIP策添,后端連接所有 kube-apiserver 實(shí)例,提供健康檢查和負(fù)載均衡功能毫缆;

運(yùn)行 keepalived 和 haproxy 的節(jié)點(diǎn)稱為 LB 節(jié)點(diǎn)唯竹。由于 keepalived 是一主多備運(yùn)行模式,故至少兩個(gè) LB 節(jié)點(diǎn)苦丁。

本文檔復(fù)用 master 節(jié)點(diǎn)的三臺(tái)機(jī)器浸颓,haproxy 監(jiān)聽的端口(8443) 需要與 kube-apiserver 的端口 6443 不同,避免沖突。

keepalived 在運(yùn)行過程中周期檢查本機(jī)的 haproxy 進(jìn)程狀態(tài)产上,如果檢測(cè)到 haproxy 進(jìn)程異常棵磷,則觸發(fā)重新選主的過程,VIP 將飄移到新選出來的主節(jié)點(diǎn)晋涣,從而實(shí)現(xiàn) VIP 的高可用仪媒。

所有組件(如 kubeclt、apiserver谢鹊、controller-manager算吩、scheduler 等)都通過 VIP 和 haproxy 監(jiān)聽的 8443 端口訪問 kube-apiserver 服務(wù)。

安裝軟件包

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "yum install -y keepalived haproxy"
  done

配置和下發(fā) haproxy 配置文件

haproxy 配置文件:

cat > haproxy.cfg <<EOF
global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    stats socket /var/run/haproxy-admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    nbproc 1

defaults
    log     global
    timeout connect 5000
    timeout client  10m
    timeout server  10m

listen  admin_stats
    bind 0.0.0.0:10080
    mode http
    log 127.0.0.1 local0 err
    stats refresh 30s
    stats uri /status
    stats realm welcome login\ Haproxy
    stats auth admin:123456
    stats hide-version
    stats admin if TRUE

listen kube-master
    bind 0.0.0.0:8443
    mode tcp
    option tcplog
    balance source
    server 192.168.16.237 192.1686.16.237:6443 check inter 2000 fall 2 rise 2 weight 1
    server 192.168.16.238 192.168.16.238:6443 check inter 2000 fall 2 rise 2 weight 1
    server 192.168.16.239 192.168.16.239:6443 check inter 2000 fall 2 rise 2 weight 1
EOF
  • haproxy 在 10080 端口輸出 status 信息佃扼;
  • haproxy 監(jiān)聽所有接口的 8443 端口赌莺,該端口與環(huán)境變量 ${KUBE_APISERVER} 指定的端口必須一致;
  • server 字段列出所有 kube-apiserver 監(jiān)聽的 IP 和端口松嘶;

下發(fā) haproxy.cfg 到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp haproxy.cfg root@${node_ip}:/etc/haproxy
  done

起 haproxy 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl restart haproxy"
  done

檢查 haproxy 服務(wù)狀態(tài)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl status haproxy|grep Active"
  done

確保狀態(tài)為 active (running)艘狭,否則查看日志,確認(rèn)原因:

journalctl -u haproxy

檢查 haproxy 是否監(jiān)聽 8443 端口:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "netstat -lnpt|grep haproxy"
  done

確保輸出類似于:

tcp        0      0 0.0.0.0:8443            0.0.0.0:*               LISTEN      120583/haproxy

配置和下發(fā) keepalived 配置文件

keepalived 是一主(master)多備(backup)運(yùn)行模式翠订,故有兩種類型的配置文件巢音。master 配置文件只有一份幌绍,backup 配置文件視節(jié)點(diǎn)數(shù)目而定如失,對(duì)于本文檔而言,規(guī)劃如下:

  • master: 192.168.16.237
  • backup:192.168.16.238 192.168.16.239

master 配置文件:

source /opt/k8s/bin/environment.sh
cat  > keepalived-master.conf <<EOF
global_defs {
    router_id lb-master-105
}

vrrp_script check-haproxy {
    script "killall -0 haproxy"
    interval 5
    weight -30
}

vrrp_instance VI-kube-master {
    state MASTER
    priority 120
    dont_track_primary
    interface ${VIP_IF}
    virtual_router_id 68
    advert_int 3
    track_script {
        check-haproxy
    }
    virtual_ipaddress {
        ${MASTER_VIP}
    }
}
EOF
  • VIP 所在的接口(interface ${VIP_IF})為 eth0劣挫;
  • 使用 killall -0 haproxy 命令檢查所在節(jié)點(diǎn)的 haproxy 進(jìn)程是否正常似谁。如果異常則將權(quán)重減少(-30),從而觸發(fā)重新選主過程傲绣;
  • router_id、virtual_router_id 用于標(biāo)識(shí)屬于該 HA 的 keepalived 實(shí)例巩踏,如果有多套 keepalived HA秃诵,則必須各不相同;

backup 配置文件:

source /opt/k8s/bin/environment.sh
cat  > keepalived-backup.conf <<EOF
global_defs {
    router_id lb-backup-105
}

vrrp_script check-haproxy {
    script "killall -0 haproxy"
    interval 5
    weight -30
}

vrrp_instance VI-kube-master {
    state BACKUP
    priority 110
    dont_track_primary
    interface ${VIP_IF}
    virtual_router_id 68
    advert_int 3
    track_script {
        check-haproxy
    }
    virtual_ipaddress {
        ${MASTER_VIP}
    }
}
EOF
  • VIP 所在的接口(interface ${VIP_IF})為 eth0塞琼;
  • 使用 killall -0 haproxy 命令檢查所在節(jié)點(diǎn)的 haproxy 進(jìn)程是否正常菠净。如果異常則將權(quán)重減少(-30),從而觸發(fā)重新選主過程;
  • router_id彪杉、virtual_router_id 用于標(biāo)識(shí)屬于該 HA 的 keepalived 實(shí)例毅往,如果有多套 keepalived HA,則必須各不相同派近;
  • priority 的值必須小于 master 的值攀唯;

下發(fā) keepalived 配置文件

下發(fā) master 配置文件:

scp keepalived-master.conf root@192.168.16.237:/etc/keepalived/keepalived.conf

下發(fā) backup 配置文件:

scp keepalived-backup.conf root@192.168.16.238:/etc/keepalived/keepalived.conf
scp keepalived-backup.conf root@192.168.16.239:/etc/keepalived/keepalived.conf

起 keepalived 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl restart keepalived"
  done

檢查 keepalived 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl status keepalived|grep Active"
  done

確保狀態(tài)為 active (running),否則查看日志渴丸,確認(rèn)原因:

journalctl -u keepalived

查看 VIP 所在的節(jié)點(diǎn)侯嘀,確绷砹瑁可以 ping 通 VIP:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh ${node_ip} "/usr/sbin/ip addr show ${VIP_IF}"
    ssh ${node_ip} "ping -c 1 ${MASTER_VIP}"
  done

查看 haproxy 狀態(tài)頁面

瀏覽器訪問 ${MASTER_VIP}:10080/status 地址,查看 haproxy 狀態(tài)頁面:

image.png

9.部署 kube-apiserver 組件

本文檔講解使用 keepalived 和 haproxy 部署一個(gè) 3 節(jié)點(diǎn)高可用 master 集群的步驟残拐,對(duì)應(yīng)的 LB VIP 為環(huán)境變量 ${MASTER_VIP}途茫。

準(zhǔn)備工作

下載最新版本的二進(jìn)制文件、安裝和配置 flanneld 參考:06-0.部署master節(jié)點(diǎn).md

創(chuàng)建 kubernetes 證書和私鑰

創(chuàng)建證書簽名請(qǐng)求:

source /opt/k8s/bin/environment.sh
cat > kubernetes-csr.json <<EOF
{
  "CN": "kubernetes",
  "hosts": [
    "127.0.0.1",
    "192.168.16.237",
    "192.168.16.238",
    "192.168.16.239",
    "${MASTER_VIP}",
    "${CLUSTER_KUBERNETES_SVC_IP}",
    "kubernetes",
    "kubernetes.default",
    "kubernetes.default.svc",
    "kubernetes.default.svc.cluster",
    "kubernetes.default.svc.cluster.local"
  ],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF
  • hosts 字段指定授權(quán)使用該證書的 IP 或域名列表溪食,這里列出了 VIP 囊卜、apiserver 節(jié)點(diǎn) IP、kubernetes 服務(wù) IP 和域名错沃;

  • 域名最后字符不能是 .(如不能為 kubernetes.default.svc.cluster.local.)栅组,否則解析時(shí)失敗,提示: x509: cannot parse dnsName "kubernetes.default.svc.cluster.local."枢析;

  • 如果使用非 cluster.local 域名玉掸,如 opsnull.com,則需要修改域名列表中的最后兩個(gè)域名為:kubernetes.default.svc.opsnull醒叁、kubernetes.default.svc.opsnull.com

  • kubernetes 服務(wù) IP 是 apiserver 自動(dòng)創(chuàng)建的司浪,一般是 --service-cluster-ip-range 參數(shù)指定的網(wǎng)段的第一個(gè)IP,后續(xù)可以通過如下命令獲劝颜印:

    $ kubectl get svc kubernetes
    NAME         CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
    kubernetes   10.254.0.1   <none>        443/TCP   1d
    

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
  -ca-key=/etc/kubernetes/cert/ca-key.pem \
  -config=/etc/kubernetes/cert/ca-config.json \
  -profile=kubernetes kubernetes-csr.json | cfssljson -bare kubernetes
ls kubernetes*pem

將生成的證書和私鑰文件拷貝到 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /etc/kubernetes/cert/ && sudo chown -R k8s /etc/kubernetes/cert/"
    scp kubernetes*.pem k8s@${node_ip}:/etc/kubernetes/cert/
  done
  • k8s 賬戶可以讀寫 /etc/kubernetes/cert/ 目錄啊易;

創(chuàng)建加密配置文件

source /opt/k8s/bin/environment.sh
cat > encryption-config.yaml <<EOF
kind: EncryptionConfig
apiVersion: v1
resources:
  - resources:
      - secrets
    providers:
      - aescbc:
          keys:
            - name: key1
              secret: ${ENCRYPTION_KEY}
      - identity: {}
EOF

將加密配置文件拷貝到 master 節(jié)點(diǎn)的 /etc/kubernetes 目錄下:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp encryption-config.yaml root@${node_ip}:/etc/kubernetes/
  done

替換后的 encryption-config.yaml 文件:encryption-config.yaml

創(chuàng)建 kube-apiserver systemd unit 模板文件

source /opt/k8s/bin/environment.sh
cat > kube-apiserver.service.template <<EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=network.target

[Service]
ExecStart=/opt/k8s/bin/kube-apiserver \\
  --enable-admission-plugins=Initializers,NamespaceLifecycle,NodeRestriction,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota \\
  --anonymous-auth=false \\
  --experimental-encryption-provider-config=/etc/kubernetes/encryption-config.yaml \\
  --advertise-address=##NODE_IP## \\
  --bind-address=##NODE_IP## \\
  --insecure-port=0 \\
  --authorization-mode=Node,RBAC \\
  --runtime-config=api/all \\
  --enable-bootstrap-token-auth \\
  --service-cluster-ip-range=${SERVICE_CIDR} \\
  --service-node-port-range=${NODE_PORT_RANGE} \\
  --tls-cert-file=/etc/kubernetes/cert/kubernetes.pem \\
  --tls-private-key-file=/etc/kubernetes/cert/kubernetes-key.pem \\
  --client-ca-file=/etc/kubernetes/cert/ca.pem \\
  --kubelet-client-certificate=/etc/kubernetes/cert/kubernetes.pem \\
  --kubelet-client-key=/etc/kubernetes/cert/kubernetes-key.pem \\
  --service-account-key-file=/etc/kubernetes/cert/ca-key.pem \\
  --etcd-cafile=/etc/kubernetes/cert/ca.pem \\
  --etcd-certfile=/etc/kubernetes/cert/kubernetes.pem \\
  --etcd-keyfile=/etc/kubernetes/cert/kubernetes-key.pem \\
  --etcd-servers=${ETCD_ENDPOINTS} \\
  --enable-swagger-ui=true \\
  --allow-privileged=true \\
  --apiserver-count=3 \\
  --audit-log-maxage=30 \\
  --audit-log-maxbackup=3 \\
  --audit-log-maxsize=100 \\
  --audit-log-path=/var/log/kube-apiserver-audit.log \\
  --event-ttl=1h \\
  --alsologtostderr=true \\
  --logtostderr=false \\
  --log-dir=/var/log/kubernetes \\
  --v=2
Restart=on-failure
RestartSec=5
Type=notify
User=k8s
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF
  • --experimental-encryption-provider-config:啟用加密特性;
  • --authorization-mode=Node,RBAC: 開啟 Node 和 RBAC 授權(quán)模式饮睬,拒絕未授權(quán)的請(qǐng)求租谈;
  • --enable-admission-plugins:啟用 ServiceAccountNodeRestriction
  • --service-account-key-file:簽名 ServiceAccount Token 的公鑰文件捆愁,kube-controller-manager 的 --service-account-private-key-file 指定私鑰文件割去,兩者配對(duì)使用;
  • --tls-*-file:指定 apiserver 使用的證書昼丑、私鑰和 CA 文件呻逆。--client-ca-file 用于驗(yàn)證 client (kue-controller-manager、kube-scheduler矾克、kubelet页慷、kube-proxy 等)請(qǐng)求所帶的證書;
  • --kubelet-client-certificate胁附、--kubelet-client-key:如果指定,則使用 https 訪問 kubelet APIs滓彰;需要為證書對(duì)應(yīng)的用戶(上面 kubernetes*.pem 證書的用戶為 kubernetes) 用戶定義 RBAC 規(guī)則控妻,否則訪問 kubelet API 時(shí)提示未授權(quán);
  • --bind-address: 不能為 127.0.0.1揭绑,否則外界不能訪問它的安全端口 6443弓候;
  • --insecure-port=0:關(guān)閉監(jiān)聽非安全端口(8080)郎哭;
  • --service-cluster-ip-range: 指定 Service Cluster IP 地址段;
  • --service-node-port-range: 指定 NodePort 的端口范圍菇存;
  • --runtime-config=api/all=true: 啟用所有版本的 APIs夸研,如 autoscaling/v2alpha1;
  • --enable-bootstrap-token-auth:啟用 kubelet bootstrap 的 token 認(rèn)證依鸥;
  • --apiserver-count=3:指定集群運(yùn)行模式亥至,多臺(tái) kube-apiserver 會(huì)通過 leader 選舉產(chǎn)生一個(gè)工作節(jié)點(diǎn),其它節(jié)點(diǎn)處于阻塞狀態(tài)贱迟;
  • User=k8s:使用 k8s 賬戶運(yùn)行姐扮;

為各節(jié)點(diǎn)創(chuàng)建和分發(fā) kube-apiserver systemd unit 文件

替換模板文件中的變量,為各節(jié)點(diǎn)創(chuàng)建 systemd unit 文件:

source /opt/k8s/bin/environment.sh
for (( i=0; i < 3; i++ ))
  do
    sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" kube-apiserver.service.template > kube-apiserver-${NODE_IPS[i]}.service 
  done
ls kube-apiserver*.service
  • NODE_NAMES 和 NODE_IPS 為相同長度的 bash 數(shù)組衣吠,分別為節(jié)點(diǎn)名稱和對(duì)應(yīng)的 IP茶敏;

分發(fā)生成的 systemd unit 文件:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/log/kubernetes && chown -R k8s /var/log/kubernetes"
    scp kube-apiserver-${node_ip}.service root@${node_ip}:/etc/systemd/system/kube-apiserver.service
  done
  • 必須先創(chuàng)建日志目錄;
  • 文件重命名為 kube-apiserver.service;

替換后的 unit 文件:kube-apiserver.service

啟動(dòng) kube-apiserver 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-apiserver && systemctl restart kube-apiserver"
  done

檢查 kube-apiserver 運(yùn)行狀態(tài)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl status kube-apiserver |grep 'Active:'"
  done

確保狀態(tài)為 active (running)缚俏,否則到 master 節(jié)點(diǎn)查看日志惊搏,確認(rèn)原因:

journalctl -u kube-apiserver

打印 kube-apiserver 寫入 etcd 的數(shù)據(jù)

source /opt/k8s/bin/environment.sh
ETCDCTL_API=3 etcdctl \
    --endpoints=${ETCD_ENDPOINTS} \
    --cacert=/etc/kubernetes/cert/ca.pem \
    --cert=/etc/etcd/cert/etcd.pem \
    --key=/etc/etcd/cert/etcd-key.pem \
    get /registry/ --prefix --keys-only

檢查集群信息

$ kubectl cluster-info
Kubernetes master is running at https://192.168.16.240:8443

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

$ kubectl get all --all-namespaces
NAMESPACE   NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
default     service/kubernetes   ClusterIP   10.254.0.1   <none>        443/TCP   35m

$ kubectl get componentstatuses
NAME                 STATUS      MESSAGE                                                                                        ERROR
controller-manager   Unhealthy   Get http://127.0.0.1:10252/healthz: dial tcp 127.0.0.1:10252: getsockopt: connection refused
scheduler            Unhealthy   Get http://127.0.0.1:10251/healthz: dial tcp 127.0.0.1:10251: getsockopt: connection refused
etcd-1               Healthy     {"health":"true"}
etcd-0               Healthy     {"health":"true"}
etcd-2               Healthy     {"health":"true"}

注意:

  1. 如果執(zhí)行 kubectl 命令式時(shí)輸出如下錯(cuò)誤信息,則說明使用的 ~/.kube/config 文件不對(duì)忧换,請(qǐng)切換到正確的賬戶后再執(zhí)行該命令:

    The connection to the server localhost:8080 was refused - did you specify the right host or port?

  2. 執(zhí)行 kubectl get componentstatuses 命令時(shí)恬惯,apiserver 默認(rèn)向 127.0.0.1 發(fā)送請(qǐng)求。當(dāng) controller-manager包雀、scheduler 以集群模式運(yùn)行時(shí)宿崭,有可能和 kube-apiserver 不在一臺(tái)機(jī)器上,這時(shí) controller-manager 或 scheduler 的狀態(tài)為 Unhealthy才写,但實(shí)際上它們工作正常葡兑。

檢查 kube-apiserver 監(jiān)聽的端口

$ sudo netstat -lnpt|grep kube
tcp        0      0 192.168.16.237:6443     0.0.0.0:*               LISTEN      13075/kube-apiserve
  • 6443: 接收 https 請(qǐng)求的安全端口,對(duì)所有請(qǐng)求做認(rèn)證和授權(quán)赞草;
  • 由于關(guān)閉了非安全端口讹堤,故沒有監(jiān)聽 8080;

授予 kubernetes 證書訪問 kubelet API 的權(quán)限

在執(zhí)行 kubectl exec厨疙、run洲守、logs 等命令時(shí),apiserver 會(huì)轉(zhuǎn)發(fā)到 kubelet沾凄。這里定義 RBAC 規(guī)則梗醇,授權(quán) apiserver 調(diào)用 kubelet API。

$ kubectl create clusterrolebinding kube-apiserver:kubelet-apis --clusterrole=system:kubelet-api-admin --user kubernetes

10 部署高可用 kube-controller-manager 集群

本文檔介紹部署高可用 kube-controller-manager 集群的步驟撒蟀。

該集群包含 3 個(gè)節(jié)點(diǎn)叙谨,啟動(dòng)后將通過競爭選舉機(jī)制產(chǎn)生一個(gè) leader 節(jié)點(diǎn),其它節(jié)點(diǎn)為阻塞狀態(tài)保屯。當(dāng) leader 節(jié)點(diǎn)不可用后手负,剩余節(jié)點(diǎn)將再次進(jìn)行選舉產(chǎn)生新的 leader 節(jié)點(diǎn)涤垫,從而保證服務(wù)的可用性。

為保證通信安全竟终,本文檔先生成 x509 證書和私鑰蝠猬,kube-controller-manager 在如下兩種情況下使用該證書:

  1. 與 kube-apiserver 的安全端口通信時(shí);
  2. 安全端口(https,10252) 輸出 prometheus 格式的 metrics统捶;

準(zhǔn)備工作

下載最新版本的二進(jìn)制文件榆芦、安裝和配置 flanneld 參考:06-0.部署master節(jié)點(diǎn).md

創(chuàng)建 kube-controller-manager 證書和私鑰

創(chuàng)建證書簽名請(qǐng)求:

cat > kube-controller-manager-csr.json <<EOF
{
    "CN": "system:kube-controller-manager",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "hosts": [
      "127.0.0.1",
      "192.168.16.237",
      "192.168.16.238",
      "192.168.16.239"
    ],
    "names": [
      {
        "C": "CN",
        "ST": "BeiJing",
        "L": "BeiJing",
        "O": "system:kube-controller-manager",
        "OU": "4Paradigm"
      }
    ]
}
EOF
  • hosts 列表包含所有 kube-controller-manager 節(jié)點(diǎn) IP;
  • CN 為 system:kube-controller-manager瘾境、O 為 system:kube-controller-manager歧杏,kubernetes 內(nèi)置的 ClusterRoleBindings system:kube-controller-manager 賦予 kube-controller-manager 工作所需的權(quán)限。

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
  -ca-key=/etc/kubernetes/cert/ca-key.pem \
  -config=/etc/kubernetes/cert/ca-config.json \
  -profile=kubernetes kube-controller-manager-csr.json | cfssljson -bare kube-controller-manager

將生成的證書和私鑰分發(fā)到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-controller-manager*.pem k8s@${node_ip}:/etc/kubernetes/cert/
  done

創(chuàng)建和分發(fā) kubeconfig 文件

kubeconfig 文件包含訪問 apiserver 的所有信息迷守,如 apiserver 地址犬绒、CA 證書和自身使用的證書;

source /opt/k8s/bin/environment.sh
kubectl config set-cluster kubernetes \
  --certificate-authority=/etc/kubernetes/cert/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=kube-controller-manager.kubeconfig

kubectl config set-credentials system:kube-controller-manager \
  --client-certificate=kube-controller-manager.pem \
  --client-key=kube-controller-manager-key.pem \
  --embed-certs=true \
  --kubeconfig=kube-controller-manager.kubeconfig

kubectl config set-context system:kube-controller-manager \
  --cluster=kubernetes \
  --user=system:kube-controller-manager \
  --kubeconfig=kube-controller-manager.kubeconfig

kubectl config use-context system:kube-controller-manager --kubeconfig=kube-controller-manager.kubeconfig

分發(fā) kubeconfig 到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-controller-manager.kubeconfig k8s@${node_ip}:/etc/kubernetes/
  done

創(chuàng)建和分發(fā) kube-controller-manager systemd unit 文件

source /opt/k8s/bin/environment.sh
cat > kube-controller-manager.service <<EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/GoogleCloudPlatform/kubernetes

[Service]
ExecStart=/opt/k8s/bin/kube-controller-manager \\
  --port=0 \\
  --secure-port=10252 \\
  --bind-address=127.0.0.1 \\
  --kubeconfig=/etc/kubernetes/kube-controller-manager.kubeconfig \\
  --service-cluster-ip-range=${SERVICE_CIDR} \\
  --cluster-name=kubernetes \\
  --cluster-signing-cert-file=/etc/kubernetes/cert/ca.pem \\
  --cluster-signing-key-file=/etc/kubernetes/cert/ca-key.pem \\
  --experimental-cluster-signing-duration=8760h \\
  --root-ca-file=/etc/kubernetes/cert/ca.pem \\
  --service-account-private-key-file=/etc/kubernetes/cert/ca-key.pem \\
  --leader-elect=true \\
  --feature-gates=RotateKubeletServerCertificate=true \\
  --controllers=*,bootstrapsigner,tokencleaner \\
  --horizontal-pod-autoscaler-use-rest-clients=true \\
  --horizontal-pod-autoscaler-sync-period=10s \\
  --tls-cert-file=/etc/kubernetes/cert/kube-controller-manager.pem \\
  --tls-private-key-file=/etc/kubernetes/cert/kube-controller-manager-key.pem \\
  --use-service-account-credentials=true \\
  --alsologtostderr=true \\
  --logtostderr=false \\
  --log-dir=/var/log/kubernetes \\
  --v=2
Restart=on
Restart=on-failure
RestartSec=5
User=k8s

[Install]
WantedBy=multi-user.target
EOF
  • --port=0:關(guān)閉監(jiān)聽 http /metrics 的請(qǐng)求兑凿,同時(shí) --address 參數(shù)無效凯力,--bind-address 參數(shù)有效;
  • --secure-port=10252礼华、--bind-address=0.0.0.0: 在所有網(wǎng)絡(luò)接口監(jiān)聽 10252 端口的 https /metrics 請(qǐng)求咐鹤;
  • --kubeconfig:指定 kubeconfig 文件路徑,kube-controller-manager 使用它連接和驗(yàn)證 kube-apiserver圣絮;
  • --cluster-signing-*-file:簽名 TLS Bootstrap 創(chuàng)建的證書祈惶;
  • --experimental-cluster-signing-duration:指定 TLS Bootstrap 證書的有效期;
  • --root-ca-file:放置到容器 ServiceAccount 中的 CA 證書扮匠,用來對(duì) kube-apiserver 的證書進(jìn)行校驗(yàn)捧请;
  • --service-account-private-key-file:簽名 ServiceAccount 中 Token 的私鑰文件,必須和 kube-apiserver 的 --service-account-key-file 指定的公鑰文件配對(duì)使用棒搜;
  • --service-cluster-ip-range :指定 Service Cluster IP 網(wǎng)段疹蛉,必須和 kube-apiserver 中的同名參數(shù)一致;
  • --leader-elect=true:集群運(yùn)行模式力麸,啟用選舉功能可款;被選為 leader 的節(jié)點(diǎn)負(fù)責(zé)處理工作,其它節(jié)點(diǎn)為阻塞狀態(tài)克蚂;
  • --feature-gates=RotateKubeletServerCertificate=true:開啟 kublet server 證書的自動(dòng)更新特性闺鲸;
  • --controllers=*,bootstrapsigner,tokencleaner:啟用的控制器列表,tokencleaner 用于自動(dòng)清理過期的 Bootstrap token埃叭;
  • --horizontal-pod-autoscaler-*:custom metrics 相關(guān)參數(shù)翠拣,支持 autoscaling/v2alpha1;
  • --tls-cert-file游盲、--tls-private-key-file:使用 https 輸出 metrics 時(shí)使用的 Server 證書和秘鑰误墓;
  • --use-service-account-credentials=true:
  • User=k8s:使用 k8s 賬戶運(yùn)行;

kube-controller-manager 不對(duì)請(qǐng)求 https metrics 的 Client 證書進(jìn)行校驗(yàn)益缎,故不需要指定 --tls-ca-file 參數(shù)谜慌,而且該參數(shù)已被淘汰。

完整 unit 見 kube-controller-manager.service

分發(fā) systemd unit 文件到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-controller-manager.service root@${node_ip}:/etc/systemd/system/
  done

kube-controller-manager 的權(quán)限

ClusteRole: system:kube-controller-manager 的權(quán)限很小莺奔,只能創(chuàng)建 secret欣范、serviceaccount 等資源對(duì)象,各 controller 的權(quán)限分散到 ClusterRole system:controller:XXX 中令哟。

需要在 kube-controller-manager 的啟動(dòng)參數(shù)中添加 --use-service-account-credentials=true 參數(shù)恼琼,這樣 main controller 會(huì)為各 controller 創(chuàng)建對(duì)應(yīng)的 ServiceAccount XXX-controller。

內(nèi)置的 ClusterRoleBinding system:controller:XXX 將賦予各 XXX-controller ServiceAccount 對(duì)應(yīng)的 ClusterRole system:controller:XXX 權(quán)限屏富。

啟動(dòng) kube-controller-manager 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/log/kubernetes && chown -R k8s /var/log/kubernetes"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-controller-manager && systemctl restart kube-controller-manager"
  done
  • 必須先創(chuàng)建日志目錄晴竞;

檢查服務(wù)運(yùn)行狀態(tài)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "systemctl status kube-controller-manager|grep Active"
  done

確保狀態(tài)為 active (running),否則查看日志狠半,確認(rèn)原因:

$ journalctl -u kube-controller-manager

查看輸出的 metric

注意:以下命令在 kube-controller-manager 節(jié)點(diǎn)上執(zhí)行噩死。

kube-controller-manager 監(jiān)聽 10252 端口,接收 https 請(qǐng)求:

$ sudo netstat -lnpt|grep kube-controll
tcp        0      0 127.0.0.1:10252         0.0.0.0:*               LISTEN      18377/kube-controll
$ curl -s --cacert /etc/kubernetes/cert/ca.pem https://127.0.0.1:10252/metrics |head
# HELP ClusterRoleAggregator_adds Total number of adds handled by workqueue: ClusterRoleAggregator
# TYPE ClusterRoleAggregator_adds counter
ClusterRoleAggregator_adds 3
# HELP ClusterRoleAggregator_depth Current depth of workqueue: ClusterRoleAggregator
# TYPE ClusterRoleAggregator_depth gauge
ClusterRoleAggregator_depth 0
# HELP ClusterRoleAggregator_queue_latency How long an item stays in workqueueClusterRoleAggregator before being requested.
# TYPE ClusterRoleAggregator_queue_latency summary
ClusterRoleAggregator_queue_latency{quantile="0.5"} 57018
ClusterRoleAggregator_queue_latency{quantile="0.9"} 57268
  • curl --cacert CA 證書用來驗(yàn)證 kube-controller-manager https server 證書神年;

測(cè)試 kube-controller-manager 集群的高可用

停掉一個(gè)或兩個(gè)節(jié)點(diǎn)的 kube-controller-manager 服務(wù)已维,觀察其它節(jié)點(diǎn)的日志,看是否獲取了 leader 權(quán)限已日。

查看當(dāng)前的 leader

$ kubectl get endpoints kube-controller-manager --namespace=kube-system  -o yaml
apiVersion: v1
kind: Endpoints
metadata:
  annotations:
    control-plane.alpha.kubernetes.io/leader: '{"holderIdentity":"kube-node2_084534e2-6cc4-11e8-a418-5254001f5b65","leaseDurationSeconds":15,"acquireTime":"2018-06-10T15:40:33Z","renewTime":"2018-06-10T16:19:08Z","leaderTransitions":12}'
  creationTimestamp: 2018-06-10T13:59:42Z
  name: kube-controller-manager
  namespace: kube-system
  resourceVersion: "4540"
  selfLink: /api/v1/namespaces/kube-system/endpoints/kube-controller-manager
  uid: 862cc048-6cb6-11e8-96fa-525400ba84c6

可見垛耳,當(dāng)前的 leader 為 kube-node2 節(jié)點(diǎn)。

部署高可用 kube-controller-manager 集群

本文檔介紹部署高可用 kube-controller-manager 集群的步驟飘千。

該集群包含 3 個(gè)節(jié)點(diǎn)堂鲜,啟動(dòng)后將通過競爭選舉機(jī)制產(chǎn)生一個(gè) leader 節(jié)點(diǎn),其它節(jié)點(diǎn)為阻塞狀態(tài)占婉。當(dāng) leader 節(jié)點(diǎn)不可用后泡嘴,剩余節(jié)點(diǎn)將再次進(jìn)行選舉產(chǎn)生新的 leader 節(jié)點(diǎn),從而保證服務(wù)的可用性逆济。

為保證通信安全酌予,本文檔先生成 x509 證書和私鑰,kube-controller-manager 在如下兩種情況下使用該證書:

  1. 與 kube-apiserver 的安全端口通信時(shí);
  2. 安全端口(https奖慌,10252) 輸出 prometheus 格式的 metrics抛虫;

準(zhǔn)備工作

下載最新版本的二進(jìn)制文件、安裝和配置 flanneld 參考:06-0.部署master節(jié)點(diǎn).md

創(chuàng)建 kube-controller-manager 證書和私鑰

創(chuàng)建證書簽名請(qǐng)求:

cat > kube-controller-manager-csr.json <<EOF
{
    "CN": "system:kube-controller-manager",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "hosts": [
      "127.0.0.1",
      "192.168.16.237",
      "192.168.16.238",
      "192.168.16.239"
    ],
    "names": [
      {
        "C": "CN",
        "ST": "BeiJing",
        "L": "BeiJing",
        "O": "system:kube-controller-manager",
        "OU": "4Paradigm"
      }
    ]
}
EOF
  • hosts 列表包含所有 kube-controller-manager 節(jié)點(diǎn) IP简僧;
  • CN 為 system:kube-controller-manager建椰、O 為 system:kube-controller-manager,kubernetes 內(nèi)置的 ClusterRoleBindings system:kube-controller-manager 賦予 kube-controller-manager 工作所需的權(quán)限岛马。

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
  -ca-key=/etc/kubernetes/cert/ca-key.pem \
  -config=/etc/kubernetes/cert/ca-config.json \
  -profile=kubernetes kube-controller-manager-csr.json | cfssljson -bare kube-controller-manager

將生成的證書和私鑰分發(fā)到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-controller-manager*.pem k8s@${node_ip}:/etc/kubernetes/cert/
  done

創(chuàng)建和分發(fā) kubeconfig 文件

kubeconfig 文件包含訪問 apiserver 的所有信息棉姐,如 apiserver 地址蛇尚、CA 證書和自身使用的證書;

source /opt/k8s/bin/environment.sh
kubectl config set-cluster kubernetes \
  --certificate-authority=/etc/kubernetes/cert/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=kube-controller-manager.kubeconfig

kubectl config set-credentials system:kube-controller-manager \
  --client-certificate=kube-controller-manager.pem \
  --client-key=kube-controller-manager-key.pem \
  --embed-certs=true \
  --kubeconfig=kube-controller-manager.kubeconfig

kubectl config set-context system:kube-controller-manager \
  --cluster=kubernetes \
  --user=system:kube-controller-manager \
  --kubeconfig=kube-controller-manager.kubeconfig

kubectl config use-context system:kube-controller-manager --kubeconfig=kube-controller-manager.kubeconfig

分發(fā) kubeconfig 到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-controller-manager.kubeconfig k8s@${node_ip}:/etc/kubernetes/
  done

創(chuàng)建和分發(fā) kube-controller-manager systemd unit 文件

source /opt/k8s/bin/environment.sh
cat > kube-controller-manager.service <<EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/GoogleCloudPlatform/kubernetes

[Service]
ExecStart=/opt/k8s/bin/kube-controller-manager \\
  --port=0 \\
  --secure-port=10252 \\
  --bind-address=127.0.0.1 \\
  --kubeconfig=/etc/kubernetes/kube-controller-manager.kubeconfig \\
  --service-cluster-ip-range=${SERVICE_CIDR} \\
  --cluster-name=kubernetes \\
  --cluster-signing-cert-file=/etc/kubernetes/cert/ca.pem \\
  --cluster-signing-key-file=/etc/kubernetes/cert/ca-key.pem \\
  --experimental-cluster-signing-duration=8760h \\
  --root-ca-file=/etc/kubernetes/cert/ca.pem \\
  --service-account-private-key-file=/etc/kubernetes/cert/ca-key.pem \\
  --leader-elect=true \\
  --feature-gates=RotateKubeletServerCertificate=true \\
  --controllers=*,bootstrapsigner,tokencleaner \\
  --horizontal-pod-autoscaler-use-rest-clients=true \\
  --horizontal-pod-autoscaler-sync-period=10s \\
  --tls-cert-file=/etc/kubernetes/cert/kube-controller-manager.pem \\
  --tls-private-key-file=/etc/kubernetes/cert/kube-controller-manager-key.pem \\
  --use-service-account-credentials=true \\
  --alsologtostderr=true \\
  --logtostderr=false \\
  --log-dir=/var/log/kubernetes \\
  --v=2
Restart=on
Restart=on-failure
RestartSec=5
User=k8s

[Install]
WantedBy=multi-user.target
EOF
  • --port=0:關(guān)閉監(jiān)聽 http /metrics 的請(qǐng)求臀玄,同時(shí) --address 參數(shù)無效尽纽,--bind-address 參數(shù)有效;
  • --secure-port=10252乃坤、--bind-address=0.0.0.0: 在所有網(wǎng)絡(luò)接口監(jiān)聽 10252 端口的 https /metrics 請(qǐng)求苛让;
  • --kubeconfig:指定 kubeconfig 文件路徑,kube-controller-manager 使用它連接和驗(yàn)證 kube-apiserver湿诊;
  • --cluster-signing-*-file:簽名 TLS Bootstrap 創(chuàng)建的證書狱杰;
  • --experimental-cluster-signing-duration:指定 TLS Bootstrap 證書的有效期;
  • --root-ca-file:放置到容器 ServiceAccount 中的 CA 證書厅须,用來對(duì) kube-apiserver 的證書進(jìn)行校驗(yàn)仿畸;
  • --service-account-private-key-file:簽名 ServiceAccount 中 Token 的私鑰文件,必須和 kube-apiserver 的 --service-account-key-file 指定的公鑰文件配對(duì)使用九杂;
  • --service-cluster-ip-range :指定 Service Cluster IP 網(wǎng)段颁湖,必須和 kube-apiserver 中的同名參數(shù)一致;
  • --leader-elect=true:集群運(yùn)行模式例隆,啟用選舉功能甥捺;被選為 leader 的節(jié)點(diǎn)負(fù)責(zé)處理工作,其它節(jié)點(diǎn)為阻塞狀態(tài)镀层;
  • --feature-gates=RotateKubeletServerCertificate=true:開啟 kublet server 證書的自動(dòng)更新特性镰禾;
  • --controllers=*,bootstrapsigner,tokencleaner:啟用的控制器列表,tokencleaner 用于自動(dòng)清理過期的 Bootstrap token唱逢;
  • --horizontal-pod-autoscaler-*:custom metrics 相關(guān)參數(shù)吴侦,支持 autoscaling/v2alpha1;
  • --tls-cert-file坞古、--tls-private-key-file:使用 https 輸出 metrics 時(shí)使用的 Server 證書和秘鑰备韧;
  • --use-service-account-credentials=true:
  • User=k8s:使用 k8s 賬戶運(yùn)行;

kube-controller-manager 不對(duì)請(qǐng)求 https metrics 的 Client 證書進(jìn)行校驗(yàn)痪枫,故不需要指定 --tls-ca-file 參數(shù)织堂,而且該參數(shù)已被淘汰。

完整 unit 見 kube-controller-manager.service

分發(fā) systemd unit 文件到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-controller-manager.service root@${node_ip}:/etc/systemd/system/
  done

kube-controller-manager 的權(quán)限

ClusteRole: system:kube-controller-manager 的權(quán)限很小奶陈,只能創(chuàng)建 secret易阳、serviceaccount 等資源對(duì)象,各 controller 的權(quán)限分散到 ClusterRole system:controller:XXX 中吃粒。

需要在 kube-controller-manager 的啟動(dòng)參數(shù)中添加 --use-service-account-credentials=true 參數(shù)潦俺,這樣 main controller 會(huì)為各 controller 創(chuàng)建對(duì)應(yīng)的 ServiceAccount XXX-controller。

內(nèi)置的 ClusterRoleBinding system:controller:XXX 將賦予各 XXX-controller ServiceAccount 對(duì)應(yīng)的 ClusterRole system:controller:XXX 權(quán)限。

啟動(dòng) kube-controller-manager 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/log/kubernetes && chown -R k8s /var/log/kubernetes"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-controller-manager && systemctl restart kube-controller-manager"
  done
  • 必須先創(chuàng)建日志目錄事示;

檢查服務(wù)運(yùn)行狀態(tài)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "systemctl status kube-controller-manager|grep Active"
  done

確保狀態(tài)為 active (running)早像,否則查看日志,確認(rèn)原因:

$ journalctl -u kube-controller-manager

查看輸出的 metric

注意:以下命令在 kube-controller-manager 節(jié)點(diǎn)上執(zhí)行很魂。

kube-controller-manager 監(jiān)聽 10252 端口扎酷,接收 https 請(qǐng)求:

$ sudo netstat -lnpt|grep kube-controll
tcp        0      0 127.0.0.1:10252         0.0.0.0:*               LISTEN      18377/kube-controll
$ curl -s --cacert /etc/kubernetes/cert/ca.pem https://127.0.0.1:10252/metrics |head
# HELP ClusterRoleAggregator_adds Total number of adds handled by workqueue: ClusterRoleAggregator
# TYPE ClusterRoleAggregator_adds counter
ClusterRoleAggregator_adds 3
# HELP ClusterRoleAggregator_depth Current depth of workqueue: ClusterRoleAggregator
# TYPE ClusterRoleAggregator_depth gauge
ClusterRoleAggregator_depth 0
# HELP ClusterRoleAggregator_queue_latency How long an item stays in workqueueClusterRoleAggregator before being requested.
# TYPE ClusterRoleAggregator_queue_latency summary
ClusterRoleAggregator_queue_latency{quantile="0.5"} 57018
ClusterRoleAggregator_queue_latency{quantile="0.9"} 57268
  • curl --cacert CA 證書用來驗(yàn)證 kube-controller-manager https server 證書;

測(cè)試 kube-controller-manager 集群的高可用

停掉一個(gè)或兩個(gè)節(jié)點(diǎn)的 kube-controller-manager 服務(wù)遏匆,觀察其它節(jié)點(diǎn)的日志,看是否獲取了 leader 權(quán)限谁榜。

查看當(dāng)前的 leader

$ kubectl get endpoints kube-controller-manager --namespace=kube-system  -o yaml
apiVersion: v1
kind: Endpoints
metadata:
  annotations:
    control-plane.alpha.kubernetes.io/leader: '{"holderIdentity":"kube-node2_084534e2-6cc4-11e8-a418-5254001f5b65","leaseDurationSeconds":15,"acquireTime":"2018-06-10T15:40:33Z","renewTime":"2018-06-10T16:19:08Z","leaderTransitions":12}'
  creationTimestamp: 2018-06-10T13:59:42Z
  name: kube-controller-manager
  namespace: kube-system
  resourceVersion: "4540"
  selfLink: /api/v1/namespaces/kube-system/endpoints/kube-controller-manager
  uid: 862cc048-6cb6-11e8-96fa-525400ba84c6

可見幅聘,當(dāng)前的 leader 為 kube-node2 節(jié)點(diǎn)。

11. 部署高可用 kube-scheduler 集群

本文檔介紹部署高可用 kube-scheduler 集群的步驟窃植。

該集群包含 3 個(gè)節(jié)點(diǎn)帝蒿,啟動(dòng)后將通過競爭選舉機(jī)制產(chǎn)生一個(gè) leader 節(jié)點(diǎn),其它節(jié)點(diǎn)為阻塞狀態(tài)巷怜。當(dāng) leader 節(jié)點(diǎn)不可用后葛超,剩余節(jié)點(diǎn)將再次進(jìn)行選舉產(chǎn)生新的 leader 節(jié)點(diǎn),從而保證服務(wù)的可用性延塑。

為保證通信安全绣张,本文檔先生成 x509 證書和私鑰,kube-scheduler 在如下兩種情況下使用該證書:

  1. 與 kube-apiserver 的安全端口通信;
  2. 安全端口(https关带,10251) 輸出 prometheus 格式的 metrics侥涵;

準(zhǔn)備工作

下載最新版本的二進(jìn)制文件、安裝和配置 flanneld 參考:06-0.部署master節(jié)點(diǎn).md

創(chuàng)建 kube-scheduler 證書和私鑰

創(chuàng)建證書簽名請(qǐng)求:

cat > kube-scheduler-csr.json <<EOF
{
    "CN": "system:kube-scheduler",
    "hosts": [
      "127.0.0.1",
      "192.168.16.237",
      "192.168.16.238",
      "192.168.16.239"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
      {
        "C": "CN",
        "ST": "BeiJing",
        "L": "BeiJing",
        "O": "system:kube-scheduler",
        "OU": "4Paradigm"
      }
    ]
}
EOF
  • hosts 列表包含所有 kube-scheduler 節(jié)點(diǎn) IP宋雏;
  • CN 為 system:kube-scheduler芜飘、O 為 system:kube-scheduler,kubernetes 內(nèi)置的 ClusterRoleBindings system:kube-scheduler 將賦予 kube-scheduler 工作所需的權(quán)限磨总。

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
  -ca-key=/etc/kubernetes/cert/ca-key.pem \
  -config=/etc/kubernetes/cert/ca-config.json \
  -profile=kubernetes kube-scheduler-csr.json | cfssljson -bare kube-scheduler

創(chuàng)建和分發(fā) kubeconfig 文件

kubeconfig 文件包含訪問 apiserver 的所有信息嗦明,如 apiserver 地址、CA 證書和自身使用的證書蚪燕;

source /opt/k8s/bin/environment.sh
kubectl config set-cluster kubernetes \
  --certificate-authority=/etc/kubernetes/cert/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=kube-scheduler.kubeconfig

kubectl config set-credentials system:kube-scheduler \
  --client-certificate=kube-scheduler.pem \
  --client-key=kube-scheduler-key.pem \
  --embed-certs=true \
  --kubeconfig=kube-scheduler.kubeconfig

kubectl config set-context system:kube-scheduler \
  --cluster=kubernetes \
  --user=system:kube-scheduler \
  --kubeconfig=kube-scheduler.kubeconfig

kubectl config use-context system:kube-scheduler --kubeconfig=kube-scheduler.kubeconfig
  • 上一步創(chuàng)建的證書娶牌、私鑰以及 kube-apiserver 地址被寫入到 kubeconfig 文件中;

分發(fā) kubeconfig 到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-scheduler.kubeconfig k8s@${node_ip}:/etc/kubernetes/
  done

創(chuàng)建和分發(fā) kube-scheduler systemd unit 文件

cat > kube-scheduler.service <<EOF
[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/GoogleCloudPlatform/kubernetes

[Service]
ExecStart=/opt/k8s/bin/kube-scheduler \\
  --address=127.0.0.1 \\
  --kubeconfig=/etc/kubernetes/kube-scheduler.kubeconfig \\
  --leader-elect=true \\
  --alsologtostderr=true \\
  --logtostderr=false \\
  --log-dir=/var/log/kubernetes \\
  --v=2
Restart=on-failure
RestartSec=5
User=k8s

[Install]
WantedBy=multi-user.target
EOF
  • --address:在 127.0.0.1:10251 端口接收 http /metrics 請(qǐng)求邻薯;kube-scheduler 目前還不支持接收 https 請(qǐng)求裙戏;
  • --kubeconfig:指定 kubeconfig 文件路徑,kube-scheduler 使用它連接和驗(yàn)證 kube-apiserver厕诡;
  • --leader-elect=true:集群運(yùn)行模式累榜,啟用選舉功能;被選為 leader 的節(jié)點(diǎn)負(fù)責(zé)處理工作,其它節(jié)點(diǎn)為阻塞狀態(tài)壹罚;
  • User=k8s:使用 k8s 賬戶運(yùn)行葛作;

完整 unit 見 kube-scheduler.service

分發(fā) systemd unit 文件到所有 master 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp kube-scheduler.service root@${node_ip}:/etc/systemd/system/
  done

啟動(dòng) kube-scheduler 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/log/kubernetes && chown -R k8s /var/log/kubernetes"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-scheduler && systemctl restart kube-scheduler"
  done
  • 必須先創(chuàng)建日志目錄猖凛;

檢查服務(wù)運(yùn)行狀態(tài)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "systemctl status kube-scheduler|grep Active"
  done

確保狀態(tài)為 active (running)赂蠢,否則查看日志,確認(rèn)原因:

journalctl -u kube-scheduler

查看輸出的 metric

注意:以下命令在 kube-scheduler 節(jié)點(diǎn)上執(zhí)行辨泳。

kube-scheduler 監(jiān)聽 10251 端口虱岂,接收 http 請(qǐng)求:

$ sudo netstat -lnpt|grep kube-sche
tcp        0      0 127.0.0.1:10251         0.0.0.0:*               LISTEN      23783/kube-schedule

$ curl -s http://127.0.0.1:10251/metrics |head
# HELP apiserver_audit_event_total Counter of audit events generated and sent to the audit backend.
# TYPE apiserver_audit_event_total counter
apiserver_audit_event_total 0
# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 9.7715e-05
go_gc_duration_seconds{quantile="0.25"} 0.000107676
go_gc_duration_seconds{quantile="0.5"} 0.00017868
go_gc_duration_seconds{quantile="0.75"} 0.000262444
go_gc_duration_seconds{quantile="1"} 0.001205223

測(cè)試 kube-scheduler 集群的高可用

隨便找一個(gè)或兩個(gè) master 節(jié)點(diǎn),停掉 kube-scheduler 服務(wù)菠红,看其它節(jié)點(diǎn)是否獲取了 leader 權(quán)限(systemd 日志)第岖。

查看當(dāng)前的 leader

$ kubectl get endpoints kube-scheduler --namespace=kube-system  -o yaml
apiVersion: v1
kind: Endpoints
metadata:
  annotations:
    control-plane.alpha.kubernetes.io/leader: '{"holderIdentity":"kube-node3_61f34593-6cc8-11e8-8af7-5254002f288e","leaseDurationSeconds":15,"acquireTime":"2018-06-10T16:09:56Z","renewTime":"2018-06-10T16:20:54Z","leaderTransitions":1}'
  creationTimestamp: 2018-06-10T16:07:33Z
  name: kube-scheduler
  namespace: kube-system
  resourceVersion: "4645"
  selfLink: /api/v1/namespaces/kube-system/endpoints/kube-scheduler
  uid: 62382d98-6cc8-11e8-96fa-525400ba84c6

可見,當(dāng)前的 leader 為 kube-node3 節(jié)點(diǎn)试溯。

12.部署 worker 節(jié)點(diǎn)

kubernetes work 節(jié)點(diǎn)運(yùn)行如下組件:

  • docker
  • kubelet
  • kube-proxy

安裝依賴包

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "yum install -y epel-release"
    ssh root@${node_ip} "yum install -y conntrack ipvsadm ipset jq iptables curl sysstat libseccomp && /usr/sbin/modprobe ip_vs "
  done

13.部署 docker 組件

docker 是容器的運(yùn)行環(huán)境蔑滓,管理它的生命周期。kubelet 通過 Container Runtime Interface (CRI) 與 docker 進(jìn)行交互遇绞〖ぃ可以二進(jìn)制或者yum方式安裝

13.1 二進(jìn)制方式安裝

使用docker info查看存儲(chǔ)驅(qū)動(dòng) 如果是vfs的話 需要更換驅(qū)動(dòng),否則會(huì)有一些問題.

安裝依賴包

下載和分發(fā) docker 二進(jìn)制文件

https://download.docker.com/linux/static/stable/x86_64/ 頁面下載最新發(fā)布包:

wget https://download.docker.com/linux/static/stable/x86_64/docker-18.03.1-ce.tgz
tar -xvf docker-18.03.1-ce.tgz

分發(fā)二進(jìn)制文件到所有 worker 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp docker/docker*  k8s@${node_ip}:/opt/k8s/bin/
    ssh k8s@${node_ip} "chmod +x /opt/k8s/bin/*"
  done

創(chuàng)建和分發(fā) systemd unit 文件

cat > docker.service <<"EOF"
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.io

[Service]
Environment="PATH=/opt/k8s/bin:/bin:/sbin:/usr/bin:/usr/sbin"
EnvironmentFile=-/run/flannel/docker
ExecStart=/opt/k8s/bin/dockerd --log-level=error $DOCKER_NETWORK_OPTIONS
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target
EOF
  • EOF 前后有雙引號(hào),這樣 bash 不會(huì)替換文檔中的變量摹闽,如 $DOCKER_NETWORK_OPTIONS蹄咖;

  • dockerd 運(yùn)行時(shí)會(huì)調(diào)用其它 docker 命令,如 docker-proxy钩骇,所以需要將 docker 命令所在的目錄加到 PATH 環(huán)境變量中比藻;

  • flanneld 啟動(dòng)時(shí)將網(wǎng)絡(luò)配置寫入 /run/flannel/docker 文件中,dockerd 啟動(dòng)前讀取該文件中的環(huán)境變量 DOCKER_NETWORK_OPTIONS 倘屹,然后設(shè)置 docker0 網(wǎng)橋網(wǎng)段银亲;

  • 如果指定了多個(gè) EnvironmentFile 選項(xiàng),則必須將 /run/flannel/docker 放在最后(確保 docker0 使用 flanneld 生成的 bip 參數(shù))纽匙;

  • docker 需要以 root 用于運(yùn)行务蝠;

  • docker 從 1.13 版本開始,可能將 iptables FORWARD chain的默認(rèn)策略設(shè)置為DROP烛缔,從而導(dǎo)致 ping 其它 Node 上的 Pod IP 失敗馏段,遇到這種情況時(shí),需要手動(dòng)設(shè)置策略為 ACCEPT

    $ sudo iptables -P FORWARD ACCEPT
    

    并且把以下命令寫入 /etc/rc.local 文件中践瓷,防止節(jié)點(diǎn)重啟iptables FORWARD chain的默認(rèn)策略又還原為DROP

    /sbin/iptables -P FORWARD ACCEPT
    

完整 unit 見 docker.service

分發(fā) systemd unit 文件到所有 worker 機(jī)器:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    scp docker.service root@${node_ip}:/etc/systemd/system/
  done

配置和分發(fā) docker 配置文件

使用國內(nèi)的倉庫鏡像服務(wù)器以加快 pull image 的速度院喜,同時(shí)增加下載的并發(fā)數(shù) (需要重啟 dockerd 生效):

cat > docker-daemon.json <<EOF
{
    "registry-mirrors": ["https://hub-mirror.c.163.com", "https://docker.mirrors.ustc.edu.cn"],
    "max-concurrent-downloads": 20
}
EOF

分發(fā) docker 配置文件到所有 work 節(jié)點(diǎn):

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p  /etc/docker/"
    scp docker-daemon.json root@${node_ip}:/etc/docker/daemon.json
  done

啟動(dòng) docker 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "systemctl stop firewalld && systemctl disable firewalld"
    ssh root@${node_ip} "/usr/sbin/iptables -F && /usr/sbin/iptables -X && /usr/sbin/iptables -F -t nat && /usr/sbin/iptables -X -t nat"
    ssh root@${node_ip} "/usr/sbin/iptables -P FORWARD ACCEPT"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable docker && systemctl restart docker"
    ssh root@${node_ip} 'for intf in /sys/devices/virtual/net/docker0/brif/*; do echo 1 > $intf/hairpin_mode; done'
    ssh root@${node_ip} "sudo sysctl -p /etc/sysctl.d/kubernetes.conf"
  done
  • 關(guān)閉 firewalld(centos7)/ufw(ubuntu16.04),否則可能會(huì)重復(fù)創(chuàng)建 iptables 規(guī)則晕翠;
  • 清理舊的 iptables rules 和 chains 規(guī)則喷舀;
  • 開啟 docker0 網(wǎng)橋下虛擬網(wǎng)卡的 hairpin 模式;

檢查服務(wù)運(yùn)行狀態(tài)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "systemctl status docker|grep Active"
  done

確保狀態(tài)為 active (running)砍濒,否則查看日志,確認(rèn)原因:

$ journalctl -u docker

檢查 docker0 網(wǎng)橋

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "/usr/sbin/ip addr show flannel.1 && /usr/sbin/ip addr show docker0"
  done

確認(rèn)各 work 節(jié)點(diǎn)的 docker0 網(wǎng)橋和 flannel.1 接口的 IP 處于同一個(gè)網(wǎng)段中(如下 172.30.39.0 和 172.30.39.1):

3: flannel.1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UNKNOWN group default
    link/ether ce:2f:d6:53:e5:f3 brd ff:ff:ff:ff:ff:ff
    inet 172.30.39.0/32 scope global flannel.1
      valid_lft forever preferred_lft forever
    inet6 fe80::cc2f:d6ff:fe53:e5f3/64 scope link
      valid_lft forever preferred_lft forever
4: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:bf:65:16:5c brd ff:ff:ff:ff:ff:ff
    inet 172.30.39.1/24 brd 172.30.39.255 scope global docker0
      valid_lft forever preferred_lft forever

13.2所有節(jié)點(diǎn)yum 方式安裝

安裝docker需要的依賴包

yum install -y yum-utils \
  device-mapper-persistent-data \
  lvm2

安裝docker的yum源硫麻,通過yum源進(jìn)行下載

yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo

安裝docker

yum -y install docker-ce-18.03.1.ce

修改啟動(dòng)文件

 vim /usr/lib/systemd/system/docker.service
### 12行添加
EnvironmentFile=-/run/flannel/docker
### 13行修改
ExecStart=/usr/bin/dockerd  --log-level=error $DOCKER_NETWORK_OPTIONS

啟動(dòng)docker

確認(rèn)各 work 節(jié)點(diǎn)的 docker0 網(wǎng)橋和 flannel.1 接口的 IP 處于同一個(gè)網(wǎng)段中(如下 172.30.39.0 和 172.30.39.1):

systemctl  daemon-reload 
systemctl  start docker 

其他步驟和二進(jìn)制方式類似爸邢,開啟防火墻轉(zhuǎn)發(fā)等

14.部署 kubelet 組件

kublet 運(yùn)行在每個(gè) worker 節(jié)點(diǎn)上,接收 kube-apiserver 發(fā)送的請(qǐng)求拿愧,管理 Pod 容器杠河,執(zhí)行交互式命令,如 exec浇辜、run券敌、logs 等。

kublet 啟動(dòng)時(shí)自動(dòng)向 kube-apiserver 注冊(cè)節(jié)點(diǎn)信息奢赂,內(nèi)置的 cadvisor 統(tǒng)計(jì)和監(jiān)控節(jié)點(diǎn)的資源使用情況陪白。

為確保安全,本文檔只開啟接收 https 請(qǐng)求的安全端口膳灶,對(duì)請(qǐng)求進(jìn)行認(rèn)證和授權(quán),拒絕未授權(quán)的訪問(如 apiserver立由、heapster)轧钓。

下載和分發(fā) kubelet 二進(jìn)制文件

創(chuàng)建 kubelet bootstrap kubeconfig 文件

source /opt/k8s/bin/environment.sh
for node_name in ${NODE_NAMES[@]}
  do
    echo ">>> ${node_name}"

    # 創(chuàng)建 token
    export BOOTSTRAP_TOKEN=$(kubeadm token create \
      --description kubelet-bootstrap-token \
      --groups system:bootstrappers:${node_name} \
      --kubeconfig ~/.kube/config)

    # 設(shè)置集群參數(shù)
    kubectl config set-cluster kubernetes \
      --certificate-authority=/etc/kubernetes/cert/ca.pem \
      --embed-certs=true \
      --server=${KUBE_APISERVER} \
      --kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig

    # 設(shè)置客戶端認(rèn)證參數(shù)
    kubectl config set-credentials kubelet-bootstrap \
      --token=${BOOTSTRAP_TOKEN} \
      --kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig

    # 設(shè)置上下文參數(shù)
    kubectl config set-context default \
      --cluster=kubernetes \
      --user=kubelet-bootstrap \
      --kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig

    # 設(shè)置默認(rèn)上下文
    kubectl config use-context default --kubeconfig=kubelet-bootstrap-${node_name}.kubeconfig
  done
  • 證書中寫入 Token 而非證書,證書后續(xù)由 controller-manager 創(chuàng)建锐膜。

查看 kubeadm 為各節(jié)點(diǎn)創(chuàng)建的 token:

$ kubeadm token list --kubeconfig ~/.kube/config
TOKEN                     TTL       EXPIRES                     USAGES                   DESCRIPTION               EXTRA GROUPS
k0s2bj.7nvw1zi1nalyz4gz   23h       2018-06-14T15:14:31+08:00   authentication,signing   kubelet-bootstrap-token   system:bootstrappers:kube-node1
mkus5s.vilnjk3kutei600l   23h       2018-06-14T15:14:32+08:00   authentication,signing   kubelet-bootstrap-token   system:bootstrappers:kube-node3
zkiem5.0m4xhw0jc8r466nk   23h       2018-06-14T15:14:32+08:00   authentication,signing   kubelet-bootstrap-token   system:bootstrappers:kube-node2
  • 創(chuàng)建的 token 有效期為 1 天毕箍,超期后將不能再被使用,且會(huì)被 kube-controller-manager 的 tokencleaner 清理(如果啟用該 controller 的話)道盏;
  • kube-apiserver 接收 kubelet 的 bootstrap token 后而柑,將請(qǐng)求的 user 設(shè)置為 system:bootstrap:,group 設(shè)置為 system:bootstrappers荷逞;

各 token 關(guān)聯(lián)的 Secret:

$ kubectl get secrets  -n kube-system
NAME                     TYPE                                  DATA      AGE
bootstrap-token-k0s2bj   bootstrap.kubernetes.io/token         7         1m
bootstrap-token-mkus5s   bootstrap.kubernetes.io/token         7         1m
bootstrap-token-zkiem5   bootstrap.kubernetes.io/token         7         1m
default-token-99st7      kubernetes.io/service-account-token   3         2d

分發(fā) bootstrap kubeconfig 文件到所有 worker 節(jié)點(diǎn)

source /opt/k8s/bin/environment.sh
for node_name in ${NODE_NAMES[@]}
  do
    echo ">>> ${node_name}"
    scp kubelet-bootstrap-${node_name}.kubeconfig k8s@${node_name}:/etc/kubernetes/kubelet-bootstrap.kubeconfig
  done

創(chuàng)建和分發(fā) kubelet 參數(shù)配置文件

從 v1.10 開始媒咳,kubelet 部分參數(shù)需在配置文件中配置,kubelet --help 會(huì)提示:

DEPRECATED: This parameter should be set via the config file specified by the Kubelet's --config flag

創(chuàng)建 kubelet 參數(shù)配置模板文件:

source /opt/k8s/bin/environment.sh
cat > kubelet.config.json.template <<EOF
{
  "kind": "KubeletConfiguration",
  "apiVersion": "kubelet.config.k8s.io/v1beta1",
  "authentication": {
    "x509": {
      "clientCAFile": "/etc/kubernetes/cert/ca.pem"
    },
    "webhook": {
      "enabled": true,
      "cacheTTL": "2m0s"
    },
    "anonymous": {
      "enabled": false
    }
  },
  "authorization": {
    "mode": "Webhook",
    "webhook": {
      "cacheAuthorizedTTL": "5m0s",
      "cacheUnauthorizedTTL": "30s"
    }
  },
  "address": "##NODE_IP##",
  "port": 10250,
  "readOnlyPort": 0,
  "cgroupDriver": "cgroupfs",
  "hairpinMode": "promiscuous-bridge",
  "serializeImagePulls": false,
  "featureGates": {
    "RotateKubeletClientCertificate": true,
    "RotateKubeletServerCertificate": true
  },
  "clusterDomain": "${CLUSTER_DNS_DOMAIN}",
  "clusterDNS": ["${CLUSTER_DNS_SVC_IP}"]
}
EOF
  • address:API 監(jiān)聽地址种远,不能為 127.0.0.1涩澡,否則 kube-apiserver、heapster 等不能調(diào)用 kubelet 的 API坠敷;
  • readOnlyPort=0:關(guān)閉只讀端口(默認(rèn) 10255)妙同,等效為未指定;
  • authentication.anonymous.enabled:設(shè)置為 false膝迎,不允許匿名?訪問 10250 端口粥帚;
  • authentication.x509.clientCAFile:指定簽名客戶端證書的 CA 證書,開啟 HTTP 證書認(rèn)證限次;
  • authentication.webhook.enabled=true:開啟 HTTPs bearer token 認(rèn)證芒涡;
  • 對(duì)于未通過 x509 證書和 webhook 認(rèn)證的請(qǐng)求(kube-apiserver 或其他客戶端),將被拒絕,提示 Unauthorized拖陆;
  • authroization.mode=Webhook:kubelet 使用 SubjectAccessReview API 查詢 kube-apiserver 某 user弛槐、group 是否具有操作資源的權(quán)限(RBAC);
  • featureGates.RotateKubeletClientCertificate依啰、featureGates.RotateKubeletServerCertificate:自動(dòng) rotate 證書乎串,證書的有效期取決于 kube-controller-manager 的 --experimental-cluster-signing-duration 參數(shù);
  • 需要 root 賬戶運(yùn)行速警;

為各節(jié)點(diǎn)創(chuàng)建和分發(fā) kubelet 配置文件:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do 
    echo ">>> ${node_ip}"
    sed -e "s/##NODE_IP##/${node_ip}/" kubelet.config.json.template > kubelet.config-${node_ip}.json
    scp kubelet.config-${node_ip}.json root@${node_ip}:/etc/kubernetes/kubelet.config.json
  done

替換后的 kubelet.config.json 文件: kubelet.config.json

創(chuàng)建和分發(fā) kubelet systemd unit 文件

創(chuàng)建 kubelet systemd unit 文件模板:

cat > kubelet.service.template <<EOF
[Unit]
Description=Kubernetes Kubelet
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=docker.service
Requires=docker.service

[Service]
WorkingDirectory=/var/lib/kubelet
ExecStart=/opt/k8s/bin/kubelet \\
  --bootstrap-kubeconfig=/etc/kubernetes/kubelet-bootstrap.kubeconfig \\
  --cert-dir=/etc/kubernetes/cert \\
  --kubeconfig=/etc/kubernetes/kubelet.kubeconfig \\
  --config=/etc/kubernetes/kubelet.config.json \\
  --hostname-override=##NODE_NAME## \\
  --pod-infra-container-image=registry.access.redhat.com/rhel7/pod-infrastructure:latest \\
  --allow-privileged=true \\
  --alsologtostderr=true \\
  --logtostderr=false \\
  --log-dir=/var/log/kubernetes \\
  --v=2
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
  • 如果設(shè)置了 --hostname-override 選項(xiàng)叹誉,則 kube-proxy 也需要設(shè)置該選項(xiàng),否則會(huì)出現(xiàn)找不到 Node 的情況闷旧;
  • --bootstrap-kubeconfig:指向 bootstrap kubeconfig 文件长豁,kubelet 使用該文件中的用戶名和 token 向 kube-apiserver 發(fā)送 TLS Bootstrapping 請(qǐng)求;
  • K8S approve kubelet 的 csr 請(qǐng)求后忙灼,在 --cert-dir 目錄創(chuàng)建證書和私鑰文件匠襟,然后寫入 --kubeconfig 文件;

替換后的 unit 文件:kubelet.service

為各節(jié)點(diǎn)創(chuàng)建和分發(fā) kubelet systemd unit 文件:

source /opt/k8s/bin/environment.sh
for node_name in ${NODE_NAMES[@]}
  do 
    echo ">>> ${node_name}"
    sed -e "s/##NODE_NAME##/${node_name}/" kubelet.service.template > kubelet-${node_name}.service
    scp kubelet-${node_name}.service root@${node_name}:/etc/systemd/system/kubelet.service
  done

Bootstrap Token Auth 和授予權(quán)限

kublet 啟動(dòng)時(shí)查找配置的 --kubeletconfig 文件是否存在该园,如果不存在則使用 --bootstrap-kubeconfig 向 kube-apiserver 發(fā)送證書簽名請(qǐng)求 (CSR)酸舍。

kube-apiserver 收到 CSR 請(qǐng)求后,對(duì)其中的 Token 進(jìn)行認(rèn)證(事先使用 kubeadm 創(chuàng)建的 token)里初,認(rèn)證通過后將請(qǐng)求的 user 設(shè)置為 system:bootstrap:啃勉,group 設(shè)置為 system:bootstrappers,這一過程稱為 Bootstrap Token Auth双妨。

默認(rèn)情況下淮阐,這個(gè) user 和 group 沒有創(chuàng)建 CSR 的權(quán)限,kubelet 啟動(dòng)失敗刁品,錯(cuò)誤日志如下:

$ sudo journalctl -u kubelet -a |grep -A 2 'certificatesigningrequests'
May 06 06:42:36 kube-node1 kubelet[26986]: F0506 06:42:36.314378   26986 server.go:233] failed to run Kubelet: cannot create certificate signing request: certificatesigningrequests.certificates.k8s.io is forbidden: User "system:bootstrap:lemy40" cannot create certificatesigningrequests.certificates.k8s.io at the cluster scope
May 06 06:42:36 kube-node1 systemd[1]: kubelet.service: Main process exited, code=exited, status=255/n/a
May 06 06:42:36 kube-node1 systemd[1]: kubelet.service: Failed with result 'exit-code'.

解決辦法是:創(chuàng)建一個(gè) clusterrolebinding泣特,將 group system:bootstrappers 和 clusterrole system:node-bootstrapper 綁定:

$ kubectl create clusterrolebinding kubelet-bootstrap --clusterrole=system:node-bootstrapper --group=system:bootstrappers

啟動(dòng) kubelet 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/lib/kubelet"
    ssh root@${node_ip} "/usr/sbin/swapoff -a"
    ssh root@${node_ip} "mkdir -p /var/log/kubernetes && chown -R k8s /var/log/kubernetes"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kubelet && systemctl restart kubelet"
  done
  • 關(guān)閉 swap 分區(qū),否則 kubelet 會(huì)啟動(dòng)失斞普铩群扶;
  • 必須先創(chuàng)建工作和日志目錄;
$ journalctl -u kubelet |tail
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.388242   22343 feature_gate.go:226] feature gates: &{{} map[RotateKubeletServerCertificate:true RotateKubeletClientCertificate:true]}
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.394342   22343 mount_linux.go:211] Detected OS with systemd
Jun 13 16:05:40 kube-node2 kubelet[22343]: W0613 16:05:40.394494   22343 cni.go:171] Unable to update cni config: No networks found in /etc/cni/net.d
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.399508   22343 server.go:376] Version: v1.10.4
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.399583   22343 feature_gate.go:226] feature gates: &{{} map[RotateKubeletServerCertificate:true RotateKubeletClientCertificate:true]}
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.399736   22343 plugins.go:89] No cloud provider specified.
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.399752   22343 server.go:492] No cloud provider specified: "" from the config file: ""
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.399777   22343 bootstrap.go:58] Using bootstrap kubeconfig to generate TLS client cert, key and kubeconfig file
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.446068   22343 csr.go:105] csr for this node already exists, reusing
Jun 13 16:05:40 kube-node2 kubelet[22343]: I0613 16:05:40.453761   22343 csr.go:113] csr for this node is still valid

kubelet 啟動(dòng)后使用 --bootstrap-kubeconfig 向 kube-apiserver 發(fā)送 CSR 請(qǐng)求镀裤,當(dāng)這個(gè) CSR 被 approve 后竞阐,kube-controller-manager 為 kubelet 創(chuàng)建 TLS 客戶端證書、私鑰和 --kubeletconfig 文件暑劝。

注意:kube-controller-manager 需要配置 --cluster-signing-cert-file--cluster-signing-key-file 參數(shù)骆莹,才會(huì)為 TLS Bootstrap 創(chuàng)建證書和私鑰。

$ kubectl get csr
NAME                                                   AGE       REQUESTOR                 CONDITION
node-csr-QzuuQiuUfcSdp3j5W4B2UOuvQ_n9aTNHAlrLzVFiqrk   43s       system:bootstrap:zkiem5   Pending
node-csr-oVbPmU-ikVknpynwu0Ckz_MvkAO_F1j0hmbcDa__sGA   27s       system:bootstrap:mkus5s   Pending
node-csr-u0E1-ugxgotO_9FiGXo8DkD6a7-ew8sX2qPE6KPS2IY   13m       system:bootstrap:k0s2bj   Pending

$ kubectl get nodes
No resources found.
  • 三個(gè) work 節(jié)點(diǎn)的 csr 均處于 pending 狀態(tài)担猛;

approve kubelet CSR 請(qǐng)求

可以手動(dòng)或自動(dòng) approve CSR 請(qǐng)求幕垦。推薦使用自動(dòng)的方式丢氢,因?yàn)閺?v1.8 版本開始,可以自動(dòng)輪轉(zhuǎn)approve csr 后生成的證書先改。

手動(dòng) approve CSR 請(qǐng)求

查看 CSR 列表:

$ kubectl get csr
NAME                                                   AGE       REQUESTOR                 CONDITION
node-csr-QzuuQiuUfcSdp3j5W4B2UOuvQ_n9aTNHAlrLzVFiqrk   43s       system:bootstrap:zkiem5   Pending
node-csr-oVbPmU-ikVknpynwu0Ckz_MvkAO_F1j0hmbcDa__sGA   27s       system:bootstrap:mkus5s   Pending
node-csr-u0E1-ugxgotO_9FiGXo8DkD6a7-ew8sX2qPE6KPS2IY   13m       system:bootstrap:k0s2bj   Pending

approve CSR:

$ kubectl certificate approve node-csr-QzuuQiuUfcSdp3j5W4B2UOuvQ_n9aTNHAlrLzVFiqrk
certificatesigningrequest.certificates.k8s.io "node-csr-QzuuQiuUfcSdp3j5W4B2UOuvQ_n9aTNHAlrLzVFiqrk" approved

查看 Approve 結(jié)果:

$ kubectl describe  csr node-csr-QzuuQiuUfcSdp3j5W4B2UOuvQ_n9aTNHAlrLzVFiqrk
Name:               node-csr-QzuuQiuUfcSdp3j5W4B2UOuvQ_n9aTNHAlrLzVFiqrk
Labels:             <none>
Annotations:        <none>
CreationTimestamp:  Wed, 13 Jun 2018 16:05:04 +0800
Requesting User:    system:bootstrap:zkiem5
Status:             Approved
Subject:
         Common Name:    system:node:kube-node2
         Serial Number:
         Organization:   system:nodes
Events:  <none>
  • Requesting User:請(qǐng)求 CSR 的用戶疚察,kube-apiserver 對(duì)它進(jìn)行認(rèn)證和授權(quán);
  • Subject:請(qǐng)求簽名的證書信息仇奶;
  • 證書的 CN 是 system:node:kube-node2循诉, Organization 是 system:nodes骂蓖,kube-apiserver 的 Node 授權(quán)模式會(huì)授予該證書的相關(guān)權(quán)限;

自動(dòng) approve CSR 請(qǐng)求

創(chuàng)建三個(gè) ClusterRoleBinding礁遵,分別用于自動(dòng) approve client靖避、renew client允趟、renew server 證書:

cat > csr-crb.yaml <<EOF
 # Approve all CSRs for the group "system:bootstrappers"
 kind: ClusterRoleBinding
 apiVersion: rbac.authorization.k8s.io/v1
 metadata:
   name: auto-approve-csrs-for-group
 subjects:
 - kind: Group
   name: system:bootstrappers
   apiGroup: rbac.authorization.k8s.io
 roleRef:
   kind: ClusterRole
   name: system:certificates.k8s.io:certificatesigningrequests:nodeclient
   apiGroup: rbac.authorization.k8s.io
---
 # To let a node of the group "system:nodes" renew its own credentials
 kind: ClusterRoleBinding
 apiVersion: rbac.authorization.k8s.io/v1
 metadata:
   name: node-client-cert-renewal
 subjects:
 - kind: Group
   name: system:nodes
   apiGroup: rbac.authorization.k8s.io
 roleRef:
   kind: ClusterRole
   name: system:certificates.k8s.io:certificatesigningrequests:selfnodeclient
   apiGroup: rbac.authorization.k8s.io
---
# A ClusterRole which instructs the CSR approver to approve a node requesting a
# serving cert matching its client cert.
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: approve-node-server-renewal-csr
rules:
- apiGroups: ["certificates.k8s.io"]
  resources: ["certificatesigningrequests/selfnodeserver"]
  verbs: ["create"]
---
 # To let a node of the group "system:nodes" renew its own server credentials
 kind: ClusterRoleBinding
 apiVersion: rbac.authorization.k8s.io/v1
 metadata:
   name: node-server-cert-renewal
 subjects:
 - kind: Group
   name: system:nodes
   apiGroup: rbac.authorization.k8s.io
 roleRef:
   kind: ClusterRole
   name: approve-node-server-renewal-csr
   apiGroup: rbac.authorization.k8s.io
EOF
  • auto-approve-csrs-for-group:自動(dòng) approve node 的第一次 CSR蔑匣; 注意第一次 CSR 時(shí)恩急,請(qǐng)求的 Group 為 system:bootstrappers;
  • node-client-cert-renewal:自動(dòng) approve node 后續(xù)過期的 client 證書氯庆,自動(dòng)生成的證書 Group 為 system:nodes;
  • node-server-cert-renewal:自動(dòng) approve node 后續(xù)過期的 server 證書蹭秋,自動(dòng)生成的證書 Group 為 system:nodes;

生效配置:

$ kubectl apply -f csr-crb.yaml

查看 kublet 的情況

等待一段時(shí)間(1-10 分鐘),三個(gè)節(jié)點(diǎn)的 CSR 都被自動(dòng) approve:

$ kubectl get csr
NAME                                                   AGE       REQUESTOR                 CONDITION
csr-98h25                                              6m        system:node:kube-node2    Approved,Issued
csr-lb5c9                                              7m        system:node:kube-node3    Approved,Issued
csr-m2hn4                                              14m       system:node:kube-node1    Approved,Issued
node-csr-7q7i0q4MF_K2TSEJj16At4CJFLlJkHIqei6nMIAaJCU   28m       system:bootstrap:k0s2bj   Approved,Issued
node-csr-ND77wk2P8k2lHBtgBaObiyYw0uz1Um7g2pRvveMF-c4   35m       system:bootstrap:mkus5s   Approved,Issued
node-csr-Nysmrw55nnM48NKwEJuiuCGmZoxouK4N8jiEHBtLQso   6m        system:bootstrap:zkiem5   Approved,Issued
node-csr-QzuuQiuUfcSdp3j5W4B2UOuvQ_n9aTNHAlrLzVFiqrk   1h        system:bootstrap:zkiem5   Approved,Issued
node-csr-oVbPmU-ikVknpynwu0Ckz_MvkAO_F1j0hmbcDa__sGA   1h        system:bootstrap:mkus5s   Approved,Issued
node-csr-u0E1-ugxgotO_9FiGXo8DkD6a7-ew8sX2qPE6KPS2IY   1h        system:bootstrap:k0s2bj   Approved,Issued

所有節(jié)點(diǎn)均 ready:

$ kubectl get nodes
NAME         STATUS    ROLES     AGE       VERSION
kube-node1   Ready     <none>    18m       v1.10.4
kube-node2   Ready     <none>    10m       v1.10.4
kube-node3   Ready     <none>    11m       v1.10.4

kube-controller-manager 為各 node 生成了 kubeconfig 文件和公私鑰:

$ ls -l /etc/kubernetes/kubelet.kubeconfig
-rw------- 1 root root 2293 Jun 13 17:07 /etc/kubernetes/kubelet.kubeconfig

$ ls -l /etc/kubernetes/cert/|grep kubelet
-rw-r--r-- 1 root root 1046 Jun 13 17:07 kubelet-client.crt
-rw------- 1 root root  227 Jun 13 17:07 kubelet-client.key
-rw------- 1 root root 1334 Jun 13 17:07 kubelet-server-2018-06-13-17-07-45.pem
lrwxrwxrwx 1 root root   58 Jun 13 17:07 kubelet-server-current.pem -> /etc/kubernetes/cert/kubelet-server-2018-06-13-17-07-45.pem
  • kubelet-server 證書會(huì)周期輪轉(zhuǎn)堤撵;

kubelet 提供的 API 接口

kublet 啟動(dòng)后監(jiān)聽多個(gè)端口感凤,用于接收 kube-apiserver 或其它組件發(fā)送的請(qǐng)求:

$ sudo netstat -lnpt|grep kubelet
tcp        0      0 192.168.16.237:4194     0.0.0.0:*               LISTEN      2490/kubelet
tcp        0      0 127.0.0.1:10248         0.0.0.0:*               LISTEN      2490/kubelet
tcp        0      0 192.168.16.237:10250    0.0.0.0:*               LISTEN      2490/kubelet
  • 4194: cadvisor http 服務(wù);
  • 10248: healthz http 服務(wù)粒督;
  • 10250: https API 服務(wù);注意:未開啟只讀端口 10255禽翼;

例如執(zhí)行 kubectl ec -it nginx-ds-5rmws -- sh 命令時(shí)屠橄,kube-apiserver 會(huì)向 kubelet 發(fā)送如下請(qǐng)求:

POST /exec/default/nginx-ds-5rmws/my-nginx?command=sh&input=1&output=1&tty=1

kubelet 接收 10250 端口的 https 請(qǐng)求:

  • /pods、/runningpods
  • /metrics闰挡、/metrics/cadvisor锐墙、/metrics/probes
  • /spec
  • /stats、/stats/container
  • /logs
  • /run/长酗、"/exec/", "/attach/", "/portForward/", "/containerLogs/" 等管理溪北;

詳情參考:https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/server/server.go#L434:3

由于關(guān)閉了匿名認(rèn)證,同時(shí)開啟了 webhook 授權(quán)夺脾,所有訪問 10250 端口 https API 的請(qǐng)求都需要被認(rèn)證和授權(quán)之拨。

預(yù)定義的 ClusterRole system:kubelet-api-admin 授予訪問 kubelet 所有 API 的權(quán)限:

$ kubectl describe clusterrole system:kubelet-api-admin
Name:         system:kubelet-api-admin
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate=true
PolicyRule:
  Resources      Non-Resource URLs  Resource Names  Verbs
  ---------      -----------------  --------------  -----
  nodes          []                 []              [get list watch proxy]
  nodes/log      []                 []              [*]
  nodes/metrics  []                 []              [*]
  nodes/proxy    []                 []              [*]
  nodes/spec     []                 []              [*]
  nodes/stats    []                 []              [*]

kublet api 認(rèn)證和授權(quán)

kublet 配置了如下認(rèn)證參數(shù):

  • authentication.anonymous.enabled:設(shè)置為 false,不允許匿名?訪問 10250 端口咧叭;
  • authentication.x509.clientCAFile:指定簽名客戶端證書的 CA 證書蚀乔,開啟 HTTPs 證書認(rèn)證;
  • authentication.webhook.enabled=true:開啟 HTTPs bearer token 認(rèn)證菲茬;

同時(shí)配置了如下授權(quán)參數(shù):

  • authroization.mode=Webhook:開啟 RBAC 授權(quán)吉挣;

kubelet 收到請(qǐng)求后派撕,使用 clientCAFile 對(duì)證書簽名進(jìn)行認(rèn)證,或者查詢 bearer token 是否有效睬魂。如果兩者都沒通過终吼,則拒絕請(qǐng)求,提示 Unauthorized:

$ curl -s --cacert /etc/kubernetes/cert/ca.pem https://192.168.16.237:10250/metrics
Unauthorized

$ curl -s --cacert /etc/kubernetes/cert/ca.pem -H "Authorization: Bearer 123456" https://192.168.16.237:10250/metrics
Unauthorized

通過認(rèn)證后氯哮,kubelet 使用 SubjectAccessReview API 向 kube-apiserver 發(fā)送請(qǐng)求际跪,查詢證書或 token 對(duì)應(yīng)的 user、group 是否有操作資源的權(quán)限(RBAC)蛙粘;

證書認(rèn)證和授權(quán):

$ # 權(quán)限不足的證書垫卤;
$ curl -s --cacert /etc/kubernetes/cert/ca.pem --cert /etc/kubernetes/cert/kube-controller-manager.pem --key /etc/kubernetes/cert/kube-controller-manager-key.pem https://192.168.16.237:10250/metrics
Forbidden (user=system:kube-controller-manager, verb=get, resource=nodes, subresource=metrics)

$ # 使用部署 kubectl 命令行工具時(shí)創(chuàng)建的、具有最高權(quán)限的 admin 證書出牧;
$ curl -s --cacert /etc/kubernetes/cert/ca.pem --cert ./admin.pem --key ./admin-key.pem https://192.168.16.237:10250/metrics|head
# HELP apiserver_client_certificate_expiration_seconds Distribution of the remaining lifetime on the certificate used to authenticate a request.
# TYPE apiserver_client_certificate_expiration_seconds histogram
apiserver_client_certificate_expiration_seconds_bucket{le="0"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="21600"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="43200"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="86400"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="172800"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="345600"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="604800"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="2.592e+06"} 0
  • --cacert穴肘、--cert--key 的參數(shù)值必須是文件路徑舔痕,如上面的 ./admin.pem 不能省略 ./评抚,否則返回 401 Unauthorized

bear token 認(rèn)證和授權(quán):

創(chuàng)建一個(gè) ServiceAccount伯复,將它和 ClusterRole system:kubelet-api-admin 綁定慨代,從而具有調(diào)用 kubelet API 的權(quán)限:

kubectl create sa kubelet-api-test
kubectl create clusterrolebinding kubelet-api-test --clusterrole=system:kubelet-api-admin --serviceaccount=default:kubelet-api-test
SECRET=$(kubectl get secrets | grep kubelet-api-test | awk '{print $1}')
TOKEN=$(kubectl describe secret ${SECRET} | grep -E '^token' | awk '{print $2}')
echo ${TOKEN}

$ curl -s --cacert /etc/kubernetes/cert/ca.pem -H "Authorization: Bearer ${TOKEN}" https://192.168.16.237:10250/metrics|head
# HELP apiserver_client_certificate_expiration_seconds Distribution of the remaining lifetime on the certificate used to authenticate a request.
# TYPE apiserver_client_certificate_expiration_seconds histogram
apiserver_client_certificate_expiration_seconds_bucket{le="0"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="21600"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="43200"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="86400"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="172800"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="345600"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="604800"} 0
apiserver_client_certificate_expiration_seconds_bucket{le="2.592e+06"} 0

cadvisor 和 metrics

cadvisor 統(tǒng)計(jì)?所在節(jié)點(diǎn)各容器的資源(CPU、內(nèi)存啸如、磁盤侍匙、網(wǎng)卡)使用情況,分別在自己的 http web 頁面(4194 端口)和 10250 以 promehteus metrics 的形式輸出叮雳。

瀏覽器訪問 http://192.168.16.237:4194/containers/ 可以查看到 cadvisor 的監(jiān)控頁面:

image.png

下面這段直接cp原文想暗,沒看懂也沒有做出來,我直接忽略了
瀏覽器訪問 https://172.27.129.80:10250/metricshttps://172.27.129.80:10250/metrics/cadvisor 分別返回 kublet 和 cadvisor 的 metrics帘不。

image.png

注意:

  • kublet.config.json 設(shè)置 authentication.anonymous.enabled 為 false说莫,不允許匿名證書訪問 10250 的 https 服務(wù);
  • 參考A.瀏覽器訪問kube-apiserver安全端口.md寞焙,創(chuàng)建和導(dǎo)入相關(guān)證書储狭,然后訪問上面的 10250 端口;

獲取 kublet 的配置

從 kube-apiserver 獲取各 node 的配置:

$ source /opt/k8s/bin/environment.sh
$ # 使用部署 kubectl 命令行工具時(shí)創(chuàng)建的捣郊、具有最高權(quán)限的 admin 證書辽狈;
$ curl -sSL --cacert /etc/kubernetes/cert/ca.pem --cert ./admin.pem --key ./admin-key.pem ${KUBE_APISERVER}/api/v1/nodes/kube-node1/proxy/configz | jq \
  '.kubeletconfig|.kind="KubeletConfiguration"|.apiVersion="kubelet.config.k8s.io/v1beta1"'
{
  "syncFrequency": "1m0s",
  "fileCheckFrequency": "20s",
  "httpCheckFrequency": "20s",
  "address": "172.27.129.80",
  "port": 10250,
  "readOnlyPort": 10255,
  "authentication": {
    "x509": {},
    "webhook": {
      "enabled": false,
      "cacheTTL": "2m0s"
    },
    "anonymous": {
      "enabled": true
    }
  },
  "authorization": {
    "mode": "AlwaysAllow",
    "webhook": {
      "cacheAuthorizedTTL": "5m0s",
      "cacheUnauthorizedTTL": "30s"
    }
  },
  "registryPullQPS": 5,
  "registryBurst": 10,
  "eventRecordQPS": 5,
  "eventBurst": 10,
  "enableDebuggingHandlers": true,
  "healthzPort": 10248,
  "healthzBindAddress": "127.0.0.1",
  "oomScoreAdj": -999,
  "clusterDomain": "cluster.local.",
  "clusterDNS": [
    "10.254.0.2"
  ],
  "streamingConnectionIdleTimeout": "4h0m0s",
  "nodeStatusUpdateFrequency": "10s",
  "imageMinimumGCAge": "2m0s",
  "imageGCHighThresholdPercent": 85,
  "imageGCLowThresholdPercent": 80,
  "volumeStatsAggPeriod": "1m0s",
  "cgroupsPerQOS": true,
  "cgroupDriver": "cgroupfs",
  "cpuManagerPolicy": "none",
  "cpuManagerReconcilePeriod": "10s",
  "runtimeRequestTimeout": "2m0s",
  "hairpinMode": "promiscuous-bridge",
  "maxPods": 110,
  "podPidsLimit": -1,
  "resolvConf": "/etc/resolv.conf",
  "cpuCFSQuota": true,
  "maxOpenFiles": 1000000,
  "contentType": "application/vnd.kubernetes.protobuf",
  "kubeAPIQPS": 5,
  "kubeAPIBurst": 10,
  "serializeImagePulls": false,
  "evictionHard": {
    "imagefs.available": "15%",
    "memory.available": "100Mi",
    "nodefs.available": "10%",
    "nodefs.inodesFree": "5%"
  },
  "evictionPressureTransitionPeriod": "5m0s",
  "enableControllerAttachDetach": true,
  "makeIPTablesUtilChains": true,
  "iptablesMasqueradeBit": 14,
  "iptablesDropBit": 15,
  "featureGates": {
    "RotateKubeletClientCertificate": true,
    "RotateKubeletServerCertificate": true
  },
  "failSwapOn": true,
  "containerLogMaxSize": "10Mi",
  "containerLogMaxFiles": 5,
  "enforceNodeAllocatable": [
    "pods"
  ],
  "kind": "KubeletConfiguration",
  "apiVersion": "kubelet.config.k8s.io/v1beta1"
}

15.部署 kube-proxy 組件

kube-proxy 運(yùn)行在所有 worker 節(jié)點(diǎn)上,模她,它監(jiān)聽 apiserver 中 service 和 Endpoint 的變化情況稻艰,創(chuàng)建路由規(guī)則來進(jìn)行服務(wù)負(fù)載均衡。

本文檔講解部署 kube-proxy 的部署侈净,使用 ipvs 模式尊勿。

下載和分發(fā) kube-proxy 二進(jìn)制文件

參考 06-0.部署master節(jié)點(diǎn).md

安裝依賴包

各節(jié)點(diǎn)需要安裝 ipvsadmipset 命令僧凤,加載 ip_vs 內(nèi)核模塊。

參考 07-0.部署worker節(jié)點(diǎn).md

創(chuàng)建 kube-proxy 證書

創(chuàng)建證書簽名請(qǐng)求:

cat > kube-proxy-csr.json <<EOF
{
  "CN": "system:kube-proxy",
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "4Paradigm"
    }
  ]
}
EOF
  • CN:指定該證書的 User 為 system:kube-proxy元扔;
  • 預(yù)定義的 RoleBinding system:node-proxier 將User system:kube-proxy 與 Role system:node-proxier 綁定躯保,該 Role 授予了調(diào)用 kube-apiserver Proxy 相關(guān) API 的權(quán)限;
  • 該證書只會(huì)被 kube-proxy 當(dāng)做 client 證書使用澎语,所以 hosts 字段為空途事;

生成證書和私鑰:

cfssl gencert -ca=/etc/kubernetes/cert/ca.pem \
  -ca-key=/etc/kubernetes/cert/ca-key.pem \
  -config=/etc/kubernetes/cert/ca-config.json \
  -profile=kubernetes  kube-proxy-csr.json | cfssljson -bare kube-proxy

創(chuàng)建和分發(fā) kubeconfig 文件

source /opt/k8s/bin/environment.sh
kubectl config set-cluster kubernetes \
  --certificate-authority=/etc/kubernetes/cert/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=kube-proxy.kubeconfig

kubectl config set-credentials kube-proxy \
  --client-certificate=kube-proxy.pem \
  --client-key=kube-proxy-key.pem \
  --embed-certs=true \
  --kubeconfig=kube-proxy.kubeconfig

kubectl config set-context default \
  --cluster=kubernetes \
  --user=kube-proxy \
  --kubeconfig=kube-proxy.kubeconfig

kubectl config use-context default --kubeconfig=kube-proxy.kubeconfig
  • --embed-certs=true:將 ca.pem 和 admin.pem 證書內(nèi)容嵌入到生成的 kubectl-proxy.kubeconfig 文件中(不加時(shí),寫入的是證書文件路徑)擅羞;

分發(fā) kubeconfig 文件:

source /opt/k8s/bin/environment.sh
for node_name in ${NODE_NAMES[@]}
  do
    echo ">>> ${node_name}"
    scp kube-proxy.kubeconfig k8s@${node_name}:/etc/kubernetes/
  done

創(chuàng)建 kube-proxy 配置文件

從 v1.10 開始尸变,kube-proxy 部分參數(shù)可以配置文件中配置〖跚危可以使用 --write-config-to 選項(xiàng)生成該配置文件召烂,或者參考 kubeproxyconfig 的類型定義源文件 :https://github.com/kubernetes/kubernetes/blob/master/pkg/proxy/apis/kubeproxyconfig/types.go

創(chuàng)建 kube-proxy config 文件模板:

cat >kube-proxy.config.yaml.template <<EOF
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: ##NODE_IP##
clientConnection:
  kubeconfig: /etc/kubernetes/kube-proxy.kubeconfig
clusterCIDR: ${CLUSTER_CIDR}
healthzBindAddress: ##NODE_IP##:10256
hostnameOverride: ##NODE_NAME##
kind: KubeProxyConfiguration
metricsBindAddress: ##NODE_IP##:10249
mode: "ipvs"
EOF
  • bindAddress: 監(jiān)聽地址;
  • clientConnection.kubeconfig: 連接 apiserver 的 kubeconfig 文件娃承;
  • clusterCIDR: kube-proxy 根據(jù) --cluster-cidr 判斷集群內(nèi)部和外部流量奏夫,指定 --cluster-cidr--masquerade-all選項(xiàng)后 kube-proxy 才會(huì)對(duì)訪問 Service IP 的請(qǐng)求做 SNAT;
  • hostnameOverride: 參數(shù)值必須與 kubelet 的值一致历筝,否則 kube-proxy 啟動(dòng)后會(huì)找不到該 Node酗昼,從而不會(huì)創(chuàng)建任何 ipvs 規(guī)則;
  • mode: 使用 ipvs 模式梳猪;

為各節(jié)點(diǎn)創(chuàng)建和分發(fā) kube-proxy 配置文件:

source /opt/k8s/bin/environment.sh
for (( i=0; i < 3; i++ ))
  do 
    echo ">>> ${NODE_NAMES[i]}"
    sed -e "s/##NODE_NAME##/${NODE_NAMES[i]}/" -e "s/##NODE_IP##/${NODE_IPS[i]}/" kube-proxy.config.yaml.template > kube-proxy-${NODE_NAMES[i]}.config.yaml
    scp kube-proxy-${NODE_NAMES[i]}.config.yaml root@${NODE_NAMES[i]}:/etc/kubernetes/kube-proxy.config.yaml
  done

替換后的 kube-proxy.config.yaml 文件:kube-proxy.config.yaml

創(chuàng)建和分發(fā) kube-proxy systemd unit 文件

source /opt/k8s/bin/environment.sh
cat > kube-proxy.service <<EOF
[Unit]
Description=Kubernetes Kube-Proxy Server
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=network.target

[Service]
WorkingDirectory=/var/lib/kube-proxy
ExecStart=/opt/k8s/bin/kube-proxy \\
  --config=/etc/kubernetes/kube-proxy.config.yaml \\
  --alsologtostderr=true \\
  --logtostderr=false \\
  --log-dir=/var/log/kubernetes \\
  --v=2
Restart=on-failure
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

替換后的 unit 文件:kube-proxy.service

分發(fā) kube-proxy systemd unit 文件:

source /opt/k8s/bin/environment.sh
for node_name in ${NODE_NAMES[@]}
  do 
    echo ">>> ${node_name}"
    scp kube-proxy.service root@${node_name}:/etc/systemd/system/
  done

啟動(dòng) kube-proxy 服務(wù)

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "mkdir -p /var/lib/kube-proxy"
    ssh root@${node_ip} "mkdir -p /var/log/kubernetes && chown -R k8s /var/log/kubernetes"
    ssh root@${node_ip} "systemctl daemon-reload && systemctl enable kube-proxy && systemctl restart kube-proxy"
  done
  • 必須先創(chuàng)建工作和日志目錄麻削;

檢查啟動(dòng)結(jié)果

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh k8s@${node_ip} "systemctl status kube-proxy|grep Active"
  done

確保狀態(tài)為 active (running),否則查看日志春弥,確認(rèn)原因:

journalctl -u kube-proxy

查看監(jiān)聽端口和 metrics

[k8s@kube-node1 ~]$ sudo netstat -lnpt|grep kube-prox
tcp        0      0 192.168.16.237:10249    0.0.0.0:*               LISTEN      16847/kube-proxy
tcp        0      0 192.168.16.237:10256    0.0.0.0:*               LISTEN      16847/kube-proxy
  • 10249:http prometheus metrics port;
  • 10256:http healthz port;

查看 ipvs 路由規(guī)則

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh root@${node_ip} "/usr/sbin/ipvsadm -ln"
  done

預(yù)期輸出:

>>> 192.168.16.237
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  10.254.0.1:443 rr persistent 10800
  -> 192.168.16.237:6443          Masq    1      0          0
>>>192.168.16.238
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  10.254.0.1:443 rr persistent 10800
  -> 192.168.16.237:6443          Masq    1      0          0
>>>192.168.16.239
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  10.254.0.1:443 rr persistent 10800
  -> 192.168.16.237:6443          Masq    1      0          0

可見將所有到 kubernetes cluster ip 443 端口的請(qǐng)求都轉(zhuǎn)發(fā)到 kube-apiserver 的 6443 端口碟婆;

16. 驗(yàn)證集群功能

本文檔使用 daemonset 驗(yàn)證 master 和 worker 節(jié)點(diǎn)是否工作正常。

檢查節(jié)點(diǎn)狀態(tài)

$ kubectl get nodes
NAME         STATUS    ROLES     AGE       VERSION
kube-node1   Ready     <none>    3h        v1.10.4
kube-node2   Ready     <none>    3h        v1.10.4
kube-node3   Ready     <none>    3h        v1.10.4

都為 Ready 時(shí)正常惕稻。

創(chuàng)建測(cè)試文件

$ cat > nginx-ds.yml <<EOF
apiVersion: v1
kind: Service
metadata:
  name: nginx-ds
  labels:
    app: nginx-ds
spec:
  type: NodePort
  selector:
    app: nginx-ds
  ports:
  - name: http
    port: 80
    targetPort: 80
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: nginx-ds
  labels:
    addonmanager.kubernetes.io/mode: Reconcile
spec:
  template:
    metadata:
      labels:
        app: nginx-ds
    spec:
      containers:
      - name: my-nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
EOF

執(zhí)行定義文件

$ kubectl create -f nginx-ds.yml
service "nginx-ds" created
daemonset.extensions "nginx-ds" created

檢查各 Node 上的 Pod IP 連通性

$ kubectl get pods  -o wide|grep nginx-ds
nginx-ds-dbn97   1/1       Running   0          2m        172.30.29.2   kube-node2
nginx-ds-rk777   1/1       Running   0          2m        172.30.81.2   kube-node1
nginx-ds-tr9g5   1/1       Running   0          2m        172.30.39.2   kube-node3

可見,nginx-ds 的 Pod IP 分別是 172.30.39.2蝙叛、172.30.81.2俺祠、172.30.29.2,在所有 Node 上分別 ping 這三個(gè) IP借帘,看是否連通:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh ${node_ip} "ping -c 1 172.30.39.2"
    ssh ${node_ip} "ping -c 1 172.30.81.2"
    ssh ${node_ip} "ping -c 1 172.30.29.2"
  done

檢查服務(wù) IP 和端口可達(dá)性

$ kubectl get svc |grep nginx-ds
nginx-ds     NodePort    10.254.254.228   <none>        80:8900/TCP   4m

可見:

  • Service Cluster IP:10.254.254.228
  • 服務(wù)端口:80
  • NodePort 端口:8900

在所有 Node 上 curl Service IP:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh ${node_ip} "curl 10.254.254.228"
  done

預(yù)期輸出 nginx 歡迎頁面內(nèi)容蜘渣。

檢查服務(wù)的 NodePort 可達(dá)性

在所有 Node 上執(zhí)行:

source /opt/k8s/bin/environment.sh
for node_ip in ${NODE_IPS[@]}
  do
    echo ">>> ${node_ip}"
    ssh ${node_ip} "curl ${node_ip}:8900"
  done

預(yù)期輸出 nginx 歡迎頁面內(nèi)容。

17. kubectl 常用命令及排查

查看集群信息
kubectl cluster-info
查看所有命名空間的pods
kubectl   get  pods  --all-namespaces
顯示Pod的更多信息
kubectl    get pods  --all-namespaces   -o wide
查看rc和service列表
kubectl get rc,service
查看所有命名空間的servers
kubectl  get svc --all-namespaces
查看pod日志
kubectl logs -f kubernetes-dashboard-86497fb476-brbz8  -n  kube-system
顯示Node的詳細(xì)信息
kubectl describe nodes <node-name>
顯示Pod的詳細(xì)信息
kubectl describe pods/<pod-name>
顯示由RC管理的Pod的信息
kubectl describe pods <rc-name>
創(chuàng)建服務(wù)
kubectl create  -f   nginx.yaml
刪除服務(wù)
kubectl  delete  -f  nginx.yaml
執(zhí)行容器的命令
執(zhí)行Pod的data命令肺然,默認(rèn)是用Pod中的第一個(gè)容器執(zhí)行
kubectl exec <pod-name> data
指定Pod中某個(gè)容器執(zhí)行data命令
kubectl exec <pod-name> -c <container-name> data
通過bash獲得Pod中某個(gè)容器的TTY蔫缸,相當(dāng)于登錄容器
kubectl exec -it <pod-name> -c <container-name> bash

待更新

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市际起,隨后出現(xiàn)的幾起案子拾碌,更是在濱河造成了極大的恐慌吐葱,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件校翔,死亡現(xiàn)場離奇詭異弟跑,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)防症,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門孟辑,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蔫敲,你說我怎么就攤上這事饲嗽。” “怎么了奈嘿?”我有些...
    開封第一講書人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵貌虾,是天一觀的道長。 經(jīng)常有香客問我指么,道長酝惧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任伯诬,我火速辦了婚禮晚唇,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘盗似。我一直安慰自己哩陕,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開白布赫舒。 她就那樣靜靜地躺著悍及,像睡著了一般。 火紅的嫁衣襯著肌膚如雪接癌。 梳的紋絲不亂的頭發(fā)上心赶,一...
    開封第一講書人閱讀 48,970評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音缺猛,去河邊找鬼缨叫。 笑死,一個(gè)胖子當(dāng)著我的面吹牛荔燎,可吹牛的內(nèi)容都是我干的耻姥。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼有咨,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼琐簇!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起座享,我...
    開封第一講書人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤婉商,失蹤者是張志新(化名)和其女友劉穎似忧,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體据某,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡橡娄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了癣籽。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片挽唉。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖筷狼,靈堂內(nèi)的尸體忽然破棺而出瓶籽,到底是詐尸還是另有隱情,我是刑警寧澤埂材,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布塑顺,位于F島的核電站,受9級(jí)特大地震影響俏险,放射性物質(zhì)發(fā)生泄漏严拒。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一竖独、第九天 我趴在偏房一處隱蔽的房頂上張望裤唠。 院中可真熱鬧,春花似錦莹痢、人聲如沸种蘸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽航瞭。三九已至,卻和暖如春坦辟,著一層夾襖步出監(jiān)牢的瞬間刊侯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來泰國打工锉走, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留滔吠,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓挠日,卻偏偏與公主長得像,于是被迫代替她去往敵國和親翰舌。 傳聞我的和親對(duì)象是個(gè)殘疾皇子嚣潜,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容