poetry

环境

安装k8s本身并不复杂,网上太多失败的例子主要是因为以下几点:

  1. 不能上外网
  2. 刚开始的系统配置漏了一两步

先给出我当前的配置环境:

CentOS=7.7
Linux=4.4
VmWare=14
Kubernetes=v1.18.0

kubeadm、kubectl、kubelet功能:

  • kubeadm 初始化工具
  • kubectl 命令行管理工具
  • kubelet 和CRI进行交互,创建Pod

两台机器,一台Master,一台Node

机器 IP
k8s-master 192.168.224.129
k8s-node1 192.168.224.130

初步环境准备(如果不说明,Master和Slaver都需要做):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 导入本地windows代理
export ALL_PROXY=socks5://192.168.224.1:10808

# 关闭交换分区
swapoff -a
sed -i 's/.*swap/#&/' /etc/fstab

# 关闭防火墙和Selinux
systemctl stop firewalld
systemctl disable firewalld
setenforce 0
sed -i 's\SELINUX=enforcing\SELINUX=disabled\' /etc/selinux/config

# 配置DNS
echo "192.168.224.129 k8s-master" >> /etc/hosts
echo "192.168.224.130 k8s-node1" >> /etc/hosts

# 设置密钥对【只需要master做】
ssh-keygen -t rsa
ssh-copy-id k8s-node1

更新内核:

1
2
3
4
5
6
rpm -Uvh https://www.elrepo.org/elrepo-release-7.0-3.el7.elrepo.noarch.rpm
yum list available --disablerepo='*' --enablerepo=elrepo-kernel
yum -y --enablerepo=elrepo-kernel install kernel-lt.x86_64
sed -i 's/GRUB_DEFAULT=.*$/GRUB_DEFAULT=0/' /etc/default/grub
grub2-mkconfig -o /boot/grub2/grub.cfg
reboot

进一步环境配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 安装依赖包
yum install -y epel-release
yum install -y chrony conntrack ipvsadm ipset jq iptables curl sysstat libseccomp wget socat git

# 内核优化
cat > kubernetes.conf <<EOF
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1
net.ipv4.tcp_tw_recycle=0
net.ipv4.neigh.default.gc_thresh1=1024
net.ipv4.neigh.default.gc_thresh1=2048
net.ipv4.neigh.default.gc_thresh1=4096
vm.swappiness=0
vm.overcommit_memory=1
vm.panic_on_oom=0
fs.inotify.max_user_instances=8192
fs.inotify.max_user_watches=1048576
fs.file-max=52706963
fs.nr_open=52706963
net.ipv6.conf.all.disable_ipv6=1
EOF
cp kubernetes.conf /etc/sysctl.d/kubernetes.conf
sysctl -p /etc/sysctl.d/kubernetes.conf

# 时区设置
timedatectl set-timezone Asia/Shanghai
systemctl enable chronyd
systemctl start chronyd
timedatectl status

# 关闭无关服务
systemctl stop postfix && systemctl disable postfix

安装

安装并配置Docker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# docker安装配置
yum update -y && yum -y install yum-utils device-mapper-persistent-data lvm2
yum-config-manager --enable docker-ce-nightly
yum-config-manager --enable docker-ce-test
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum -y install docker-ce docker-ce-cli containerd.io
systemctl enable docker && systemctl start docker

cat > /etc/docker/daemon.json <<EOF
{
"exec-opts": ["native.cgroupdriver=systemd"],
"log-driver": "json-file",
"log-opts": {
"max-size": "100m"
},
"storage-driver": "overlay2",
"storage-opts": [
"overlay2.override_kernel_check=true"
]
}
EOF
systemctl daemon-reload && systemctl restart docker

安装kubelet kubeadm kubectl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 配置Google源
cat > /etc/yum.repos.d/kubernetes.repo <<EOF
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
EOF

# 安装kubelet kubeadm kubectl
yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes
systemctl start kubelet && systemctl enable kubelet

一下只需要在Master上部署


初始化Master节点,有两种方法:

1、用配置文件初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 导出默认配置文件
kubeadm config print init-defaults > kubeadm-config.yaml

# 修改默认配置文件
vim kubeadm-config.yaml

localAPIEndpoint:
advertiseAddress: 192.168.224.129
networking:
dnsDomain: cluster.local
podSubnet: 10.244.0.0/16
serviceSubnet: 10.96.0.0/12

# 主要修改advertiseAddress和添加podSubnet,podSubnet需要和以上一致

# 进行初始化
kubeadm init --config=kubeadm-config.yaml --upload-certs | tee kubeadm-init.log

# ps:初始化过程中回去国外源拉取大量镜像,可以使用kubeadm config images pull查看镜像拉取过程

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

# 安装Pod网络插件CNI,不安装网络插件Node就会始终处于NotReady状态
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

将节点加入到K8S

1
2
3
# 这条命令是初始化完成之后自动生成的,只需要复制到Node执行即可
kubeadm join 192.168.224.129:6443 --token u4or3g.hhljh4eybldeh1bv \
--discovery-token-ca-cert-hash sha256:e363af78bb503cbc0c20113f296a7f2d4f5340ae8d7a9e9de2eb0bf5ecda1a45

在Master查看Node状态信息

1
2
3
4
5
6
7
8
9
10
11
[root@k8s-master ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
k8s-master Ready master 59m v1.18.5
k8s-node1 Ready <none> 59m v1.18.5


# 查看详细状态
kubectl get nodes -o wide

# 持续刷新
kubectl get nodes -o wide -w

部署Dashboard

1
2
3
4
5
6
7
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml

# 获取Token
kubectl describe secrets -n kube-system $(kubectl -n kube-system get secret|grep deployment-controller-token-w7zc5 | awk '{print $1}')

# 删除DashBoard
kubectl delete -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml

如果不想安装图形界面,在Windows本机访问Dashboard,稍后会讲解

安装CentOS7的图形界面,是为了再localhost中访问dashboard

1
2
3
4
5
6
7
yum -y groups install "GNOME Desktop" --skip-broken
yum -y install xrdp
yum -y install tigervnc-server.x86_64
systemctl restart xrdp

# Windows下键盘敲Win+R 输入mstcs,输入Master的IP地址,连接,输入账号密码,登录
# 打开Firefox,访问dashboard的地址

开启kube-proxy,访问地址:

http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/#/overview?namespace=default

1
2
[root@k8s-master ~]# kubectl proxy
Starting to serve on 127.0.0.1:8001

DashBorad

Windows本机访问DashBoard:

第一种方式,动态Nodeport补丁

1
2
3
4
5
6
7
8
9
# 先下载dashboard的yaml文件
wget https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml

# 部署
kubectl apply -f recommended.yaml

# 修改端口为Nodeport
kubectl patch svc kubernetes-dashboard -n kubernetes-dashboard \
-p '{"spec":{"type":"NodePort","ports":[{"port":443,"targetPort":8443,"nodePort":30003}]}}'

第二种方式:

修改配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 下载yaml文件
# 修改recommend.yaml配置文件

kind: Service
apiVersion: v1
metadata:
labels:
k8s-app: kubernetes-dashboard
name: kubernetes-dashboard
namespace: kubernetes-dashboard
spec:
type: NodePort
ports:
- port: 443
targetPort: 8443
nodePort: 30003
selector:
k8s-app: kubernetes-dashboard

# 部署
kubectl apply -f recommended.yaml

查看部署情况

1
2
3
4
5
6
7
8
9
[root@k8s-master01 dashborad]# kubectl get svc -n kubernetes-dashboard -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
dashboard-metrics-scraper ClusterIP 10.107.137.212 <none> 8000/TCP 45m k8s-app=dashboard-metrics-scraper
kubernetes-dashboard NodePort 10.111.194.59 <none> 443:30003/TCP 45m k8s-app=kubernetes-dashboard

[root@k8s-master01 dashboard]# kubectl get svc -n kubernetes-dashboard
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
dashboard-metrics-scraper ClusterIP 10.97.67.195 <none> 8000/TCP 72s
kubernetes-dashboard NodePort 10.106.9.117 <none> 443:30003/TCP 73s

这时候在windows(本机)访问虚拟机的ip+port是这样的:

image-20200723111133837

这里被坑了好久,正确的访问应该是:https://ip:port,那个https一定要加,不能用http。

获取K8S的DashBoard Token

1
2
3
4
# 获取token
kubectl describe secrets -n kubernetes-dashboard
# 删除DashBoard
kubectl delete -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml

Windows本机访问Dashboard

输出

Kubernetes初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
[root@k8s-master ~]# cat kubeadm-init.log 
[init] Using Kubernetes version: v1.18.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配置文件位置
[kubelet-start] Starting the kubelet
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key # 生成ca证书
[certs] Generating "apiserver" certificate and key # 生成apiserver证书
[certs] apiserver serving cert is signed for DNS names [k8s-master kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.224.129]
[certs] Generating "apiserver-kubelet-client" certificate and key # 以下都是各类证书,Kubernetes各组件通过HTTPS证书认证进行通信
[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 [k8s-master localhost] and IPs [192.168.224.129 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [k8s-master localhost] and IPs [192.168.224.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"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[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 15.506392 seconds
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config-1.18" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Storing the certificates in Secret "kubeadm-certs" in the "kube-system" Namespace
[upload-certs] Using certificate key:
c00c2202124c09e619c5d7aad8b97d2605266864c2caf9db48f08a864b8167a5
[mark-control-plane] Marking the node k8s-master as control-plane by adding the label "node-role.kubernetes.io/master=''"
[mark-control-plane] Marking the node k8s-master as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: abcdef.0123456789abcdef
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] configured RBAC rules to allow Node Bootstrap tokens to get nodes
[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.224.129:6443 --token abcdef.0123456789abcdef \
--discovery-token-ca-cert-hash sha256:95ff2bd76b5dec945651a4db5412bdfbc5588bf5b8cb1e9df05ddeb648b5ef7a

加入Node节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@k8s-node1 ~]# kubeadm join 192.168.224.129:6443 --token abcdef.0123456789abcdef \
> --discovery-token-ca-cert-hash sha256:95ff2bd76b5dec945651a4db5412bdfbc5588bf5b8cb1e9df05ddeb648b5ef7a
W0714 10:10:57.574520 54894 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.18" 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.

创建密钥

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@k8s-master ~]# kubectl describe secrets -n kube-system $(kubectl -n kube-system get secret|grep deployment-controller-token-w7zc5 | awk '{print $1}')
Name: deployment-controller-token-w7zc5
Namespace: kube-system
Labels: <none>
Annotations: kubernetes.io/service-account.name: deployment-controller
kubernetes.io/service-account.uid: b70c5000-eea5-4df4-9a52-4afa460657aa

Type: kubernetes.io/service-account-token

Data
====
token: eyJhbGciOiJSUzI1NiIsImtpZCI6InlaQkZhTDhsRDN1UFlOTWNPaXlEUTRWUXFWNmJRcHFBWHB6QWt3OWdsME0ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkZXBsb3ltZW50LWNvbnRyb2xsZXItdG9rZW4tdzd6YzUiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVwbG95bWVudC1jb250cm9sbGVyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiYjcwYzUwMDAtZWVhNS00ZGY0LTlhNTItNGFmYTQ2MDY1N2FhIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRlcGxveW1lbnQtY29udHJvbGxlciJ9.lRATZAlb-LJkS77HSTNFMZKTApY4uRS4_RBUqTPP9752hMOSilHbDbLeDTI1p8K2aiqTNMbRdBJBBiOwtR2jtX0IOXhXlFcrEagGEWbRbyaHx1Nw9Sn84xE70BYlWbHG4EHnKD65okiQgXwegGG121nlh-F_qWpl-n01cGXDqLp-IxV5ZMWLvbZ9OCblgNJF7bFLVwJKbALdvDME4hUXNAsnFTytkv14E36LL8ywjWTRFhWeCVQ_ndNKI4OtfTZV3HiSNN4ag4M_6yS_8VspFrqrbqcGkb63kjK8W4oz68yj3ocurPA0Yf_zGODEeUSp7fq751Dct4iWDqHZMw8ARw
ca.crt: 1025 bytes
namespace: 11 bytes

问题

pod删除不了,一直Terminating

1
2
3
4
5
[root@k8s-master01 dashboard]# kubectl get pod -n kubernetes-dashboard 
NAME READY STATUS RESTARTS AGE
dashboard-metrics-scraper-6b4884c9d5-hhdrg 1/1 Terminating 0 59m
kubernetes-dashboard-7b544877d5-gdlvr 1/1 Terminating 0 59m

强制删除

1
kubectl delete pod -n kubernetes-dashboard --all --grace-period=0 --force

如果这样也删不掉,请检查你是否有rs/rc,如果有,应该先删除rs和rc

1
2
kubectl get rs -n kubernetes-dashboard
kubectl get rc -n kubernetes-dashboard