Ubuntu18.04 Server部署Flannel網絡的Kubernetes


准備服務器

ESXi6.5安裝Ubuntu18.04 Server, 使用三台主機, 計划使用hostname為 kube01, kube02, kube03, 配置為2核4G/160G, K8s要求U為雙核以上.

因為ESXi6.5存在Ubuntu虛機在Remote SSH時宕機的Bug, 根據 https://kb.vmware.com/s/article/2151480 中的解決方案, 需要SSH登錄ESXi后修改配置, 對應的文件在 /vmfs/volumes/584f7xxx-7xx749b4-3461-x0... / 目錄下, 將虛機關機后, 找到對應的虛機文件目錄, 在下面找到vmx文件, 在最后添加

vmxnet3.rev.30 = FALSE

 

更新服務器

將Ubuntu的apt源設為國內

kube02:~$ more /etc/apt/sources.list
deb https://mirrors.ustc.edu.cn/ubuntu bionic main
deb https://mirrors.ustc.edu.cn/ubuntu bionic-security main
deb https://mirrors.ustc.edu.cn/ubuntu bionic-updates main

sudo apt update
sudo apt upgrade

 

修改主機名

修改cloud.cfg

sudo vi /etc/cloud/cloud.cfg
# 將
preserve_hostname: false
# 修改為
preserve_hostname: true

否則hostnamectl set-hostname在重啟后就被恢復了

修改hostname

sudo hostnamectl set-hostname kube01

 

關閉swap分區

1. 立即關閉swap

sudo swapoff -a 

2. 在fstab中關閉swap

vi /etc/fstab 

用#注釋swap那一行

3. 在systemctl中禁用swap, 這一步如果不操作的話, 重啟后依然會出現swap分區

# 也可能是sdb, sdc, 根據自己機器硬盤定, 看哪個分區是swap), 假定是/dev/sda2
sudo fdisk -lu /dev/sda 
# 根據上一步的結果, 執行下面的命令
sudo systemctl mask dev-sda2.swap

 

安裝並配置 Docker

根據計划安裝的k8s版本, 選擇對應的docker版本, 以下為直接安裝最新版

# 准備軟件
sudo apt install apt-transport-https ca-certificates curl software-properties-common
# 安裝證書, 注意管道后面要用sudo
curl -fsSL http://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
# 添加當前發行版的apt源
lsb_release -cs
sudo add-apt-repository "deb [arch=amd64] http://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
# 安裝Docker
sudo apt install docker-ce
# 檢查版本, 此次安裝版本為 19.03.5
docker version
# 將當前用戶添加到docker group, 之后需要重新登錄使其生效, 用id命令檢查
sudo usermod -aG docker milton
# 配置docker, 添加mirror及其他配置
sudo vi /etc/docker/daemon.json

daemon.json內容如下

{
  "registry-mirrors": ["https://registry.docker-cn.com"],
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {"max-size": "100m"},
  "storage-driver": "overlay2"
}

修改cgroup為systemd

# 重啟 docker服務, 並檢查Cgroup Driver和Registry Mirrors是否正確
sudo systemctl restart docker
docker info

 如果需要安裝指定版本的docker, 需要使用以下命令

# 查看可用版本列表
apt-cache madison docker-ce
# 安裝指定版本
sudo apt install docker-ce=18.06.3~ce~3-0~ubuntu

 

安裝Kubernetes

# 安裝證書, 注意管道后面的sudo
curl -fsSL https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo apt-key add -
# 添加apt源, 沒有bionic的, 用xenial
cd /etc/apt/sources.list.d/
sudo vi kubernetes.list

kubernetes.list文件的內容

deb https://mirrors.aliyun.com/kubernetes/apt/ kubernetes-xenial main

更新並安裝

sudo apt update
sudo apt install kubelet kubeadm kubectl

kubeadm: the command to bootstrap the cluster.
kubelet: the component that runs on all of the machines in your cluster and does things like starting pods and containers.
kubectl: the command line util to talk to your cluster.

同樣, 這里也可以選擇指定的版本, 使用以下命令安裝

apt-cache madison kubelet
sudo apt install kubelet=1.14.10-00 kubeadm=1.14.10-00 kubectl=1.14.10-00

 

拖取無法下載的k8s容器鏡像

查看需要的鏡像列表, 會得到以 k8s.gcr.io/ 開頭的一堆結果

kubeadm config images list

寫一個腳本, 將來源改為 registry.aliyuncs.com/google_containers/ , 拖取完再改回去, 腳本內容如下, 要根據上一步得到的列表修改, 然后執行.

#!/bin/bash
# 下面的鏡像應該去除"k8s.gcr.io/"的前綴,版本換成kubeadm config images list命令獲取到的版本
images=(
    kube-apiserver:v1.17.0
    kube-controller-manager:v1.17.0
    kube-scheduler:v1.17.0
    kube-proxy:v1.17.0
    pause:3.1
    etcd:3.4.3-0
    coredns:1.6.5
)

for imageName in ${images[@]} ; do
    docker pull registry.aliyuncs.com/google_containers/$imageName
    docker tag registry.aliyuncs.com/google_containers/$imageName k8s.gcr.io/$imageName
    docker rmi registry.aliyuncs.com/google_containers/$imageName
done

對於node節點, 因為join后也需要下載並啟動對應的容器, 如果沒有預先下載會發現join后, 在nodes列表里一直會NotReady, 所以也要預先下載, 配置node節點到這步就可以了, 如果是配置master節點, 就再往下走

使用kubeadm init初始化Master主機

上面的准備工作都做好之后, 就可以初始化Master主機了

sudo kubeadm init --apiserver-advertise-address=0.0.0.0 --pod-network-cidr=172.16.0.0/16 --service-cidr=10.1.0.0/16

其中的參數說明

  • --apiserver-advertise-address 用哪個IP(網口)提供api, 可以用當前主機的IP, 或者0.0.0.0不指定
  • --pod-network-cidr Pod層的網絡IP范圍, 需要與后面要配置的kube-flannel.yml里的設置一致
  • --service-cidr Service層的網絡IP范圍, 這個是虛擬IP不會體現在路由表上, 與前面的IP區分開就行

輸出的信息

W1231 08:57:05.495224   11297 version.go:101] could not fetch a Kubernetes version from the internet: unable to get URL "https://dl.k8s.io/release/stable-1.txt": Get https://dl.k8s.io/release/stable-1.txt: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
W1231 08:57:05.495416   11297 version.go:102] falling back to the local client version: v1.17.0
W1231 08:57:05.495703   11297 validation.go:28] Cannot validate kube-proxy config - no validator is available
W1231 08:57:05.495735   11297 validation.go:28] Cannot validate kubelet config - no validator is available
[init] Using Kubernetes version: v1.17.0
[preflight] Running pre-flight checks
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kube01 kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.1.0.1 192.168.11.129]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [kube01 localhost] and IPs [192.168.11.129 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [kube01 localhost] and IPs [192.168.11.129 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
W1231 08:57:14.315543   11297 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[control-plane] Creating static Pod manifest for "kube-scheduler"
W1231 08:57:14.318419   11297 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[apiclient] All control plane components are healthy after 37.004860 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.17" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node kube01 as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node kube01 as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: f3jgn2.5w8152dpifacihnj
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes control-plane has initialized successfully!

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

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

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

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

kubeadm join 192.168.11.129:6443 --token f3jgn2.5w8152dpifacihnj \
    --discovery-token-ca-cert-hash sha256:cc1ae32e0924dffa587b5d94b61005ae892db289f1a59f1ef71b45a7eda65ca3 

根據上面的提示, 創建.kube 目錄, 復制config文件並修改owner屬性. kubeadm join的命令在24小時內有效(包括關機重啟).

檢查

# 查看pods
kubectl get pods -n kube-system
# 輸出
NAME                             READY   STATUS    RESTARTS   AGE
coredns-6955765f44-7dnqv         1/1     Running   0          71m
coredns-6955765f44-pvlcp         1/1     Running   0          71m
etcd-kube01                      1/1     Running   0          71m
kube-apiserver-kube01            1/1     Running   0          71m
kube-controller-manager-kube01   1/1     Running   0          71m
kube-proxy-7c8f5                 1/1     Running   0          71m
kube-scheduler-kube01            1/1     Running   0          71m

.

安裝Flannel

# 下載 kube-flannel.yml 
wget https://github.com/coreos/flannel/raw/master/Documentation/kube-flannel.yml
# 修改其中net-conf.json的Network參數使其與kubeadm init時指定的 --pod-network-cidr一致, 此次使用的是172.16.0.0/16
vi kube-flannel.yml 
# 安裝
kubectl apply -f kube-flannel.yml 
輸出
podsecuritypolicy.policy/psp.flannel.unprivileged created
clusterrole.rbac.authorization.k8s.io/flannel created
clusterrolebinding.rbac.authorization.k8s.io/flannel created
serviceaccount/flannel created
configmap/kube-flannel-cfg created
daemonset.apps/kube-flannel-ds-amd64 created
daemonset.apps/kube-flannel-ds-arm64 created
daemonset.apps/kube-flannel-ds-arm created
daemonset.apps/kube-flannel-ds-ppc64le created
daemonset.apps/kube-flannel-ds-s390x created

而后會在后台進程下載flannel的容器鏡像並啟動, 稍待片刻后, 查看flannel網絡信息

more /run/flannel/subnet.env 
FLANNEL_NETWORK=172.16.0.0/16
FLANNEL_SUBNET=172.16.0.1/24
FLANNEL_MTU=1450
FLANNEL_IPMASQ=true

查看flannel網絡配置

more /etc/cni/net.d/10-flannel.conflist 
{
  "name": "cbr0",
  "cniVersion": "0.3.1",
  "plugins": [
    {
      "type": "flannel",
      "delegate": {
        "hairpinMode": true,
        "isDefaultGateway": true
      }
    },
    {
      "type": "portmap",
      "capabilities": {
        "portMappings": true
      }
    }
  ]
}

再次查看pods, 能看到新增加的flannel

kube-flannel-ds-amd64-kkxlm      1/1     Running   0          3m5s

查看pod日志

kubectl logs coredns-6955765f44-7dnqv -n kube-system
.:53
[INFO] plugin/reload: Running configuration MD5 = 4e235fcc3696966e76816bcd9034ebc7
CoreDNS-1.6.5
linux/amd64, go1.13.4, c2fd1b2

查看nodes, 此時只有master主機

kubectl get nodes
NAME     STATUS   ROLES    AGE   VERSION
kube01   Ready    master   78m   v1.17.0

 

Node主機加入集群

使用前面kubeadm init產生的命令, 需要sudo, 與網上查到的教程不同, 不需要從master主機復制配置文件, 實際測試直接運行下面的命令就加入集群了

sudo kubeadm join 192.168.11.129:6443 --token f3jgn2.5w8152dpifacihnj --discovery-token-ca-cert-hash sha256:cc1ae32e0924dffa587b5d94b61005ae892db289f1a59f1ef71b45a7eda65ca3

輸出

W1231 10:42:36.665020    6229 join.go:346] [preflight] WARNING: JoinControlPane.controlPlane settings will be ignored when control-plane flag is not set.
[preflight] Running pre-flight checks
[preflight] Reading configuration from the cluster...
[preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[kubelet-start] Downloading configuration for the kubelet from the "kubelet-config-1.17" ConfigMap in the kube-system namespace
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Starting the kubelet
[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...

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

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

在master主機上檢查新加入的node主機

kubectl get nodes
# 會看到NotReady
NAME     STATUS     ROLES    AGE    VERSION
kube01   Ready      master   105m   v1.17.0
kube02   NotReady   <none>   10s    v1.17.0

# 過一段時間后就Ready了
NAME     STATUS   ROLES    AGE    VERSION
kube01   Ready    master   107m   v1.17.0
kube02   Ready    <none>   109s   v1.17.0

 

部署測試容器

在master主機上創建一個nginx-deployment.yaml文件, 內容如下

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2 # tells deployment to run 2 pods matching the template
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

如果在國內, 可以將nginx:1.7.9替換為 registry.cn-shanghai.aliyuncs.com/jovi/nginx:alpine 這個鏡像拉取比較快

運行部署命令

kubectl apply -f nginx-deployment.yaml

查看部署, 查看對應的pod, 如果pod一直不ready, 可以用describe看pod的event列表, 現在執行到哪一步. 在有些網絡下pull image會花比較長時間.

$ kubectl describe deployment nginx-deployment

$ kubectl get pods
NAME                               READY   STATUS              RESTARTS   AGE
nginx-deployment-6dd86d77d-qwlmz   0/1     ContainerCreating   0          78s
nginx-deployment-6dd86d77d-xk294   0/1     ContainerCreating   0          78s

$ kubectl describe pod nginx-deployment-6dd86d77d-qwlmz

通過describe查看到pod的IP后, 就可以在master節點通過 curl http://IP 查看到nginx的歡迎頁了.

集群節點間Pods的網絡互通問題

在K8s 1.17下, 默認安裝完, master節點就能ping通node節點上的pod IP, 不存在互通問題.

存在問題的是K8s 1.14. 在百度上查到的方式, 大多數使用了下面的第一種方法, 實際上不是最優方案.

在k8s 1.12之前, 默認是使用以下方式來解決node節點的pod之間的互相訪問, 相應討論 https://github.com/coreos/flannel/issues/699

1. 在node節點上, 修改 /etc/sysctl.conf,  設置 #net.ipv4.ip_forward=1, 並執行 sudo sysctl -p 生效
2. 在node節點上, 執行 sudo iptables --policy FORWARD ACCEPT

這時候從master節點或者其他node節點, 去ping這個node節點上的pod IP就能ping通

在1.13及之后, k8s調整了網絡策略, 因為這樣的方式會帶來安全問題, 相應的討論在 
https://github.com/kubernetes/kubernetes/issues/40182 以及 https://github.com/moby/moby/pull/28257

要解決互通問題, 可以使用針對cni0網口的特定規則, 執行

sudo iptables -A FORWARD -i cni0 -j ACCEPT
sudo iptables -A FORWARD -o cni0 -j ACCEPT

然后這個node節點上的pod IP就能被ping通了. 在1.14下沒有直接設置這個的方法, 可以加到開機啟動執行腳本中去.

節點維護

節點的維護涉及到加入/刪除節點, 停用/啟用節點等

加入新節點

新加入節點: 在node主機上使用 kubeadm join 命令. 對於已經過期的token, 在master主機上通過以下步驟得到hash

# 查看現在可用的token
$ kubeadm token list
TOKEN                     TTL         EXPIRES                USAGES                   DESCRIPTION                                                EXTRA GROUPS
pn2yvw.h2ffrw5goe0y8hoy   3h          2020-01-08T11:41:49Z   authentication,signing   The default bootstrap token generated by 'kubeadm init'.   system:bootstrappers:kubeadm:default-node-token

# 運行以下命令得到sha256 Hash, 取等號后面的部分
$ openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt \
    | openssl rsa -pubin -outform der 2>/dev/null \
    | openssl dgst -sha256 -hex \
(stdin)= 165d0f5e60f569e8fbf558f61b8b3e823023cdba4e3d95aa55cc5b6e7a082841

根據上面得到的結果, 組裝成kubeadm join命令, 兩個值分別來自於上面兩個命令的結果, 在node主機上執行

sudo kubeadm join 192.168.11.129:6443 --token pn2yvw.h2ffrw5goe0y8hoy --discovery-token-ca-cert-hash sha256:165d0f5e60f569e8fbf558f61b8b3e823023cdba4e3d95aa55cc5b6e7a082841

如果沒有可用的token, 或者都已經過期, 則使用以下命令創建

kubeadm token create --print-join-command

停用 / 啟用節點

在master主機上執行命令

# 停用節點, 使其unscheduable
kubectl drain 節點名

# 啟用節點, 使其scheduable
kubectl uncordon 節點名

刪除節點

在master主機上, 先停用節點后, 再使用 kubectl delete node 節點名 刪除節點

 

集群關機重啟

集群關機, 直接在所有節點上執行halt -p是可以的, 如果講究操作順序的話:

  1. 卸載pods,
  2. 在master上drain所有的node, 
  3. 在node上停止kubelet服務, 停止docker服務, 關機
  4. 在master上停止kubelet服務, 停止docker服務, 關機

因為K8s視所有pod都是臨時的, 整個集群應當看做一個和持久數據無關的服務群體, 所以在停機時, 應當將(非系統自帶的)pod全部消除, 在下次啟動集群后, 再由發布腳本重建所有pod.

參考

https://kubernetes.io/docs/setup/production-environment/container-runtimes/
http://pwittrock.github.io/docs/admin/kubeadm/
https://github.com/coreos/flannel
https://www.latelee.org/kubernetes/k8s-deploy-1.17.0-detail.html
https://blog.csdn.net/liukuan73/article/details/83116271

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM