名称 | 版本 |
---|---|
CentOS | 7.5.1804 |
kubernetes verison | 1.16.15 |
docker-ce verison | 18.09.9 |
master | 192.168.100.108 |
worker | 192.168.100.110 |
(worker节点安装,master可装可不装)
wget -P /etc/yum.repos.d/ https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo #下载阿里repo文件
yum --showduplicates list docker-ce | expand #列出所有安装包
yum list docker-ce-18.09.9 #列出指定版本安装包
yum install docker-ce-18.09.9 docker-ce-cli-18.09.9 -y #安装指定版本的docker
#配置镜像加速
mkdir -p /etc/docker
mkdir -p /data/docker
cat > /etc/docker/daemon.json << EOF
{
"graph": "/data/docker",
"registry-mirrors": ["https://b9pmyelo.mirror.aliyuncs.com"]
}
EOF
#启动服务
systemctl daemon-reload
systemctl enable docker
systemctl start docker
#下载镜像
docker search flannel
docker pull lizhenliang/flannel
docker tag lizhenliang/flannel quay.io/coreos/flannel:v0.13.0
docker pull lizhenliang/pause-amd64:3.0
wget -P /usr/local/src/ https://dl.k8s.io/v1.12.10/kubernetes.tar.gz
wget -P /usr/local/src/ https://dl.k8s.io/v1.12.10/kubernetes-client-linux-amd64.tar.gz
wget -P /usr/local/src/ https://dl.k8s.io/v1.12.10/kubernetes-server-linux-amd64.tar.gz
wget -P /usr/local/src/ https://dl.k8s.io/v1.12.10/kubernetes-node-linux-amd64.tar.gz
wget -P /usr/local/src/ https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
wget -P /usr/local/src/ https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
wget -P /usr/local/src/ https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
wget -P /usr/local/src/ https://github.com/etcd-io/etcd/releases/download/v3.4.14/etcd-v3.4.14-linux-amd64.tar.gz
wget -P /usr/local/src/ https://github.com/coreos/flannel/releases/download/v0.13.0/flannel-v0.13.0-linux-amd64.tar.gz
wget -P /usr/local/src/ https://github.com/containernetworking/plugins/releases/download/v0.9.0/cni-plugins-linux-amd64-v0.9.0.tgz
cp /usr/local/src/cfssl_linux-amd64 /usr/local/bin/cfssl
cp /usr/local/src/cfssljson_linux-amd64 /usr/local/bin/cfssljson
cp /usr/local/src/cfssl-certinfo_linux-amd64 /usr/local/bin/cfssl-certinfo
chmod +x /usr/local/bin/cfssl*
mkdir -p ~/TLS/{etcd,k8s} && cd /root/TLS/etcd/
#创建ca配置文件
cat > ca-config.json << EOF
{
"signing": {
"default": {
"expiry": "87600h"
},
"profiles": {
"www": {
"expiry": "87600h",
"usages": [
"signing",
"key encipherment",
"server auth",
"client auth"
]
}
}
}
}
EOF
cat > ca-csr.json << EOF
{
"CN": "etcd CA",
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "Beijing",
"ST": "Beijing"
}
]
}
EOF
#生成证书
cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
ls *pem
#输出
ca-key.pem ca.pem
#创建证书申请文件
cat > server-csr.json << EOF
{
"CN": "etcd",
"hosts": [
"192.168.100.108",
"192.168.100.110"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "BeiJing",
"ST": "BeiJing"
}
]
}
EOF
#生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=www server-csr.json | cfssljson -bare server
ls server*pem
#输出
server-key.pem server.pem
#解压etcd安装包
mkdir /opt/etcd/{bin,cfg,ssl} -p
cd /usr/local/src/
tar -zxvf etcd-v3.4.14-linux-amd64.tar.gz
cp etcd-v3.4.14-linux-amd64.tar.gz/{etcd,etcdctl} /opt/etcd/bin/
#创建etcd配置文件
cat > /opt/etcd/cfg/etcd.conf << EOF
#[Member]
ETCD_NAME="etcd-1"
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="https://192.168.100.108:2380"
ETCD_LISTEN_CLIENT_URLS="https://192.168.100.108:2379"
#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://192.168.100.108:2380"
ETCD_ADVERTISE_CLIENT_URLS="https://192.168.100.108:2379"
ETCD_INITIAL_CLUSTER="etcd-1=https://192.168.100.108:2380,etcd-2=https://192.168.100.110:2380"
ETCD_INITIAL_CLUSTER_TOKEN="etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
EOF
cat > /usr/lib/systemd/system/etcd.service << EOF
[Unit]
Description=Etcd Server
After=network.target
After=network-online.target
Wants=network-online.target
[Service]
Type=notify
EnvironmentFile=/opt/etcd/cfg/etcd.conf
ExecStart=/opt/etcd/bin/etcd \
--cert-file=/opt/etcd/ssl/server.pem \
--key-file=/opt/etcd/ssl/server-key.pem \
--peer-cert-file=/opt/etcd/ssl/server.pem \
--peer-key-file=/opt/etcd/ssl/server-key.pem \
--trusted-ca-file=/opt/etcd/ssl/ca.pem \
--peer-trusted-ca-file=/opt/etcd/ssl/ca.pem \
--logger=zap
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
#拷贝证书
cp ~/TLS/etcd/ca*pem /opt/etcd/ssl/
cp -a ~/TLS/etcd/server*pem /opt/etcd/ssl/
ll /opt/etcd/ssl/
#输出
total 16
-rw------- 1 root root 1679 Feb 10 13:42 ca-key.pem
-rw-r--r-- 1 root root 1265 Feb 10 13:42 ca.pem
-rw------- 1 root root 1675 Feb 10 13:42 server-key.pem
-rw-r--r-- 1 root root 1330 Feb 10 13:42 server.pem
#拷贝文件至node节点
ssh node1 mkdir /opt/etcd/{bin,cfg,ssl} -p #为node节点创建目录
scp -r /opt/etcd/ node1:/opt
scp -r /usr/lib/systemd/system/etcd.service node1:/usr/lib/systemd/system/
scp /opt/etcd/cfg/etcd.conf node1:/opt/etcd/cfg/
#node节点修改etcd配置文件
vim /opt/etcd/cfg/etcd.conf
#[Member]
ETCD_NAME="etcd-2" # 修改此处,节点2改为etcd-2,节点3改为etcd-3
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="https://192.168.100.110:2380" # 修改此处为当前服务器IP
ETCD_LISTEN_CLIENT_URLS="https://192.168.100.110:2379" # 修改此处为当前服务器IP
#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://192.168.100.110:2380" # 修改此处为当前服务器IP
ETCD_ADVERTISE_CLIENT_URLS="https://192.168.100.110:2379" # 修改此处为当前服务器IP
ETCD_INITIAL_CLUSTER="etcd-1=https://192.168.100.108:2380,etcd-2=https://192.168.100.110:2380"
ETCD_INITIAL_CLUSTER_TOKEN="etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
#启动服务器,node节点同时启动
systemctl daemon-reload
systemctl start etcd
systemctl enable etcd
#查看集群状态
ETCDCTL_API=3 /opt/etcd/bin/etcdctl --cacert=/opt/etcd/ssl/ca.pem --cert=/opt/etcd/ssl/server.pem --key=/opt/etcd/ssl/server-key.pem --endpoints="https://192.168.100.108:2379,https://192.168.100.110:2379" endpoint health
#输出
https://192.168.100.108:2379 is healthy: successfully committed proposal: took = 33.994781ms
https://192.168.100.110:2379 is healthy: successfully committed proposal: took = 35.049844ms
制作apiserver证书
mkdir -p /root/TLS/apiserver && cd /root/TLS/apiserver/
cat > ca-config.json << EOF
{
"signing": {
"default": {
"expiry": "87600h"
},
"profiles": {
"kubernetes": {
"expiry": "87600h",
"usages": [
"signing",
"key encipherment",
"server auth",
"client auth"
]
}
}
}
}
EOF
cat > ca-csr.json << EOF
{
"CN": "kubernetes",
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "Beijing",
"ST": "Beijing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
#生成证书
cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
ll *pem
#输出
-rw------- 1 root root 1675 Feb 10 14:41 ca-key.pem
-rw-r--r-- 1 root root 1359 Feb 10 14:41 ca.pem
#创建apiserver https证书
#工作目录/root/TLS/apiserver
cat > server-csr.json << EOF
{
"CN": "kubernetes",
"hosts": [
"10.0.0.1",
"127.0.0.1",
"192.168.100.108",
"192.168.100.110",
"kubernetes",
"kubernetes.default",
"kubernetes.default.svc",
"kubernetes.default.svc.cluster",
"kubernetes.default.svc.cluster.local"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "BeiJing",
"ST": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes server-csr.json | cfssljson -bare server
#输出
2021/02/10 14:43:53 [INFO] generate received request
2021/02/10 14:43:53 [INFO] received CSR
2021/02/10 14:43:53 [INFO] generating key: rsa-2048
2021/02/10 14:43:54 [INFO] encoded CSR
2021/02/10 14:43:54 [INFO] signed certificate with serial number 428652289545589142514966989351494232826426284544
2021/02/10 14:43:54 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").
#查看
ll server*pem
#输出
-rw------- 1 root root 1675 Feb 10 14:43 server-key.pem
-rw-r--r-- 1 root root 1619 Feb 10 14:43 server.pem
安装apiserver服务
#解压安装包
-p /opt/kubernetes/{bin,cfg,ssl,logs}
cd /usr/local/src/
tar -zxvf kubernetes-server-linux-amd64.tar.gz
cd kubernetes/server/bin/
cp kube-apiserver /opt/kubernetes/bin/
cp kube-scheduler /opt/kubernetes/bin/
cp kube-controller-manager /opt/kubernetes/bin/
cp kubectl /usr/bin/
#创建配置文件
cat > /opt/kubernetes/cfg/kube-apiserver.conf << EOF
KUBE_APISERVER_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/kubernetes/logs \\
--etcd-servers=https://192.168.100.108:2379,https://192.168.100.110:2379 \\
--bind-address=192.168.100.108 \\
--secure-port=6443 \\
--advertise-address=192.168.100.108 \\
--allow-privileged=true \\
--service-cluster-ip-range=10.0.0.0/24 \\
--enable-admission-plugins=NamespaceLifecycle,LimitRanger,ServiceAccount,ResourceQuota,NodeRestriction \\
--authorization-mode=RBAC,Node \\
--enable-bootstrap-token-auth=true \\
--token-auth-file=/opt/kubernetes/cfg/token.csv \\
--service-node-port-range=30000-32767 \\
--kubelet-client-certificate=/opt/kubernetes/ssl/server.pem \\
--kubelet-client-key=/opt/kubernetes/ssl/server-key.pem \\
--tls-cert-file=/opt/kubernetes/ssl/server.pem \\
--tls-private-key-file=/opt/kubernetes/ssl/server-key.pem \\
--client-ca-file=/opt/kubernetes/ssl/ca.pem \\
--service-account-key-file=/opt/kubernetes/ssl/ca-key.pem \\
--etcd-cafile=/opt/etcd/ssl/ca.pem \\
--etcd-certfile=/opt/etcd/ssl/server.pem \\
--etcd-keyfile=/opt/etcd/ssl/server-key.pem \\
--audit-log-maxage=30 \\
--audit-log-maxbackup=3 \\
--audit-log-maxsize=100 \\
--audit-log-path=/opt/kubernetes/logs/k8s-audit.log"
EOF
注释:上面两个\ \ 第一个是转义符,第二个是换行符,使用转义符是为了使用EOF保留换行符。
#拷贝证书至配置文件中的目录
cp -a /root/TLS/apiserver/ca*pem /opt/kubernetes/ssl/
cp -a /root/TLS/apiserver/server*pem /opt/kubernetes/ssl/
ll /opt/kubernetes/ssl/
#输出
total 16
-rw------- 1 root root 1675 Feb 10 14:41 ca-key.pem
-rw-r--r-- 1 root root 1359 Feb 10 14:41 ca.pem
-rw------- 1 root root 1675 Feb 10 14:43 server-key.pem
-rw-r--r-- 1 root root 1619 Feb 10 14:43 server.pem
启动TLS bootstrapping机制
#生成token
head -c 16 /dev/urandom | od -An -t x | tr -d ' '
b3059ea6ee7750d23813c526b71a3e17
#创建token文件
cat > /opt/kubernetes/cfg/token.csv << EOF
b3059ea6ee7750d23813c526b71a3e17,kubelet-bootstrap,10001,"system:node-bootstrapper"
EOF
使用systemd管理apiserver服务
cat > /usr/lib/systemd/system/kube-apiserver.service << EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes
[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-apiserver.conf
ExecStart=/opt/kubernetes/bin/kube-apiserver \$KUBE_APISERVER_OPTS
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
启动服务
systemctl daemon-reload
systemctl start kube-apiserver
systemctl status kube-apiserver
systemctl enable kube-apiserver
授权kubelet-bootstrap用户允许请求证书
kubectl create clusterrolebinding kubelet-bootstrap \
--clusterrole=system:node-bootstrapper \
--user=kubelet-bootstrap
创建配置文件
cat > /opt/kubernetes/cfg/kube-controller-manager.conf << EOF
KUBE_CONTROLLER_MANAGER_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/kubernetes/logs \\
--leader-elect=true \\
--master=127.0.0.1:8080 \\
--bind-address=127.0.0.1 \\
--allocate-node-cidrs=true \\
--cluster-cidr=10.244.0.0/16 \\
--service-cluster-ip-range=10.0.0.0/24 \\
--cluster-signing-cert-file=/opt/kubernetes/ssl/ca.pem \\
--cluster-signing-key-file=/opt/kubernetes/ssl/ca-key.pem \\
--root-ca-file=/opt/kubernetes/ssl/ca.pem \\
--service-account-private-key-file=/opt/kubernetes/ssl/ca-key.pem \\
--experimental-cluster-signing-duration=87600h0m0s"
EOF
创建服务的systemd配置管理文件
cat > /usr/lib/systemd/system/kube-controller-manager.service << EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/kubernetes/kubernetes
[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-controller-manager.conf
ExecStart=/opt/kubernetes/bin/kube-controller-manager \$KUBE_CONTROLLER_MANAGER_OPTS
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
启动服务
systemctl daemon-reload
systemctl start kube-controller-manager
systemctl enable kube-controller-manager
创建配置文件
cat > /opt/kubernetes/cfg/kube-scheduler.conf << EOF
KUBE_SCHEDULER_OPTS="--logtostderr=false \
--v=2 \
--log-dir=/opt/kubernetes/logs \
--leader-elect \
--master=127.0.0.1:8080 \
--bind-address=127.0.0.1"
EOF
使用systemd管理服务
cat > /usr/lib/systemd/system/kube-scheduler.service << EOF
[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/kubernetes/kubernetes
[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-scheduler.conf
ExecStart=/opt/kubernetes/bin/kube-scheduler \$KUBE_SCHEDULER_OPTS
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
启动服务
systemctl daemon-reload
systemctl start kube-scheduler
systemctl enable kube-scheduler
查看集群状态
说明:kubernetes 在1.16版本的时候,查看cs集群状态,服务会出现unknow状态,网上查询说明,可能是cs接口被移除,在后续版本中可能还可以使用这个接口查询集群状态,v1.16.15版本尝试使用以下命令:
kubectl get cs -o=go-template='{{printf "NAME\t\t\tHEALTH_STATUS\tMESSAGE\t\n"}}{{range .items}}{{$name := .metadata.name}}{{range .conditions}}{{printf "%-24s%-16s%-20s\n" $name .status .message}}{{end}}{{end}}'
说明:还是在master节点上操作,即master节点同时作为worker节点。
#在所有worker节点操作
mkdir -p /opt/kubernetes/{bin,cfg,ssl,logs}
#拷贝kubelet kube-proxy配置文件
scp master:/usr/local/src/kubernetes/server/bin/{kubelet,kube-proxy} /opt/kubernetes/bin/
(在master上创建后拷贝到worker节点)
创建配置文件
cat > /opt/kubernetes/cfg/kubelet.conf << EOF
KUBELET_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/kubernetes/logs \\
--hostname-override=master \\
--network-plugin=cni \\
--kubeconfig=/opt/kubernetes/cfg/kubelet.kubeconfig \\
--bootstrap-kubeconfig=/opt/kubernetes/cfg/bootstrap.kubeconfig \\
--config=/opt/kubernetes/cfg/kubelet-config.yml \\
--cert-dir=/opt/kubernetes/ssl \\
--pod-infra-container-image=lizhenliang/pause-amd64:3.0"
EOF
cat > /opt/kubernetes/cfg/kubelet-config.yml << EOF
kind: KubeletConfiguration
apiVersion: kubelet.config.k8s.io/v1beta1
address: 0.0.0.0
port: 10250
readOnlyPort: 10255
cgroupDriver: cgroupfs
clusterDNS:
- 10.0.0.2
clusterDomain: cluster.local
failSwapOn: false
authentication:
anonymous:
enabled: false
webhook:
cacheTTL: 2m0s
enabled: true
x509:
clientCAFile: /opt/kubernetes/ssl/ca.pem
authorization:
mode: Webhook
webhook:
cacheAuthorizedTTL: 5m0s
cacheUnauthorizedTTL: 30s
evictionHard:
imagefs.available: 15%
memory.available: 100Mi
nodefs.available: 10%
nodefs.inodesFree: 5%
maxOpenFiles: 1000000
maxPods: 110
EOF
生成bootstrap.kubeconfig脚本
vim bootstrap-kubeconfig.sh
-----------------------------------------------------------------------
#!/bin/bash
KUBE_APISERVER="https://192.168.100.108:6443" # apiserver IP:PORT
TOKEN="b3059ea6ee7750d23813c526b71a3e17" # 与token.csv里保持一致
# 生成 kubelet bootstrap kubeconfig 配置文件
kubectl config set-cluster kubernetes \
--certificate-authority=/opt/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server=${KUBE_APISERVER} \
--kubeconfig=bootstrap.kubeconfig
kubectl config set-credentials "kubelet-bootstrap" \
--token=${TOKEN} \
--kubeconfig=bootstrap.kubeconfig
kubectl config set-context default \
--cluster=kubernetes \
--user="kubelet-bootstrap" \
--kubeconfig=bootstrap.kubeconfig
kubectl config use-context default --kubeconfig=bootstrap.kubeconfig
------------------------------------------------------------------------------
#执行输出
[root@master ~]# bash bootstrap-kubeconfig.sh
Cluster "kubernetes" set.
User "kubelet-bootstrap" set.
Context "default" created.
Switched to context "default".
#拷贝生成文件
cp -a bootstrap.kubeconfig /opt/kubernetes/cfg/
使用systemd管理kubelet
cat > /usr/lib/systemd/system/kubelet.service << EOF
[Unit]
Description=Kubernetes Kubelet
After=docker.service
[Service]
EnvironmentFile=/opt/kubernetes/cfg/kubelet.conf
ExecStart=/opt/kubernetes/bin/kubelet \$KUBELET_OPTS
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
设置开机启动
systemctl daemon-reload
systemctl start kubelet
systemctl enable kubelet
设置kubelet证书申请并加入集群
# 查看kubelet证书请求
[root@master ~]# kubectl get csr
NAME AGE REQUESTOR CONDITION
node-csr-RgoEH4A6kVERa6gmY4a0wO4-s6IaqD8F6qEBOpNqoFI 92s kubelet-bootstrap Pending
# 批准申请
[root@master ~]# kubectl certificate approve node-csr-RgoEH4A6kVERa6gmY4a0wO4-s6IaqD8F6qEBOpNqoFI
certificatesigningrequest.certificates.k8s.io/node-csr-RgoEH4A6kVERa6gmY4a0wO4-s6IaqD8F6qEBOpNqoFI approved
#查看节点
[root@master ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
master NotReady <none> 9s v1.16.15
创建配置文件
cat > /opt/kubernetes/cfg/kube-proxy.conf << EOF
KUBE_PROXY_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/kubernetes/logs \\
--config=/opt/kubernetes/cfg/kube-proxy-config.yml"
EOF
配置config文件
cat > /opt/kubernetes/cfg/kube-proxy-config.yml << EOF
kind: KubeProxyConfiguration
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
metricsBindAddress: 0.0.0.0:10249
clientConnection:
kubeconfig: /opt/kubernetes/cfg/kube-proxy.kubeconfig
hostnameOverride: master
clusterCIDR: 10.0.0.0/24
EOF
生成kube-proxy证书
#切换到apiserver的目录下
cd /root/TLS/apiserver/
# 创建证书请求文件
cat > kube-proxy-csr.json << EOF
{
"CN": "system:kube-proxy",
"hosts": [],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "BeiJing",
"ST": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
# 生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-proxy-csr.json | cfssljson -bare kube-proxy
# 查看证书
ls kube-proxy*pem
生成kubeconfig配置文件
vim kubeconfig.sh
--------------------------------------------------------------------
#!/bin/bash
KUBE_APISERVER="https://192.168.100.108:6443" #修改本地ip地址
kubectl config set-cluster kubernetes \
--certificate-authority=/opt/kubernetes/ssl/ca.pem \
--embed-certs=true \
--server=${KUBE_APISERVER} \
--kubeconfig=kube-proxy.kubeconfig
kubectl config set-credentials kube-proxy \
--client-certificate=/root/TLS/apiserver/kube-proxy.pem \
--client-key=/root/TLS/apiserver/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
-------------------------------------------------------------------------
#执行脚本
[root@master ~]# bash kube-proxy-config.sh
Cluster "kubernetes" set.
User "kube-proxy" set.
Context "default" modified.
Switched to context "default".
#拷贝配置文件
cp -a kube-proxy.kubeconfig /opt/kubernetes/cfg/
使用systemd管理服务
cat > /usr/lib/systemd/system/kube-proxy.service << EOF
[Unit]
Description=Kubernetes Proxy
After=network.target
[Service]
EnvironmentFile=/opt/kubernetes/cfg/kube-proxy.conf
ExecStart=/opt/kubernetes/bin/kube-proxy \$KUBE_PROXY_OPTS
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
启动服务
systemctl daemon-reload
systemctl start kube-proxy
systemctl enable kube-proxy
创建目录拷贝安装包
mkdir -p /opt/cni/bin
cd /usr/local/src
tar -zxvf cni-plugins-linux-amd64-v0.9.0.tgz -C /opt/cni/bin/
./
./macvlan
./flannel
./static
./vlan
./portmap
./host-local
./vrf
./bridge
./tuning
./firewall
./host-device
./sbr
./loopback
./dhcp
./ptp
./ipvlan
./bandwidth
创建配置文件
#flannel yml文件地址https://github.com/flannel-io/flannel/tree/master/Documentation
vim kube-flannel.yml
#以下是文件内容
---
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: psp.flannel.unprivileged
annotations:
seccomp.security.alpha.kubernetes.io/allowedProfileNames: docker/default
seccomp.security.alpha.kubernetes.io/defaultProfileName: docker/default
apparmor.security.beta.kubernetes.io/allowedProfileNames: runtime/default
apparmor.security.beta.kubernetes.io/defaultProfileName: runtime/default
spec:
privileged: false
volumes:
- configMap
- secret
- emptyDir
- hostPath
allowedHostPaths:
- pathPrefix: "/etc/cni/net.d"
- pathPrefix: "/etc/kube-flannel"
- pathPrefix: "/run/flannel"
readOnlyRootFilesystem: false
# Users and groups
runAsUser:
rule: RunAsAny
supplementalGroups:
rule: RunAsAny
fsGroup:
rule: RunAsAny
# Privilege Escalation
allowPrivilegeEscalation: false
defaultAllowPrivilegeEscalation: false
# Capabilities
allowedCapabilities: ['NET_ADMIN', 'NET_RAW']
defaultAddCapabilities: []
requiredDropCapabilities: []
# Host namespaces
hostPID: false
hostIPC: false
hostNetwork: true
hostPorts:
- min: 0
max: 65535
# SELinux
seLinux:
# SELinux is unused in CaaSP
rule: 'RunAsAny'
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: flannel
rules:
- apiGroups: ['extensions']
resources: ['podsecuritypolicies']
verbs: ['use']
resourceNames: ['psp.flannel.unprivileged']
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- apiGroups:
- ""
resources:
- nodes
verbs:
- list
- watch
- apiGroups:
- ""
resources:
- nodes/status
verbs:
- patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: flannel
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: flannel
subjects:
- kind: ServiceAccount
name: flannel
namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: flannel
namespace: kube-system
---
kind: ConfigMap
apiVersion: v1
metadata:
name: kube-flannel-cfg
namespace: kube-system
labels:
tier: node
app: flannel
data:
cni-conf.json: |
{
"name": "cbr0",
"cniVersion": "0.3.1",
"plugins": [
{
"type": "flannel",
"delegate": {
"hairpinMode": true,
"isDefaultGateway": true
}
},
{
"type": "portmap",
"capabilities": {
"portMappings": true
}
}
]
}
net-conf.json: |
{
"Network": "10.244.0.0/16",
"Backend": {
"Type": "vxlan"
}
}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: kube-flannel-ds
namespace: kube-system
labels:
tier: node
app: flannel
spec:
selector:
matchLabels:
app: flannel
template:
metadata:
labels:
tier: node
app: flannel
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/os
operator: In
values:
- linux
hostNetwork: true
priorityClassName: system-node-critical
tolerations:
- operator: Exists
effect: NoSchedule
serviceAccountName: flannel
initContainers:
- name: install-cni
image: quay.io/coreos/flannel:v0.13.0
command:
- cp
args:
- -f
- /etc/kube-flannel/cni-conf.json
- /etc/cni/net.d/10-flannel.conflist
volumeMounts:
- name: cni
mountPath: /etc/cni/net.d
- name: flannel-cfg
mountPath: /etc/kube-flannel/
containers:
- name: kube-flannel
image: quay.io/coreos/flannel:v0.13.0
command:
- /opt/bin/flanneld
args:
- --ip-masq
- --kube-subnet-mgr
resources:
requests:
cpu: "100m"
memory: "50Mi"
limits:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: false
capabilities:
add: ["NET_ADMIN", "NET_RAW"]
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
volumeMounts:
- name: run
mountPath: /run/flannel
- name: flannel-cfg
mountPath: /etc/kube-flannel/
volumes:
- name: run
hostPath:
path: /run/flannel
- name: cni
hostPath:
path: /etc/cni/net.d
- name: flannel-cfg
configMap:
name: kube-flannel-cfg
-------------------------------------------------------------------------
#创建flannel服务
[root@master ~]# 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 created
#查看容器运行状态
[root@master ~]# kubectl get pods -n kube-system
NAME READY STATUS RESTARTS AGE
kube-flannel-ds-cqwgq 1/1 Running 0 42s
#查看node状态
[root@master ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
master Ready <none> 163m v1.16.15
#创建配置文件
cat > apiserver-to-kubelet-rbac.yaml << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
annotations:
rbac.authorization.kubernetes.io/autoupdate: "true"
labels:
kubernetes.io/bootstrapping: rbac-defaults
name: system:kube-apiserver-to-kubelet
rules:
- apiGroups:
- ""
resources:
- nodes/proxy
- nodes/stats
- nodes/log
- nodes/spec
- nodes/metrics
- pods/log
verbs:
- "*"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: system:kube-apiserver
namespace: ""
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: system:kube-apiserver-to-kubelet
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: kubernetes
EOF
# 执行配置文件
[root@master ~]# kubectl apply -f apiserver-to-kubelet-rbac.yaml
clusterrole.rbac.authorization.k8s.io/system:kube-apiserver-to-kubelet created
clusterrolebinding.rbac.authorization.k8s.io/system:kube-apiserver created
拷贝文件
#在master节点操作
ssh node1 mkdir -p /opt/cni/
scp -r /opt/cni/ node1:/opt/cni/
scp /opt/kubernetes/bin/kubelet node1:/opt/kubernetes/bin/
scp /opt/kubernetes/bin/kube-proxy node1:/opt/kubernetes/bin/
scp /opt/kubernetes/ssl/ca.pem node1:/opt/kubernetes/ssl/
scp /opt/kubernetes/cfg/kube-proxy* node1:/opt/kubernetes/cfg/
scp /opt/kubernetes/cfg/kubelet* node1:/opt/kubernetes/cfg/
scp /opt/kubernetes/cfg/bootstrap.kubeconfig node1:/opt/kubernetes/cfg/
scp -r /usr/lib/systemd/system/{kubelet,kube-proxy}.service node1:/usr/lib/systemd/system
#以下在worker节点上操作
rm -f /opt/kubernetes/cfg/kubelet.kubeconfig
rm -f /opt/kubernetes/ssl/kubelet*
#修改kubelet和kube-proxy配置文件
vim /opt/kubernetes/cfg/kubelet.conf
---------------------------------------------------
--hostname-override=master
# 把上面的修改为下面这种
--hostname-override=node1
--------------------------------------------------
vim /opt/kubernetes/cfg/kube-proxy-config.yml
---------------------------------------------------
hostnameOverride: master
#把上面得修改为下面的
hostnameOverride: node1
---------------------------------------------------
#启动服务
systemctl daemon-reload
systemctl start kubelet
systemctl enable kubelet
systemctl start kube-proxy
systemctl enable kube-proxy
新节点认证
#查看kubelet申请证书
[root@master ~]# kubectl get csr
NAME AGE REQUESTOR CONDITION
node-csr-9RG_O18U0KpTNsdUQAHcfWRtx4uMpgK87rDFH_IMCBE 16h kubelet-bootstrap Pending
#加入新节点
[root@master ~]# kubectl certificate approve node-csr-9RG_O18U0KpTNsdUQAHcfWRtx4uMpgK87rDFH_IMCBE
certificatesigningrequest.certificates.k8s.io/node-csr-9RG_O18U0KpTNsdUQAHcfWRtx4uMpgK87rDFH_IMCBE approved
#查看节点状态
[root@master opt]# kubectl get node
NAME STATUS ROLES AGE VERSION
master Ready <none> 25h v1.16.15
node1 Ready <none> 5h38m v1.16.15
链接地址:https://github.com/kubernetes/kubernetes/tree/v1.20.4/cluster/addons/dashboard
打开后复制本地,上传到节点上
修改文件,在32、36行添加port类型和端口
apiVersion: v1
kind: Namespace
metadata:
name: kubernetes-dashboard
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: Reconcile
---
apiVersion: v1
kind: ServiceAccount
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: Reconcile
name: kubernetes-dashboard
namespace: kubernetes-dashboard
---
kind: Service
apiVersion: v1
metadata:
labels:
k8s-app: kubernetes-dashboard
kubernetes.io/cluster-service: "true"
addonmanager.kubernetes.io/mode: Reconcile
name: kubernetes-dashboard
namespace: kubernetes-dashboard
spec:
type: NodePort #添加port类型
ports:
- port: 443
targetPort: 8443
nodePort: 30001 #添加端口号
selector:
k8s-app: kubernetes-dashboard
---
apiVersion: v1
kind: Secret
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: EnsureExists
name: kubernetes-dashboard-certs
namespace: kubernetes-dashboard
type: Opaque
---
apiVersion: v1
kind: Secret
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: EnsureExists
name: kubernetes-dashboard-csrf
namespace: kubernetes-dashboard
type: Opaque
data:
csrf: ""
---
apiVersion: v1
kind: Secret
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: EnsureExists
name: kubernetes-dashboard-key-holder
namespace: kubernetes-dashboard
type: Opaque
---
kind: ConfigMap
apiVersion: v1
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: EnsureExists
name: kubernetes-dashboard-settings
namespace: kubernetes-dashboard
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: Reconcile
name: kubernetes-dashboard
namespace: kubernetes-dashboard
rules:
- apiGroups: [""]
resources: ["secrets"]
resourceNames: ["kubernetes-dashboard-key-holder", "kubernetes-dashboard-certs", "kubernetes-dashboard-csrf"]
verbs: ["get", "update", "delete"]
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["kubernetes-dashboard-settings"]
verbs: ["get", "update"]
- apiGroups: [""]
resources: ["services"]
resourceNames: ["heapster", "dashboard-metrics-scraper"]
verbs: ["proxy"]
- apiGroups: [""]
resources: ["services/proxy"]
resourceNames: ["heapster", "http:heapster:", "https:heapster:", "dashboard-metrics-scraper", "http:dashboard-metrics-scraper"]
verbs: ["get"]
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: Reconcile
name: kubernetes-dashboard
rules:
- apiGroups: ["metrics.k8s.io"]
resources: ["pods", "nodes"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: Reconcile
name: kubernetes-dashboard
namespace: kubernetes-dashboard
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: kubernetes-dashboard
subjects:
- kind: ServiceAccount
name: kubernetes-dashboard
namespace: kubernetes-dashboard
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: kubernetes-dashboard
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: Reconcile
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: kubernetes-dashboard
subjects:
- kind: ServiceAccount
name: kubernetes-dashboard
namespace: kubernetes-dashboard
---
kind: Deployment
apiVersion: apps/v1
metadata:
labels:
k8s-app: kubernetes-dashboard
name: kubernetes-dashboard
namespace: kubernetes-dashboard
spec:
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
k8s-app: kubernetes-dashboard
template:
metadata:
labels:
k8s-app: kubernetes-dashboard
spec:
containers:
- name: kubernetes-dashboard
image: kubernetesui/dashboard:v2.0.1
imagePullPolicy: Always
ports:
- containerPort: 8443
protocol: TCP
args:
- --auto-generate-certificates
- --namespace=kubernetes-dashboard
volumeMounts:
- name: kubernetes-dashboard-certs
mountPath: /certs
- mountPath: /tmp
name: tmp-volume
livenessProbe:
httpGet:
scheme: HTTPS
path: /
port: 8443
initialDelaySeconds: 30
timeoutSeconds: 30
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsUser: 1001
runAsGroup: 2001
volumes:
- name: kubernetes-dashboard-certs
secret:
secretName: kubernetes-dashboard-certs
- name: tmp-volume
emptyDir: {}
serviceAccountName: kubernetes-dashboard
nodeSelector:
"kubernetes.io/os": linux
tolerations:
- key: "CriticalAddonsOnly"
operator: "Exists"
- key: node-role.kubernetes.io/master
effect: NoSchedule
---
kind: Service
apiVersion: v1
metadata:
labels:
k8s-app: dashboard-metrics-scraper
name: dashboard-metrics-scraper
namespace: kubernetes-dashboard
spec:
ports:
- port: 8000
targetPort: 8000
selector:
k8s-app: dashboard-metrics-scraper
---
kind: Deployment
apiVersion: apps/v1
metadata:
labels:
k8s-app: dashboard-metrics-scraper
name: dashboard-metrics-scraper
namespace: kubernetes-dashboard
spec:
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
k8s-app: dashboard-metrics-scraper
template:
metadata:
labels:
k8s-app: dashboard-metrics-scraper
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: dashboard-metrics-scraper
image: kubernetesui/metrics-scraper:v1.0.4
ports:
- containerPort: 8000
protocol: TCP
livenessProbe:
httpGet:
scheme: HTTP
path: /
port: 8000
initialDelaySeconds: 30
timeoutSeconds: 30
volumeMounts:
- mountPath: /tmp
name: tmp-volume
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
runAsUser: 1001
runAsGroup: 2001
serviceAccountName: kubernetes-dashboard
nodeSelector:
"kubernetes.io/os": linux
tolerations:
- key: node-role.kubernetes.io/master
effect: NoSchedule
volumes:
- name: tmp-volume
emptyDir: {}
创建自签名证书
cd /root/TLS/k8s/
openssl genrsa -out ca.key 2048
openssl req -new -x509 -key ca.key -out ca.crt -days 3650 -subj "/C=CN/ST=HB/L=WH/O=DM/OU=YPT/CN=CA"
openssl x509 -in ca.crt -noout -text
创建dashboard证书
openssl genrsa -out dashboard.key 2048
openssl req -new -sha256 -key dashboard.key -out dashboard.csr -subj "/C=CN/ST=HB/L=WH/O=DM/OU=YPT/CN=10.255.55.6"
#编辑文件
vim dashboard.cnf
----------------------------------------------------
extensions = san
[san]
keyUsage = digitalSignature
extendedKeyUsage = clientAuth,serverAuth
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
subjectAltName = IP:192.168.100.108,DNS:localhost #节点IP地址
-----------------------------------------------------
openssl x509 -req -sha256 -days 3650 -in dashboard.csr -out dashboard.crt -CA ca.crt -CAkey ca.key -CAcreateserial -extfile dashboard.cnf
openssl x509 -in dashboard.crt -noout -text
挂载证书到kubernetes-dashboard,创建dashboard服务
kubectl create namespace kubernetes-dashboard
kubectl create secret generic kubernetes-dashboard-certs --from-file="./dashboard.crt,./dashboard.key" -n kubernetes-dashboard
kubectl apply -f /root/dashboard.yaml
启用RBAC认证授权,此时通过https协议访问30001端口即可打开dashboard的控制台,为了保护数据安全性,集群默认开启了RBAC认证授权,需要授予权限的用户才可以访问到kubernetes集群,因此需要授权用户访问集群,集群中已定有了cluster-admin的角色和相关的Role,ClusterRole和ClusterRoleBinding角色,定义ServiceAccount将其关联即可,如下:
vim dashboard-rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: dashboard-admin
namespace: kubernetes-dashboard
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: dashboard-admin
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: dashboard-admin
namespace: kubernetes-dashboard
获取token
kubectl describe secret -n kubernetes-dashboard $(kubectl get secret -n kubernetes-dashboard | grep dashboard-admin| awk '{print $1}')
参考链接:
https://github.com/
https://www.cnblogs.com/zhaobin-diray/p/13724988.html
https://blog.csdn.net/qq_21127151/article/details/113874239