一、实验环境
1、安装说明
selinux iptables off
官方网站:https://kubernetes.io/zh-cn/docs/home
主机名 | IP | 系统版本 | 安装服务 |
---|---|---|---|
master01 | 10.10.10.21 | rhel7.5 | nginx、etcd、api-server、scheduler、controller-manager、kubelet、proxy |
master02 | 10.10.10.22 | rhel7.5 | nginx、etcd、api-server、scheduler、controller-manager、kubelet、proxy |
master03 | 10.10.10.23 | rhel7.5 | nginx、etcd、api-server、scheduler、controller-manager、kubelet、proxy |
node01 | 10.10.10.24 | rhel7.5 | nginx、kubelet、proxy |
node02 | 10.10.10.25 | rhel7.5 | nginx、kubelet、proxy |
master-lb | 10.10.10.30 | VIP |
2、配置hosts、NetworkManager、swap(所有机器)
master-lb为高可用集群vip,不是高可用的话为master01 IP
# cat /etc/hosts
10.10.10.21 master01
10.10.10.22 master02
10.10.10.23 master03
10.10.10.30 master-lb
10.10.10.24 node01
10.10.10.25 node02# swapoff -a
# sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab
# systemctl disable --now NetworkManager
# systemctl start network && systemctl enable network
3、同步时间(所有节点)
# ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# echo "Asia/Shanghai" > /etc/timezone
# ntpdate time2.aliyun.com# crontab -e #加入crontab
*/5 * * * * /usr/sbin/ntpdate time2.aliyun.com
4、配置limit与k8s.conf(所有)
# cat >>/etc/security/limits.conf<<EOF
* soft nofile 655360
* hard nofile 131072
* soft nproc 655350
* hard nproc 655350
* seft memlock unlimited
* hard memlock unlimitedd
EOF# cat > /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF# sysctl --system
5、配置免密登录(master01)
方便登录其他节点进行管理
[root@master01 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:M+0a6K6QIY3RwNW9KguMDqrTcy3F9Z96a2cm4jrUdNc root@master01
The key's randomart image is:
+---[RSA 2048]----+
|o ... . |
| + . . |
|. . . . |
| + .... . . E|
|= o ...S+.. . |
|o+ + .o..+o |
|+.+ oo... .. . |
|o.ooo.. .o. * + |
|o. o.+o o+o=.* |
+----[SHA256]-----+[root@master01 ~]# for i in master01 master02 master03 node01 node02;do ssh-copy-id -i .ssh/id_rsa.pub $i;done
6、安装常用工具(所有)
# yum -y install wget jq psmisc vim net-tools telnet yum-utils device-mapper-persistent-data lvm2 git network-scripts tar curl ipvsadm ipset sysstat conntrack libseccomp
7、内核升级(所有)
下载地址:https://elrepo.org/linux/kernel/el7/x86_64/RPMS/
# yum install -y kernel-ml-6.3.2-1.el7.elrepo.x86_64.rpm
# yum install -y kernel-ml-devel-6.3.2-1.el7.elrepo.x86_64.rpm
# grub2-set-default 0 && grub2-mkconfig -o /etc/grub2.cfg
# grubby --args="user_namespace.enable=1" --update-kernel="$(grubby --default-kernel)"
# grubby --default-kernel #查看默认内核
9、安装ipvsadm(所有)
# cat > /etc/modules-load.d/ipvs.conf << EOF
ip_vs
ip_vs_rr
ip_vs_wrr
ip_vs_sh
nf_conntrack
ip_tables
ip_set
xt_set
ipt_set
ipt_rpfilter
ipt_REJECT
ipip
EOF# systemctl enable --now systemd-modules-load.service
# lsmod | grep -e ip_vs -e nf_conntrack
nf_conntrack_netlink 57344 0
nfnetlink 24576 4 nf_conntrack_netlink,nf_tables,ip_set
ip_vs_sh 16384 0
ip_vs_wrr 16384 0
ip_vs_rr 16384 6
ip_vs 200704 12 ip_vs_rr,ip_vs_sh,ip_vs_wrr
nf_conntrack 180224 7 xt_conntrack,nf_nat,xt_nat,nf_conntrack_netlink,xt_CT,xt_MASQUERADE,ip_vs
nf_defrag_ipv6 24576 4 nf_conntrack,xt_socket,xt_TPROXY,ip_vs
nf_defrag_ipv4 16384 3 nf_conntrack,xt_socket,xt_TPROXY
libcrc32c 16384 5 nf_conntrack,nf_nat,nf_tables,xfs,ip_vs
10、开启内核参数(所有)
注意:如果内核版本小于4.19,那么配置中的nf_conntrack应该为nf_conntrack_ipv4
# cat >> /etc/sysctl.d/k8s.conf <<EOF
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-iptables = 1
fs.may_detach_mounts = 1
vm.overcommit_memory=1
vm.panic_on_oom=0
fs.inotify.max_user_watches=89100
fs.file-max=52706963
fs.nr_open=52706963
net.netfilter.nf_conntrack_max=2310720net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl =15
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_orphans = 327680
net.ipv4.tcp_orphan_retries = 3
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.ip_conntrack_max = 65536
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_timestamps = 0
net.core.somaxconn = 16384net.ipv6.conf.all.disable_ipv6 = 0
net.ipv6.conf.default.disable_ipv6 = 0
net.ipv6.conf.lo.disable_ipv6 = 0
net.ipv6.conf.all.forwarding = 1
EOF# sysctl --system
11、安装Containerd作为Runtime(所有节点)
(1)安装Containerd
https://github.com/containernetworking/plugins/releases
https://github.com/containerd/containerd/releases
https://github.com/kubernetes-sigs/cri-tools/releases
# ls cri-containerd-cni-1.6.20-linux-amd64.tar.gz crictl-v1.27.0-linux-amd64.tar.gz cni-plugins-linux-amd64-v1.3.0.tgz#创建cni插件所需目录
# mkdir -p /etc/cni/net.d /opt/cni/bin
#解压cni二进制包
# tar xf cni-plugins-linux-amd64-v*.tgz -C /opt/cni/bin/#解压
# tar -xzf cri-containerd-cni-*-linux-amd64.tar.gz -C /#创建服务启动文件
# cat > /etc/systemd/system/containerd.service <<EOF
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target local-fs.target[Service]
ExecStartPre=-/sbin/modprobe overlay
ExecStart=/usr/local/bin/containerd
Type=notify
Delegate=yes
KillMode=process
Restart=always
RestartSec=5
LimitNPROC=infinity
LimitCORE=infinity
LimitNOFILE=infinity
TasksMax=infinity
OOMScoreAdjust=-999[Install]
WantedBy=multi-user.target
EOF
(2)配置Containerd所需的模块
# cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF# systemctl restart systemd-modules-load.service
(3)配置Containerd所需的内核
# cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF# 加载内核
# sysctl --system
(4)创建Containerd的配置文件
# 创建默认配置文件
# mkdir -p /etc/containerd
# containerd config default | tee /etc/containerd/config.toml# 修改Containerd的配置文件
# sed -i "s#SystemdCgroup\ \=\ false#SystemdCgroup\ \=\ true#g" /etc/containerd/config.toml
# cat /etc/containerd/config.toml | grep SystemdCgroup# sed -i "s#registry.k8s.io#registry.cn-hangzhou.aliyuncs.com/chenby#g" /etc/containerd/config.toml
# cat /etc/containerd/config.toml | grep sandbox_image# sed -i "s#config_path\ \=\ \"\"#config_path\ \=\ \"/etc/containerd/certs.d\"#g" /etc/containerd/config.toml
# cat /etc/containerd/config.toml | grep certs.d# mkdir /etc/containerd/certs.d/docker.io -pv# cat > /etc/containerd/certs.d/docker.io/hosts.toml << EOF
server = "https://docker.io"
[host."https://hub-mirror.c.163.com"]capabilities = ["pull", "resolve"]
EOF
(5)启动并设置为开机启动
# systemctl daemon-reload
# systemctl enable --now containerd
# systemctl restart containerd
(6)配置crictl客户端连接的运行时位置
#解压
# tar xf crictl-v*-linux-amd64.tar.gz -C /usr/bin/
#生成配置文件
# cat > /etc/crictl.yaml <<EOF
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
EOF# 测试
# systemctl restart containerd
# crictl info
12、k8s与etcd下载及安装(master01)
https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.26.md#server-binaries
下载etcd地址:https://github.com/etcd-io/etcd/releases/tag/v3.5.9
[root@master01 ~]# ls etcd-v3.5.9-linux-amd64.tar.gz kubernetes-server-linux-amd64.tar.gz
etcd-v3.5.9-linux-amd64.tar.gz kubernetes-server-linux-amd64.tar.gz
[root@master01 ~]# tar -xf kubernetes-server-linux-amd64.tar.gz --strip-components=3 -C /usr/local/bin kubernetes/server/bin/kube{let,ctl,-apiserver,-controller-manager,-scheduler,-proxy}# 解压etcd安装文件
[root@master01 ~]# tar -xf etcd*.tar.gz && mv etcd-*/etcd /usr/local/bin/ && mv etcd-*/etcdctl /usr/local/bin/
13、将组件发送至其他k8s节点(master01)
[root@master01 ~]# Master='master02 master03'
[root@master01 ~]# Work='node01 node02'[root@master01 ~]# for NODE in $Master; do echo $NODE; scp /usr/local/bin/kube{let,ctl,-apiserver,-controller-manager,-scheduler,-proxy} $NODE:/usr/local/bin/; scp /usr/local/bin/etcd* $NODE:/usr/local/bin/; done
[root@master01 ~]# for NODE in $Work; do scp /usr/local/bin/kube{let,-proxy} $NODE:/usr/local/bin/ ; done[root@master01 ~]# mkdir -p /opt/cni/bin
二、证书创建(master01)
1、安装cfssl证书工具
https://imroc.cc/kubernetes/trick/certs/sign-certs-with-cfssl.html
安装包下载地址:https://github.com/cloudflare/cfssl/releases
[root@master01 ~]# ls cfssl*
cfssl_1.6.2_linux_amd64 cfssl-certinfo_1.6.2_linux_amd64 cfssljson_1.6.2_linux_amd64
[root@master01 ~]# mv cfssl_1.6.2_linux_amd64 /usr/bin/cfssl
[root@master01 ~]# mv cfssl-certinfo_1.6.2_linux_amd64 /usr/bin/cfssl-certinfo
[root@master01 ~]# mv cfssljson_1.6.2_linux_amd64 /usr/bin/cfssljson
[root@master01 ~]# chmod +x /usr/bin/cfssl*
2、创建证书相关文件
mkdir pki
cd pki
cat > admin-csr.json << EOF
{"CN": "admin","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "system:masters","OU": "Kubernetes-manual"}]
}
EOFcat > ca-config.json << EOF
{"signing": {"default": {"expiry": "876000h"},"profiles": {"kubernetes": {"usages": ["signing","key encipherment","server auth","client auth"],"expiry": "876000h"}}}
}
EOFcat > etcd-ca-csr.json << EOF
{"CN": "etcd","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "etcd","OU": "Etcd Security"}],"ca": {"expiry": "876000h"}
}
EOFcat > front-proxy-ca-csr.json << EOF
{"CN": "kubernetes","key": {"algo": "rsa","size": 2048},"ca": {"expiry": "876000h"}
}
EOFcat > kubelet-csr.json << EOF
{"CN": "system:node:\$NODE","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","L": "Beijing","ST": "Beijing","O": "system:nodes","OU": "Kubernetes-manual"}]
}
EOFcat > manager-csr.json << EOF
{"CN": "system:kube-controller-manager","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "system:kube-controller-manager","OU": "Kubernetes-manual"}]
}
EOFcat > apiserver-csr.json << EOF
{"CN": "kube-apiserver","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "Kubernetes","OU": "Kubernetes-manual"}]
}
EOFcat > ca-csr.json << EOF
{"CN": "kubernetes","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "Kubernetes","OU": "Kubernetes-manual"}],"ca": {"expiry": "876000h"}
}
EOFcat > etcd-csr.json << EOF
{"CN": "etcd","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "etcd","OU": "Etcd Security"}]
}
EOFcat > front-proxy-client-csr.json << EOF
{"CN": "front-proxy-client","key": {"algo": "rsa","size": 2048}
}
EOFcat > kube-proxy-csr.json << EOF
{"CN": "system:kube-proxy","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "system:kube-proxy","OU": "Kubernetes-manual"}]
}
EOFcat > scheduler-csr.json << EOF
{"CN": "system:kube-scheduler","key": {"algo": "rsa","size": 2048},"names": [{"C": "CN","ST": "Beijing","L": "Beijing","O": "system:kube-scheduler","OU": "Kubernetes-manual"}]
}
EOFcd ..
mkdir bootstrap
cd bootstrap
cat > bootstrap.secret.yaml << EOF
apiVersion: v1
kind: Secret
metadata:name: bootstrap-token-c8ad9cnamespace: kube-system
type: bootstrap.kubernetes.io/token
stringData:description: "The default bootstrap token generated by 'kubelet '."token-id: c8ad9ctoken-secret: 2e4d610cf3e7426eusage-bootstrap-authentication: "true"usage-bootstrap-signing: "true"auth-extra-groups: system:bootstrappers:default-node-token,system:bootstrappers:worker,system:bootstrappers:ingress---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:name: kubelet-bootstrap
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:node-bootstrapper
subjects:
- apiGroup: rbac.authorization.k8s.iokind: Groupname: system:bootstrappers:default-node-token
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:name: node-autoapprove-bootstrap
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:certificates.k8s.io:certificatesigningrequests:nodeclient
subjects:
- apiGroup: rbac.authorization.k8s.iokind: Groupname: system:bootstrappers:default-node-token
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:name: node-autoapprove-certificate-rotation
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:certificates.k8s.io:certificatesigningrequests:selfnodeclient
subjects:
- apiGroup: rbac.authorization.k8s.iokind: Groupname: system:nodes
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:annotations:rbac.authorization.kubernetes.io/autoupdate: "true"labels:kubernetes.io/bootstrapping: rbac-defaultsname: system:kube-apiserver-to-kubelet
rules:- apiGroups:- ""resources:- nodes/proxy- nodes/stats- nodes/log- nodes/spec- nodes/metricsverbs:- "*"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:name: system:kube-apiservernamespace: ""
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:kube-apiserver-to-kubelet
subjects:- apiGroup: rbac.authorization.k8s.iokind: Username: kube-apiserver
EOFcd ..
mkdir coredns
cd coredns
cat > coredns.yaml << EOF
apiVersion: v1
kind: ServiceAccount
metadata:name: corednsnamespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:labels:kubernetes.io/bootstrapping: rbac-defaultsname: system:coredns
rules:- apiGroups:- ""resources:- endpoints- services- pods- namespacesverbs:- list- watch- apiGroups:- discovery.k8s.ioresources:- endpointslicesverbs:- list- watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:annotations:rbac.authorization.kubernetes.io/autoupdate: "true"labels:kubernetes.io/bootstrapping: rbac-defaultsname: system:coredns
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:coredns
subjects:
- kind: ServiceAccountname: corednsnamespace: kube-system
---
apiVersion: v1
kind: ConfigMap
metadata:name: corednsnamespace: kube-system
data:Corefile: |.:53 {errorshealth {lameduck 5s}readykubernetes cluster.local in-addr.arpa ip6.arpa {fallthrough in-addr.arpa ip6.arpa}prometheus :9153forward . /etc/resolv.conf {max_concurrent 1000}cache 30loopreloadloadbalance}
---
apiVersion: apps/v1
kind: Deployment
metadata:name: corednsnamespace: kube-systemlabels:k8s-app: kube-dnskubernetes.io/name: "CoreDNS"
spec:# replicas: not specified here:# 1. Default is 1.# 2. Will be tuned in real time if DNS horizontal auto-scaling is turned on.strategy:type: RollingUpdaterollingUpdate:maxUnavailable: 1selector:matchLabels:k8s-app: kube-dnstemplate:metadata:labels:k8s-app: kube-dnsspec:priorityClassName: system-cluster-criticalserviceAccountName: corednstolerations:- key: "CriticalAddonsOnly"operator: "Exists"nodeSelector:kubernetes.io/os: linuxaffinity:podAntiAffinity:preferredDuringSchedulingIgnoredDuringExecution:- weight: 100podAffinityTerm:labelSelector:matchExpressions:- key: k8s-appoperator: Invalues: ["kube-dns"]topologyKey: kubernetes.io/hostnamecontainers:- name: corednsimage: registry.cn-hangzhou.aliyuncs.com/chenby/coredns:v1.10.0imagePullPolicy: IfNotPresentresources:limits:memory: 170Mirequests:cpu: 100mmemory: 70Miargs: [ "-conf", "/etc/coredns/Corefile" ]volumeMounts:- name: config-volumemountPath: /etc/corednsreadOnly: trueports:- containerPort: 53name: dnsprotocol: UDP- containerPort: 53name: dns-tcpprotocol: TCP- containerPort: 9153name: metricsprotocol: TCPsecurityContext:allowPrivilegeEscalation: falsecapabilities:add:- NET_BIND_SERVICEdrop:- allreadOnlyRootFilesystem: truelivenessProbe:httpGet:path: /healthport: 8080scheme: HTTPinitialDelaySeconds: 60timeoutSeconds: 5successThreshold: 1failureThreshold: 5readinessProbe:httpGet:path: /readyport: 8181scheme: HTTPdnsPolicy: Defaultvolumes:- name: config-volumeconfigMap:name: corednsitems:- key: Corefilepath: Corefile
---
apiVersion: v1
kind: Service
metadata:name: kube-dnsnamespace: kube-systemannotations:prometheus.io/port: "9153"prometheus.io/scrape: "true"labels:k8s-app: kube-dnskubernetes.io/cluster-service: "true"kubernetes.io/name: "CoreDNS"
spec:selector:k8s-app: kube-dnsclusterIP: 10.96.0.10 ports:- name: dnsport: 53protocol: UDP- name: dns-tcpport: 53protocol: TCP- name: metricsport: 9153protocol: TCP
EOFcd ..
mkdir metrics-server
cd metrics-server
cat > metrics-server.yaml << EOF
apiVersion: v1
kind: ServiceAccount
metadata:labels:k8s-app: metrics-servername: metrics-servernamespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:labels:k8s-app: metrics-serverrbac.authorization.k8s.io/aggregate-to-admin: "true"rbac.authorization.k8s.io/aggregate-to-edit: "true"rbac.authorization.k8s.io/aggregate-to-view: "true"name: system:aggregated-metrics-reader
rules:
- apiGroups:- metrics.k8s.ioresources:- pods- nodesverbs:- get- list- watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:labels:k8s-app: metrics-servername: system:metrics-server
rules:
- apiGroups:- ""resources:- pods- nodes- nodes/stats- namespaces- configmapsverbs:- get- list- watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:labels:k8s-app: metrics-servername: metrics-server-auth-readernamespace: kube-system
roleRef:apiGroup: rbac.authorization.k8s.iokind: Rolename: extension-apiserver-authentication-reader
subjects:
- kind: ServiceAccountname: metrics-servernamespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:labels:k8s-app: metrics-servername: metrics-server:system:auth-delegator
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:auth-delegator
subjects:
- kind: ServiceAccountname: metrics-servernamespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:labels:k8s-app: metrics-servername: system:metrics-server
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:metrics-server
subjects:
- kind: ServiceAccountname: metrics-servernamespace: kube-system
---
apiVersion: v1
kind: Service
metadata:labels:k8s-app: metrics-servername: metrics-servernamespace: kube-system
spec:ports:- name: httpsport: 443protocol: TCPtargetPort: httpsselector:k8s-app: metrics-server
---
apiVersion: apps/v1
kind: Deployment
metadata:labels:k8s-app: metrics-servername: metrics-servernamespace: kube-system
spec:selector:matchLabels:k8s-app: metrics-serverstrategy:rollingUpdate:maxUnavailable: 0template:metadata:labels:k8s-app: metrics-serverspec:containers:- args:- --cert-dir=/tmp- --secure-port=4443- --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname- --kubelet-use-node-status-port- --metric-resolution=15s- --kubelet-insecure-tls- --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem # change to front-proxy-ca.crt for kubeadm- --requestheader-username-headers=X-Remote-User- --requestheader-group-headers=X-Remote-Group- --requestheader-extra-headers-prefix=X-Remote-Extra-image: registry.cn-hangzhou.aliyuncs.com/chenby/metrics-server:v0.5.2imagePullPolicy: IfNotPresentlivenessProbe:failureThreshold: 3httpGet:path: /livezport: httpsscheme: HTTPSperiodSeconds: 10name: metrics-serverports:- containerPort: 4443name: httpsprotocol: TCPreadinessProbe:failureThreshold: 3httpGet:path: /readyzport: httpsscheme: HTTPSinitialDelaySeconds: 20periodSeconds: 10resources:requests:cpu: 100mmemory: 200MisecurityContext:readOnlyRootFilesystem: truerunAsNonRoot: truerunAsUser: 1000volumeMounts:- mountPath: /tmpname: tmp-dir- name: ca-sslmountPath: /etc/kubernetes/pkinodeSelector:kubernetes.io/os: linuxpriorityClassName: system-cluster-criticalserviceAccountName: metrics-servervolumes:- emptyDir: {}name: tmp-dir- name: ca-sslhostPath:path: /etc/kubernetes/pki---
apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:labels:k8s-app: metrics-servername: v1beta1.metrics.k8s.io
spec:group: metrics.k8s.iogroupPriorityMinimum: 100insecureSkipTLSVerify: trueservice:name: metrics-servernamespace: kube-systemversion: v1beta1versionPriority: 100
EOF
3、生成etcd证书
[root@master01 ~]# mkdir -p /etc/etcd/ssl
[root@master01 ~]# cd pki/
[root@master01 pki]# cfssl gencert -initca etcd-ca-csr.json | cfssljson -bare /etc/etcd/ssl/etcd-ca
[root@master01 pki]# cfssl gencert \-ca=/etc/etcd/ssl/etcd-ca.pem \-ca-key=/etc/etcd/ssl/etcd-ca-key.pem \-config=ca-config.json \-hostname=127.0.0.1,master01,master02,master03,10.10.10.21,10.10.10.22,10.10.10.23,fc00:43f4:1eea:1::10,fc00:43f4:1eea:1::20,fc00:43f4:1eea:1::30 \-profile=kubernetes \etcd-csr.json | cfssljson -bare /etc/etcd/ssl/etcd
4、将etcd证书复制到其他节点
[root@master01 pki]# Master='master02 master03'
[root@master01 pki]# for NODE in $Master; do ssh $NODE "mkdir -p /etc/etcd/ssl"; for FILE in etcd-ca-key.pem etcd-ca.pem etcd-key.pem etcd.pem; do scp /etc/etcd/ssl/${FILE} $NODE:/etc/etcd/ssl/${FILE}; done; done
5、生成k8s相关证书
[root@master01 pki]# mkdir -p /etc/kubernetes/pki
[root@master01 pki]# cfssl gencert -initca ca-csr.json | cfssljson -bare /etc/kubernetes/pki/ca
[root@master01 pki]# cfssl gencert \-ca=/etc/kubernetes/pki/ca.pem \-ca-key=/etc/kubernetes/pki/ca-key.pem \-config=ca-config.json \-hostname=10.96.0.1,10.10.10.30,127.0.0.1,kubernetes,kubernetes.default,kubernetes.default.svc,kubernetes.default.svc.cluster,kubernetes.default.svc.cluster.local,x.oiox.cn,k.oiox.cn,l.oiox.cn,o.oiox.cn,10.10.10.21,10.10.10.22,10.10.10.23,10.10.10.24,10.10.10.25,10.10.10.26,10.10.10.27,10.10.10.28,3.10.10.10.29,fc00:43f4:1eea:1::10,fc00:43f4:1eea:1::20,fc00:43f4:1eea:1::30,fc00:43f4:1eea:1::40,fc00:43f4:1eea:1::50,fc00:43f4:1eea:1::60,fc00:43f4:1eea:1::70,fc00:43f4:1eea:1::80 \-profile=kubernetes apiserver-csr.json | cfssljson -bare /etc/kubernetes/pki/apiserver
6、生成apiserver聚合证书
[root@master01 pki]# cfssl gencert -initca front-proxy-ca-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-ca # 有一个警告,可以忽略
[root@master01 pki]# cfssl gencert \
-ca=/etc/kubernetes/pki/front-proxy-ca.pem \
-ca-key=/etc/kubernetes/pki/front-proxy-ca-key.pem \
-config=ca-config.json \
-profile=kubernetes front-proxy-client-csr.json | cfssljson -bare /etc/kubernetes/pki/front-proxy-client
7、生成controller-manage的证书
在选择使用那种高可用方案 若使用 haproxy、keepalived 那么为 --server=https://10.10.10.30:8443 若使用 nginx方案,那么为 --server=https://127.0.0.1:8443
[root@master01 pki]# cfssl gencert \-ca=/etc/kubernetes/pki/ca.pem \-ca-key=/etc/kubernetes/pki/ca-key.pem \-config=ca-config.json \-profile=kubernetes \manager-csr.json | cfssljson -bare /etc/kubernetes/pki/controller-manager[root@master01 pki]# kubectl config set-cluster kubernetes \--certificate-authority=/etc/kubernetes/pki/ca.pem \--embed-certs=true \--server=https://127.0.0.1:8443 \--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig# 设置一个环境项,一个上下文
[root@master01 pki]# kubectl config set-context system:kube-controller-manager@kubernetes \--cluster=kubernetes \--user=system:kube-controller-manager \--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig# 设置一个用户项
[root@master01 pki]# kubectl config set-credentials system:kube-controller-manager \--client-certificate=/etc/kubernetes/pki/controller-manager.pem \--client-key=/etc/kubernetes/pki/controller-manager-key.pem \--embed-certs=true \--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig# 设置默认环境
[root@master01 pki]# kubectl config use-context system:kube-controller-manager@kubernetes \--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig[root@master01 pki]# cfssl gencert \-ca=/etc/kubernetes/pki/ca.pem \-ca-key=/etc/kubernetes/pki/ca-key.pem \-config=ca-config.json \-profile=kubernetes \scheduler-csr.json | cfssljson -bare /etc/kubernetes/pki/scheduler# 若使用 haproxy、keepalived 那么为 `--server=https://10.10.10.30:8443`
# 若使用 nginx方案,那么为 `--server=https://127.0.0.1:8443`[root@master01 pki]# kubectl config set-cluster kubernetes \--certificate-authority=/etc/kubernetes/pki/ca.pem \--embed-certs=true \--server=https://127.0.0.1:8443 \--kubeconfig=/etc/kubernetes/scheduler.kubeconfig[root@master01 pki]# kubectl config set-credentials system:kube-scheduler \--client-certificate=/etc/kubernetes/pki/scheduler.pem \--client-key=/etc/kubernetes/pki/scheduler-key.pem \--embed-certs=true \--kubeconfig=/etc/kubernetes/scheduler.kubeconfig[root@master01 pki]# kubectl config set-context system:kube-scheduler@kubernetes \--cluster=kubernetes \--user=system:kube-scheduler \--kubeconfig=/etc/kubernetes/scheduler.kubeconfig[root@master01 pki]# kubectl config use-context system:kube-scheduler@kubernetes \--kubeconfig=/etc/kubernetes/scheduler.kubeconfig[root@master01 pki]# cfssl gencert \-ca=/etc/kubernetes/pki/ca.pem \-ca-key=/etc/kubernetes/pki/ca-key.pem \-config=ca-config.json \-profile=kubernetes \admin-csr.json | cfssljson -bare /etc/kubernetes/pki/admin# 若使用 haproxy、keepalived 那么为 `--server=https://10.10.10.30:8443`
# 若使用 nginx方案,那么为 `--server=https://127.0.0.1:8443`[root@master01 pki]# kubectl config set-cluster kubernetes \--certificate-authority=/etc/kubernetes/pki/ca.pem \--embed-certs=true \--server=https://127.0.0.1:8443 \--kubeconfig=/etc/kubernetes/admin.kubeconfig[root@master01 pki]# kubectl config set-credentials kubernetes-admin \--client-certificate=/etc/kubernetes/pki/admin.pem \--client-key=/etc/kubernetes/pki/admin-key.pem \--embed-certs=true \--kubeconfig=/etc/kubernetes/admin.kubeconfig[root@master01 pki]# kubectl config set-context kubernetes-admin@kubernetes \--cluster=kubernetes \--user=kubernetes-admin \--kubeconfig=/etc/kubernetes/admin.kubeconfig[root@master01 pki]# kubectl config use-context kubernetes-admin@kubernetes --kubeconfig=/etc/kubernetes/admin.kubeconfig
8、创建kube-proxy证书
[root@master01 pki]# cfssl gencert \-ca=/etc/kubernetes/pki/ca.pem \-ca-key=/etc/kubernetes/pki/ca-key.pem \-config=ca-config.json \-profile=kubernetes \kube-proxy-csr.json | cfssljson -bare /etc/kubernetes/pki/kube-proxy# 若使用 haproxy、keepalived 那么为 `--server=https://10.10.10.30:8443`
# 若使用 nginx方案,那么为 `--server=https://127.0.0.1:8443`[root@master01 pki]# kubectl config set-cluster kubernetes \--certificate-authority=/etc/kubernetes/pki/ca.pem \--embed-certs=true \--server=https://127.0.0.1:8443 \--kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig[root@master01 pki]# kubectl config set-credentials kube-proxy \--client-certificate=/etc/kubernetes/pki/kube-proxy.pem \--client-key=/etc/kubernetes/pki/kube-proxy-key.pem \--embed-certs=true \--kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig[root@master01 pki]# kubectl config set-context kube-proxy@kubernetes \--cluster=kubernetes \--user=kube-proxy \--kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig[root@master01 pki]# kubectl config use-context kube-proxy@kubernetes --kubeconfig=/etc/kubernetes/kube-proxy.kubeconfig
9、创建ServiceAccount Key-secret
[root@master01 pki]# openssl genrsa -out /etc/kubernetes/pki/sa.key 2048
[root@master01 pki]# openssl rsa -in /etc/kubernetes/pki/sa.key -pubout -out /etc/kubernetes/pki/sa.pub
10、将证书发送到其他master节点
#其他节点创建目录
# mkdir /etc/kubernetes/pki/ -p
[root@master01 pki]# for NODE in master02 master03; do for FILE in $(ls /etc/kubernetes/pki | grep -v etcd); do scp /etc/kubernetes/pki/${FILE} $NODE:/etc/kubernetes/pki/${FILE}; done; for FILE in admin.kubeconfig controller-manager.kubeconfig scheduler.kubeconfig; do scp /etc/kubernetes/${FILE} $NODE:/etc/kubernetes/${FILE}; done; done[root@master01 pki]# ls /etc/kubernetes/pki/ |wc -l
26
三、安装etcd
1、配置etcd.config.yml
(1)master01
[root@master01 ~]# cat > /etc/etcd/etcd.config.yml << EOF
name: 'master01'
data-dir: /var/lib/etcd
wal-dir: /var/lib/etcd/wal
snapshot-count: 5000
heartbeat-interval: 100
election-timeout: 1000
quota-backend-bytes: 0
listen-peer-urls: 'https://10.10.10.21:2380'
listen-client-urls: 'https://10.10.10.21:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://10.10.10.21:2380'
advertise-client-urls: 'https://10.10.10.21:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'master01=https://10.10.10.21:2380,master02=https://10.10.10.22:2380,master03=https://10.10.10.23:2380'
initial-cluster-token: 'etcd-k8s-cluster'
initial-cluster-state: 'new'
strict-reconfig-check: false
enable-v2: true
enable-pprof: true
proxy: 'off'
proxy-failure-wait: 5000
proxy-refresh-interval: 30000
proxy-dial-timeout: 1000
proxy-write-timeout: 5000
proxy-read-timeout: 0
client-transport-security:cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'client-cert-auth: truetrusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'auto-tls: true
peer-transport-security:cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'peer-client-cert-auth: truetrusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'auto-tls: true
debug: false
log-package-levels:
log-outputs: [default]
force-new-cluster: false
EOF
(2)master02
[root@master02 ~]# cat > /etc/etcd/etcd.config.yml << EOF
name: 'master02'
data-dir: /var/lib/etcd
wal-dir: /var/lib/etcd/wal
snapshot-count: 5000
heartbeat-interval: 100
election-timeout: 1000
quota-backend-bytes: 0
listen-peer-urls: 'https://10.10.10.22:2380'
listen-client-urls: 'https://10.10.10.22:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://10.10.10.22:2380'
advertise-client-urls: 'https://10.10.10.22:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'master01=https://10.10.10.21:2380,master02=https://10.10.10.22:2380,master03=https://10.10.10.23:2380'
initial-cluster-token: 'etcd-k8s-cluster'
initial-cluster-state: 'new'
strict-reconfig-check: false
enable-v2: true
enable-pprof: true
proxy: 'off'
proxy-failure-wait: 5000
proxy-refresh-interval: 30000
proxy-dial-timeout: 1000
proxy-write-timeout: 5000
proxy-read-timeout: 0
client-transport-security:cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'client-cert-auth: truetrusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'auto-tls: true
peer-transport-security:cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'peer-client-cert-auth: truetrusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'auto-tls: true
debug: false
log-package-levels:
log-outputs: [default]
force-new-cluster: false
EOF
(3)master03
[root@master03 ~]# cat > /etc/etcd/etcd.config.yml << EOF
name: 'master03'
data-dir: /var/lib/etcd
wal-dir: /var/lib/etcd/wal
snapshot-count: 5000
heartbeat-interval: 100
election-timeout: 1000
quota-backend-bytes: 0
listen-peer-urls: 'https://10.10.10.23:2380'
listen-client-urls: 'https://10.10.10.23:2379,http://127.0.0.1:2379'
max-snapshots: 3
max-wals: 5
cors:
initial-advertise-peer-urls: 'https://10.10.10.23:2380'
advertise-client-urls: 'https://10.10.10.23:2379'
discovery:
discovery-fallback: 'proxy'
discovery-proxy:
discovery-srv:
initial-cluster: 'master01=https://10.10.10.21:2380,master02=https://10.10.10.22:2380,master03=https://10.10.10.23:2380'
initial-cluster-token: 'etcd-k8s-cluster'
initial-cluster-state: 'new'
strict-reconfig-check: false
enable-v2: true
enable-pprof: true
proxy: 'off'
proxy-failure-wait: 5000
proxy-refresh-interval: 30000
proxy-dial-timeout: 1000
proxy-write-timeout: 5000
proxy-read-timeout: 0
client-transport-security:cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'client-cert-auth: truetrusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'auto-tls: true
peer-transport-security:cert-file: '/etc/kubernetes/pki/etcd/etcd.pem'key-file: '/etc/kubernetes/pki/etcd/etcd-key.pem'peer-client-cert-auth: truetrusted-ca-file: '/etc/kubernetes/pki/etcd/etcd-ca.pem'auto-tls: true
debug: false
log-package-levels:
log-outputs: [default]
force-new-cluster: false
EOF
2、配置etcd.service(所有master)
[root@master01 ~]# cat > /usr/lib/systemd/system/etcd.service << EOF[Unit]
Description=Etcd Service
Documentation=https://coreos.com/etcd/docs/latest/
After=network.target[Service]
Type=notify
ExecStart=/usr/local/bin/etcd --config-file=/etc/etcd/etcd.config.yml
Restart=on-failure
RestartSec=10
LimitNOFILE=65536[Install]
WantedBy=multi-user.target
Alias=etcd3.service
EOF
3、创建etcd证书目录
[root@master01 ~]# mkdir /etc/kubernetes/pki/etcd
[root@master01 ~]# ln -s /etc/etcd/ssl/* /etc/kubernetes/pki/etcd/
[root@master01 ~]# systemctl daemon-reload
[root@master01 ~]# systemctl enable --now etcd
4、查看etcd状态
[root@master01 ~]# export ETCDCTL_API=3
[root@master01 ~]# etcdctl --endpoints="10.10.10.21:2379,10.10.10.22:2379,10.10.10.23:2379" --cacert=/etc/kubernetes/pki/etcd/etcd-ca.pem --cert=/etc/kubernetes/pki/etcd/etcd.pem --key=/etc/kubernetes/pki/etcd/etcd-key.pem endpoint health --write-out=table
+------------------+--------+-------------+-------+
| ENDPOINT | HEALTH | TOOK | ERROR |
+------------------+--------+-------------+-------+
| 10.10.10.21:2379 | true | 15.031181ms | |
| 10.10.10.23:2379 | true | 18.406134ms | |
| 10.10.10.22:2379 | true | 17.884968ms | |
+------------------+--------+-------------+-------+[root@master01 ~]# etcdctl --endpoints="10.10.10.21:2379,10.10.10.22:2379,10.10.10.23:2379" --cacert=/etc/kubernetes/pki/etcd/etcd-ca.pem --cert=/etc/kubernetes/pki/etcd/etcd.pem --key=/etc/kubernetes/pki/etcd/etcd-key.pem endpoint status --write-out=table
+------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
| ENDPOINT | ID | VERSION | DB SIZE | IS LEADER | IS LEARNER | RAFT TERM | RAFT INDEX | RAFT APPLIED INDEX | ERRORS |
+------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
| 10.10.10.21:2379 | e25fc87884ebf1d0 | 3.5.9 | 9.0 MB | true | false | 3 | 26234 | 26234 | |
| 10.10.10.22:2379 | 88d337be31bcc4cb | 3.5.9 | 9.1 MB | false | false | 3 | 26234 | 26234 | |
| 10.10.10.23:2379 | 3328a27328e918a | 3.5.9 | 9.0 MB | false | false | 3 | 26234 | 26234 | |
+------------------+------------------+---------+---------+-----------+------------+-----------+------------+--------------------+--------+
四、高可用配置
1、安装nginx(master01)
[root@master01 ~]# yum install gcc -y
[root@master01 ~]# wget http://nginx.org/download/nginx-1.22.1.tar.gz
[root@master01 ~]# tar xvf nginx-1.22.1.tar.gz
[root@master01 nginx-1.22.1]# cd nginx-1.22.1/# 进行编译
[root@master01 nginx-1.22.1]# ./configure --with-stream --without-http --without-http_uwsgi_module --without-http_scgi_module --without-http_fastcgi_module
make && make install
2、发送nginx(master01)
# 拷贝编译好的nginx
[root@master01 ~]# node='master02 master03 node01 node02'
[root@master01 ~]# for NODE in $node; do scp -r /usr/local/nginx/ $NODE:/usr/local/nginx/; done
3、写入启动配置(所有机器)
# cat > /usr/local/nginx/conf/kube-nginx.conf <<EOF
worker_processes 1;
events {worker_connections 1024;
}
stream {upstream backend {least_conn;hash consistent;server 10.10.10.21:6443 max_fails=3 fail_timeout=30s;server 10.10.10.22:6443 max_fails=3 fail_timeout=30s;server 10.10.10.23:6443 max_fails=3 fail_timeout=30s;}server {listen 127.0.0.1:8443;proxy_connect_timeout 1s;proxy_pass backend;}
}
EOF# cat > /etc/systemd/system/kube-nginx.service <<EOF
[Unit]
Description=kube-apiserver nginx proxy
After=network.target
After=network-online.target
Wants=network-online.target[Service]
Type=forking
ExecStartPre=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/kube-nginx.conf -p /usr/local/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/kube-nginx.conf -p /usr/local/nginx
ExecReload=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/kube-nginx.conf -p /usr/local/nginx -s reload
PrivateTmp=true
Restart=always
RestartSec=5
StartLimitInterval=0
LimitNOFILE=65536[Install]
WantedBy=multi-user.target
EOF
4、设置开机自启(所有机器)
# systemctl enable --now kube-nginx
# systemctl restart kube-nginx
# systemctl status kube-nginx
五、安装Master节点组件
1、创建目录(所有机器)
# mkdir -p /etc/kubernetes/manifests/ /etc/systemd/system/kubelet.service.d /var/lib/kubelet /var/log/kubernetes
2、创建apiserver(所有master)
(1)配置master01
[root@master01 ~]# cat > /usr/lib/systemd/system/kube-apiserver.service <<EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes
After=network.target[Service]
ExecStart=/usr/local/bin/kube-apiserver \\--v=2 \\--allow-privileged=true \\--bind-address=0.0.0.0 \\--secure-port=6443 \\--advertise-address=10.10.10.21 \\--service-cluster-ip-range=10.96.0.0/12,fd00:1111::/112 \\--service-node-port-range=30000-32767 \\--etcd-servers=https://10.10.10.21:2379,https://10.10.10.22:2379,https://10.10.10.23:2379 \\--etcd-cafile=/etc/etcd/ssl/etcd-ca.pem \\--etcd-certfile=/etc/etcd/ssl/etcd.pem \\--etcd-keyfile=/etc/etcd/ssl/etcd-key.pem \\--client-ca-file=/etc/kubernetes/pki/ca.pem \\--tls-cert-file=/etc/kubernetes/pki/apiserver.pem \\--tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem \\--kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem \\--kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem \\--service-account-key-file=/etc/kubernetes/pki/sa.pub \\--service-account-signing-key-file=/etc/kubernetes/pki/sa.key \\--service-account-issuer=https://kubernetes.default.svc.cluster.local \\--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname \\--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota --authorization-mode=Node,RBAC \\--enable-bootstrap-token-auth=true \\--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem \\--proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem \\--proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem \\--requestheader-allowed-names=aggregator \\--requestheader-group-headers=X-Remote-Group \\--requestheader-extra-headers-prefix=X-Remote-Extra- \\--requestheader-username-headers=X-Remote-User \\--enable-aggregator-routing=true# --feature-gates=IPv6DualStack=true# --token-auth-file=/etc/kubernetes/token.csvRestart=on-failure
RestartSec=10s
LimitNOFILE=65535[Install]
WantedBy=multi-user.targetEOF
(2)配置master02
[root@master02 ~]# cat > /usr/lib/systemd/system/kube-apiserver.service <<EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes
After=network.target[Service]
ExecStart=/usr/local/bin/kube-apiserver \\--v=2 \\--allow-privileged=true \\--bind-address=0.0.0.0 \\--secure-port=6443 \\--advertise-address=10.10.10.22 \\--service-cluster-ip-range=10.96.0.0/12,fd00:1111::/112 \\--service-node-port-range=30000-32767 \\--etcd-servers=https://10.10.10.21:2379,https://10.10.10.22:2379,https://10.10.10.23:2379 \\--etcd-cafile=/etc/etcd/ssl/etcd-ca.pem \\--etcd-certfile=/etc/etcd/ssl/etcd.pem \\--etcd-keyfile=/etc/etcd/ssl/etcd-key.pem \\--client-ca-file=/etc/kubernetes/pki/ca.pem \\--tls-cert-file=/etc/kubernetes/pki/apiserver.pem \\--tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem \\--kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem \\--kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem \\--service-account-key-file=/etc/kubernetes/pki/sa.pub \\--service-account-signing-key-file=/etc/kubernetes/pki/sa.key \\--service-account-issuer=https://kubernetes.default.svc.cluster.local \\--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname \\--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota --authorization-mode=Node,RBAC \\--enable-bootstrap-token-auth=true \\--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem \\--proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem \\--proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem \\--requestheader-allowed-names=aggregator \\--requestheader-group-headers=X-Remote-Group \\--requestheader-extra-headers-prefix=X-Remote-Extra- \\--requestheader-username-headers=X-Remote-User \\--enable-aggregator-routing=true# --feature-gates=IPv6DualStack=true# --token-auth-file=/etc/kubernetes/token.csvRestart=on-failure
RestartSec=10s
LimitNOFILE=65535[Install]
WantedBy=multi-user.targetEOF
(3)配置master03
[root@master03 ~]# cat > /usr/lib/systemd/system/kube-apiserver.service <<EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes
After=network.target[Service]
ExecStart=/usr/local/bin/kube-apiserver \\--v=2 \\--allow-privileged=true \\--bind-address=0.0.0.0 \\--secure-port=6443 \\--advertise-address=10.10.10.23 \\--service-cluster-ip-range=10.96.0.0/12,fd00:1111::/112 \\--service-node-port-range=30000-32767 \\--etcd-servers=https://10.10.10.21:2379,https://10.10.10.22:2379,https://10.10.10.23:2379 \\--etcd-cafile=/etc/etcd/ssl/etcd-ca.pem \\--etcd-certfile=/etc/etcd/ssl/etcd.pem \\--etcd-keyfile=/etc/etcd/ssl/etcd-key.pem \\--client-ca-file=/etc/kubernetes/pki/ca.pem \\--tls-cert-file=/etc/kubernetes/pki/apiserver.pem \\--tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem \\--kubelet-client-certificate=/etc/kubernetes/pki/apiserver.pem \\--kubelet-client-key=/etc/kubernetes/pki/apiserver-key.pem \\--service-account-key-file=/etc/kubernetes/pki/sa.pub \\--service-account-signing-key-file=/etc/kubernetes/pki/sa.key \\--service-account-issuer=https://kubernetes.default.svc.cluster.local \\--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname \\--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,ResourceQuota --authorization-mode=Node,RBAC \\--enable-bootstrap-token-auth=true \\--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem \\--proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.pem \\--proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client-key.pem \\--requestheader-allowed-names=aggregator \\--requestheader-group-headers=X-Remote-Group \\--requestheader-extra-headers-prefix=X-Remote-Extra- \\--requestheader-username-headers=X-Remote-User \\--enable-aggregator-routing=true# --feature-gates=IPv6DualStack=true# --token-auth-file=/etc/kubernetes/token.csvRestart=on-failure
RestartSec=10s
LimitNOFILE=65535[Install]
WantedBy=multi-user.targetEOF
(4)启动apiserver(所有master)
# systemctl daemon-reload && systemctl enable --now kube-apiserver# 注意查看状态是否启动正常
# systemctl status kube-apiserver
3、部署controller-manager(所有master)
(1)配置kube-controller-manager.service
# cat > /usr/lib/systemd/system/kube-controller-manager.service << EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/kubernetes/kubernetes
After=network.target[Service]
ExecStart=/usr/local/bin/kube-controller-manager \\--v=2 \\--bind-address=127.0.0.1 \\--root-ca-file=/etc/kubernetes/pki/ca.pem \\--cluster-signing-cert-file=/etc/kubernetes/pki/ca.pem \\--cluster-signing-key-file=/etc/kubernetes/pki/ca-key.pem \\--service-account-private-key-file=/etc/kubernetes/pki/sa.key \\--kubeconfig=/etc/kubernetes/controller-manager.kubeconfig \\--leader-elect=true \\--use-service-account-credentials=true \\--node-monitor-grace-period=40s \\--node-monitor-period=5s \\--pod-eviction-timeout=2m0s \\--controllers=*,bootstrapsigner,tokencleaner \\--allocate-node-cidrs=true \\--service-cluster-ip-range=10.96.0.0/12,fd00:1111::/112 \\--cluster-cidr=172.16.0.0/12,fc00:2222::/112 \\--node-cidr-mask-size-ipv4=24 \\--node-cidr-mask-size-ipv6=120 \\--requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.pem # --feature-gates=IPv6DualStack=trueRestart=always
RestartSec=10s[Install]
WantedBy=multi-user.targetEOF
(2)启动manager
# systemctl daemon-reload
# systemctl enable --now kube-controller-manager
# systemctl status kube-controller-manager
4、部署scheduler(所有master)
(1)配置kube-scheduler.service
# cat > /usr/lib/systemd/system/kube-scheduler.service << EOF
[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/kubernetes/kubernetes
After=network.target[Service]
ExecStart=/usr/local/bin/kube-scheduler \\--v=2 \\--bind-address=127.0.0.1 \\--leader-elect=true \\--kubeconfig=/etc/kubernetes/scheduler.kubeconfigRestart=always
RestartSec=10s[Install]
WantedBy=multi-user.targetEOF
(2)启动scheduler
# systemctl daemon-reload
# systemctl restart kube-scheduler
# systemctl enable kube-scheduler
六、TLS Bootstrapping配置
1、配置bootstrap(master01)
# 若使用 haproxy、keepalived 那么为 `--server=https://10.10.10.30:8443`
# 若使用 nginx方案,那么为 `--server=https://127.0.0.1:8443`
[root@master01 ~]# cd bootstrap[root@master01 bootstrap]# kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.pem \
--embed-certs=true --server=https://127.0.0.1:8443 \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig[root@master01 bootstrap]# kubectl config set-credentials tls-bootstrap-token-user \
--token=c8ad9c.2e4d610cf3e7426e \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig[root@master01 bootstrap]# kubectl config set-context tls-bootstrap-token-user@kubernetes \
--cluster=kubernetes \
--user=tls-bootstrap-token-user \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig[root@master01 bootstrap]# kubectl config use-context tls-bootstrap-token-user@kubernetes \
--kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig# token的位置在bootstrap.secret.yaml,如果修改的话到这个文件修改
[root@master01 bootstrap]# mkdir -p /root/.kube ; cp /etc/kubernetes/admin.kubeconfig /root/.kube/config
2、查看状态以及配置secret
[root@master01 bootstrap]# kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME STATUS MESSAGE ERROR
etcd-2 Healthy {"health":"true","reason":""}
etcd-0 Healthy {"health":"true","reason":""}
etcd-1 Healthy {"health":"true","reason":""}
scheduler Healthy ok
controller-manager Healthy ok[root@master01 bootstrap]# kubectl create -f bootstrap.secret.yaml
七、安装Node节点组件(所有机器)
在1.19之后需要master节点也安装,不然访问很慢
1、在master01上将证书复制到node节点
[root@master01 ~]# cd /etc/kubernetes/[root@master01 kubernetes]# for NODE in master02 master03 node01 node02; do ssh $NODE mkdir -p /etc/kubernetes/pki; for FILE in pki/ca.pem pki/ca-key.pem pki/front-proxy-ca.pem bootstrap-kubelet.kubeconfig kube-proxy.kubeconfig; do scp /etc/kubernetes/$FILE $NODE:/etc/kubernetes/${FILE}; done; done
2、部署kubelet(所有机器)
(1)配置kubelet.service
# mkdir -p /var/lib/kubelet /var/log/kubernetes /etc/systemd/system/kubelet.service.d /etc/kubernetes/manifests/# cat > /usr/lib/systemd/system/kubelet.service << EOF
[Unit]
Description=Kubernetes Kubelet
Documentation=https://github.com/kubernetes/kubernetes
After=containerd.service
Requires=containerd.service[Service]
ExecStart=/usr/local/bin/kubelet \\--bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.kubeconfig \\--kubeconfig=/etc/kubernetes/kubelet.kubeconfig \\--config=/etc/kubernetes/kubelet-conf.yml \\--container-runtime-endpoint=unix:///run/containerd/containerd.sock \\--node-labels=node.kubernetes.io/node=# --feature-gates=IPv6DualStack=true# --container-runtime=remote# --runtime-request-timeout=15m# --cgroup-driver=systemd[Install]
WantedBy=multi-user.target
EOF
(2)创建kubelet的配置文件
# cat > /etc/kubernetes/kubelet-conf.yml <<EOF
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
address: 0.0.0.0
port: 10250
readOnlyPort: 10255
authentication:anonymous:enabled: falsewebhook:cacheTTL: 2m0senabled: truex509:clientCAFile: /etc/kubernetes/pki/ca.pem
authorization:mode: Webhookwebhook:cacheAuthorizedTTL: 5m0scacheUnauthorizedTTL: 30s
cgroupDriver: systemd
cgroupsPerQOS: true
clusterDNS:
- 10.96.0.10
clusterDomain: cluster.local
containerLogMaxFiles: 5
containerLogMaxSize: 10Mi
contentType: application/vnd.kubernetes.protobuf
cpuCFSQuota: true
cpuManagerPolicy: none
cpuManagerReconcilePeriod: 10s
enableControllerAttachDetach: true
enableDebuggingHandlers: true
enforceNodeAllocatable:
- pods
eventBurst: 10
eventRecordQPS: 5
evictionHard:imagefs.available: 15%memory.available: 100Minodefs.available: 10%nodefs.inodesFree: 5%
evictionPressureTransitionPeriod: 5m0s
failSwapOn: true
fileCheckFrequency: 20s
hairpinMode: promiscuous-bridge
healthzBindAddress: 127.0.0.1
healthzPort: 10248
httpCheckFrequency: 20s
imageGCHighThresholdPercent: 85
imageGCLowThresholdPercent: 80
imageMinimumGCAge: 2m0s
iptablesDropBit: 15
iptablesMasqueradeBit: 14
kubeAPIBurst: 10
kubeAPIQPS: 5
makeIPTablesUtilChains: true
maxOpenFiles: 1000000
maxPods: 110
nodeStatusUpdateFrequency: 10s
oomScoreAdj: -999
podPidsLimit: -1
registryBurst: 10
registryPullQPS: 5
resolvConf: /etc/resolv.conf
rotateCertificates: true
runtimeRequestTimeout: 2m0s
serializeImagePulls: true
staticPodPath: /etc/kubernetes/manifests
streamingConnectionIdleTimeout: 4h0m0s
syncFrequency: 1m0s
volumeStatsAggPeriod: 1m0s
EOF
(3)启动kubelet
# systemctl daemon-reload
# systemctl restart kubelet
# systemctl enable --now kubelet
(4)查看集群
# kubectl get node
NAME STATUS ROLES AGE VERSION
master01 Ready <none> 1h32m v1.26.5
master02 Ready <none> 1h32m v1.26.5
master03 Ready <none> 1h32m v1.26.5
node01 Ready <none> 1h32m v1.26.5
node02 Ready <none> 1h32m v1.26.
3、kube-proxy配置
(1)将kubeconfig发送至其他节点(master01)
[root@master01 ~]# for NODE in master02 master03; do scp /etc/kubernetes/kube-proxy.kubeconfig $NODE:/etc/kubernetes/kube-proxy.kubeconfig; done
[root@master01 ~]# for NODE in node01 node02; do scp /etc/kubernetes/kube-proxy.kubeconfig $NODE:/etc/kubernetes/kube-proxy.kubeconfig; done
(2)配置kube-proxy.service(所有机器)
# cat > /usr/lib/systemd/system/kube-proxy.service << EOF
[Unit]
Description=Kubernetes Kube Proxy
Documentation=https://github.com/kubernetes/kubernetes
After=network.target[Service]
ExecStart=/usr/local/bin/kube-proxy \\--config=/etc/kubernetes/kube-proxy.yaml \\--v=2Restart=always
RestartSec=10s[Install]
WantedBy=multi-user.targetEOF
(3)配置kube-proxy.yaml(所有机器)
# cat > /etc/kubernetes/kube-proxy.yaml << EOF
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
clientConnection:acceptContentTypes: ""burst: 10contentType: application/vnd.kubernetes.protobufkubeconfig: /etc/kubernetes/kube-proxy.kubeconfigqps: 5
clusterCIDR: 172.16.0.0/12,fc00:2222::/112
configSyncPeriod: 15m0s
conntrack:max: nullmaxPerCore: 32768min: 131072tcpCloseWaitTimeout: 1h0m0stcpEstablishedTimeout: 24h0m0s
enableProfiling: false
healthzBindAddress: 0.0.0.0:10256
hostnameOverride: ""
iptables:masqueradeAll: falsemasqueradeBit: 14minSyncPeriod: 0ssyncPeriod: 30s
ipvs:masqueradeAll: trueminSyncPeriod: 5sscheduler: "rr"syncPeriod: 30s
kind: KubeProxyConfiguration
metricsBindAddress: 127.0.0.1:10249
mode: "ipvs"
nodePortAddresses: null
oomScoreAdj: -999
portRange: ""
udpIdleTimeout: 250msEOF
(4)启动kube-proxy(所有机器)
# systemctl daemon-reload
# systemctl restart kube-proxy
# systemctl enable --now kube-proxy
八、安装网络cilium插件
1、升级libseccomp(所有机器)
# https://github.com/opencontainers/runc/releases
# 升级runc
# wget https://ghproxy.com/https://github.com/opencontainers/runc/releases/download/v1.1.4/runc.amd64
install -m 755 runc.amd64 /usr/local/sbin/runc
# cp -p /usr/local/sbin/runc /usr/local/bin/runc
# cp -p /usr/local/sbin/runc /usr/bin/runc#下载高于2.4以上的包
# yum -y install http://rpmfind.net/linux/centos/8-stream/BaseOS/x86_64/os/Packages/libseccomp-2.5.1-1.el8.x86_64.rpm#查看当前版本
# rpm -qa | grep libseccomp
libseccomp-2.5.1-1.el8.x86_64
2、安装helm(master01)
[root@master01 ~]# wget https://get.helm.sh/helm-canary-linux-amd64.tar.gz
[root@master01 ~]# tar xvf helm-canary-linux-amd64.tar.gz
[root@master01 ~]# cp linux-amd64/helm /usr/local/bin/
[root@master01 ~]# helm repo add cilium https://helm.cilium.io
3、下载cilium(master01)
### helm pull cilium/cilium(这样也可以下载)
[root@master01 ~]# wget --no-check-certificate https://helm.cilium.io/cilium-1.13.3.tgz
[root@master01 ~]# tar xvf cilium-1.13.3.tgz
4、三种不同参数安装(master01)
# 默认参数安装
helm install harbor ./cilium/ -n kube-system# 启用ipv6
# helm install cilium cilium/cilium --namespace kube-system --set ipv6.enabled=true# 启用路由信息和监控插件
# helm install cilium cilium/cilium --namespace kube-system --set hubble.relay.enabled=true --set hubble.ui.enabled=true --set prometheus.enabled=true --set operator.prometheus.enabled=true --set hubble.enabled=true --set hubble.metrics.enabled="{dns,drop,tcp,flow,port-distribution,icmp,http}"
5、安装失败处理
[root@master01 ~]# helm -n kube-system ls -a
NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION
harbor kube-system 1 2023-05-27 23:35:11.584665236 +0800 CST deployed cilium-1.13.3 1.13.3[root@master01 ~]# helm -n kube-system delete harbor
release "harbor" uninstalled
6、查看状态
[root@master01 ~]# kubectl get pod -A | grep cil
kube-system cilium-7jdbv 1/1 Running 0 1h3m
kube-system cilium-cbjvv 1/1 Running 0 1h3m
kube-system cilium-k2vff 1/1 Running 0 1h3m
kube-system cilium-operator-58bf55d99b-b6d5t 1/1 Running 0 1h3m
kube-system cilium-operator-58bf55d99b-zxmxp 1/1 Running 0 1h3m
kube-system cilium-t5hrl 1/1 Running 0 1h3m
kube-system cilium-zkbnn 1/1 Running 0 1h3m
九、安装CoreDNS(master01)
1、创建CoreDNS
[root@master01 ~]# cd coredns/
[root@master01 coredns]# cat coredns.yaml | grep clusterIP:clusterIP: 10.96.0.10[root@master01 coredns]# kubectl create -f coredns.yaml
2、查看状态
[root@master01 coredns]# kubectl get pod -A |grep coredns
kube-system coredns-568bb5dbff-sjkjs 1/1 Running 0 25s
十、安装Metrics Server
1、创建metrics-server
[root@master01 ~]# cd metrics-server/
[root@master01 metrics-server]# kubectl apply -f metrics-server.yaml
2、查看状态
[root@master01 metrics-server]# kubectl top node
NAME CPU(cores) CPU% MEMORY(bytes) MEMORY%
master01 95m 9% 1068Mi 58%
master02 84m 8% 1024Mi 55%
master03 64m 6% 757Mi 41%
node01 24m 2% 354Mi 42%
node02 26m 2% 379Mi 45%
参考文章
:https://github.com/cby-chen/Kubernetes/blob/main/doc/v1.26.1-CentOS-binary-install-IPv6-IPv4-Three-Masters-Two-Slaves-Offline.md