控制kubernetes集群
主要负责接收、校验并响应所有的REST请求,结果状态被持久存储在etcd当中,所有资源增删改查的唯一入口
负责管理集群各种资源,保证资源处于预期的状态
资源调度,负责决定将Pod放到哪个Node上运行
接收Schedule发送的node信息,根据信息创建和运行容器,并向master报告运行状态
负责将访问的service的数据请求转发到后端的pod容器
目前生产部署Kubernetes集群主要有两种方式:
Kubeadm是一个K8s部署工具,提供kubeadm init和kubeadm join,用于快速部署Kubernetes集群。
官方地址:https://kubernetes.io/docs/reference/setup-tools/kubeadm/kubeadm/
从github下载发行版的二进制包,手动部署每个组件,组成Kubernetes集群。
Kubeadm降低部署门槛,但屏蔽了很多细节,遇到问题很难排查。如果想更容易可控,推荐使用二进制包部署Kubernetes集群,虽然手动部署麻烦点,期间可以学习很多工作原理,也利于后期维护。
在开始之前,部署Kubernetes集群机器需要满足以下几个条件:
软件 | 版本 |
---|---|
操作系统 | CentOS Linux release 7.7.1611 (Core) |
Docker | 19-ce |
Kubernetes | 1.18 |
服务器整体规划:
角色 | IP | 组件 |
---|---|---|
k8s-master | 10.20.17.20 | kube-apiserver,kube-controller-manager,kube-scheduler,etcd |
k8s-node1 | 10.20.17.21 | kubelet,kube-proxy,docker etcd |
k8s-node2 | 10.20.17.22 | kubelet,kube-proxy,docker,etcd |
根据规划设置主机名 (所有节点)
hostnamectl set-hostname
设置/etc/hosts保证主机名能够解析 (所有节点)
# cat /etc/hosts
10.20.17.20 k8s-master
10.20.17.21 k8s-node1
10.20.17.22 k8s-node2
所有节点
# 关闭防火墙
systemctl disable firewalld 永久
systemctl stop firewalld 临时
# 关闭selinux
sed -i 's/enforcing/disabled/' /etc/selinux/config # 永久
setenforce 0 # 临时
所有节点
swapoff -a # 临时
sed -ri 's/.*swap.*/#&/' /etc/fstab # 永久
将桥接的IPv4流量传递到iptables的链 (所有节点)
cat > /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
EOF
sysctl --system # 生效
所有节点
ssh-keygen -t rsa
ssh-copy-id k8s-master
ssh-copy-id k8s-node1
ssh-copy-id k8s-node2
所有节点
可为docker设置一个阿里云镜像加速器
# cat /etc/docker/daemon.json
{
"registry-mirrors": ["https://zn14eon5.mirror.aliyuncs.com"]
}
启动并设置开机启动
systemctl daemon-reload
systemctl start docker
systemctl enable docker
注:注册阿里云账号,获取专属加速地址阿里云镜像仓库
Etcd 是一个分布式键值存储系统,Kubernetes使用Etcd进行数据存储,所以先准备一个Etcd数据库,为解决Etcd单点故障,应采用集群方式部署,这里使用3台组建集群,可容忍1台机器故障,当然,你也可以使用5台组建集群,可容忍2台机器故障。
节点名称 | IP |
---|---|
etcd-1 | 10.20.17.20 |
etcd-2 | 10.20.17.21 |
etcd-3 | 10.20.17.22 |
注:为了节省机器,这里与K8s节点机器复用。也可以独立于k8s集群之外部署,只要apiserver能连接到就行
cfssl是一个开源的证书管理工具,使用json文件生成证书,相比openssl更方便使用。
找任意一台服务器操作,这里用Master节点。
mkdir -p /opt/tools
mkdir -p /opt/tools/cfssl
cd /opt/tools/cfssl/
wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
chmod +x cfssl_linux-amd64 cfssljson_linux-amd64 cfssl-certinfo_linux-amd64
mv cfssl_linux-amd64 /usr/local/bin/cfssl
mv cfssljson_linux-amd64 /usr/local/bin/cfssljson
mv cfssl-certinfo_linux-amd64 /usr/bin/cfssl-certinfo
创建工作目录:
mkdir -p /root/TLS/{etcd,k8s}
mkdir -p /root/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": [
"10.20.17.20",
"10.20.17.21",
"10.20.17.22"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"L": "BeiJing",
"ST": "BeiJing"
}
]
}
EOF
注:上述文件hosts字段中IP为所有etcd节点的集群内部通信IP,一个都不能少!为了方便后期扩容可以多写几个预留的IP。
生成证书:
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
下载地址:https://github.com/etcd-io/etcd/releases/download/v3.4.9/etcd-v3.4.9-linux-amd64.tar.gz
以下在etcd 节点1上操作,为简化操作,待会将节点1生成的所有文件拷贝到节点2和节点3。
mkdir -p /opt/etcd/{bin,cfg,ssl}
tar zxvf /opt/tools/etcd-v3.4.9-linux-amd64.tar.gz
mv /opt/tools/etcd-v3.4.9-linux-amd64/{etcd,etcdctl} /opt/etcd/bin/
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://10.20.17.20:2380"
ETCD_LISTEN_CLIENT_URLS="https://10.20.17.20:2379"
#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://10.20.17.20:2380"
ETCD_ADVERTISE_CLIENT_URLS="https://10.20.17.20:2379"
ETCD_INITIAL_CLUSTER="etcd-1=https://10.20.17.20:2380,etcd-2=https://10.20.17.21:2380,etcd-3=https://10.20.17.22: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 /root/TLS/etcd/ca*pem /root/TLS/etcd/server*pem /opt/etcd/ssl/
scp -r /opt/etcd/ k8s-node1:/opt/
scp /usr/lib/systemd/system/etcd.service k8s-node1:/usr/lib/systemd/system/
scp -r /opt/etcd/ k8s-node2:/opt/
scp /usr/lib/systemd/system/etcd.service k8s-node2:/usr/lib/systemd/system/
然后在节点2和节点3分别修改etcd.conf配置文件中的节点名称和当前服务器IP:
[root@k8s-node1 bin]# vim /opt/etcd/cfg/etcd.conf
#[Member]
ETCD_NAME="etcd-1" # 修改此处,节点2改为etcd-2,节点3改为etcd-3
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="https://10.20.17.20:2380" # 修改此处为当前服务器IP
ETCD_LISTEN_CLIENT_URLS="https://10.20.17.20:2379" # 修改此处为当前服务器IP
#[Clustering]
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://10.20.17.20:2380" # 修改此处为当前服务器IP
ETCD_ADVERTISE_CLIENT_URLS="https://10.20.17.20:2379" # 修改此处为当前服务器IP
ETCD_INITIAL_CLUSTER="etcd-1=https://10.20.17.20:2380,etcd-2=https://10.20.17.21:2380,etcd-3=https://10.20.17.22:2380"
ETCD_INITIAL_CLUSTER_TOKEN="etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
systemctl daemon-reload # 配置生效
systemctl start etcd # 启动etcd
systemctl status etcd # 查看启动状态
systemctl enable etcd # 设置开机启动
注意:以上三个节点需要先启动其他节点的 etcd 而不是 master 的etcd !!!
启动master节点的etcd服务后,发现服务无法启动,可使用 journalctl -xe 命令或查看系统日志cat /var/log/messages
看到以下关于etcd的报错信息:
"msg":"prober detected unhealthy status","round-tripper-name":"ROUND_TRIPPER_RAFT_MESSAGE","remote-peer-id":"427a09770fe3b784","rtt":"0s","error":"dial tcp 10.20.17.21:2380: connect: connection refused"
报错原因:分析是因为etcd1的配置文件/etc/systemd/system/etcd.service 启动脚本中的ETCD_INITIAL_CLUSTER_STATE是new,而在配置中ETCD_INITIAL_CLUSTER写入了etcd2/3的IP:PORT,这时etcd1尝试去连接etcd2、etcd3,但是etcd2、3的etcd服务此时还未启动,因此需要先启动etcd2和3的etcd服务,再去启动etcd1。
# 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://10.20.17.2017.21:2379,https://10.20.17.22:2379" endpoint health
https://10.20.17.20:2379 is healthy: successfully committed proposal: took = 11.989312ms
https://10.20.17.21:2379 is healthy: successfully committed proposal: took = 12.942844ms
https://10.20.17.22:2379 is healthy: successfully committed proposal: took = 29.3212ms
如果输出上面信息,就说明集群部署成功。如果有问题第一步先看日志:/var/log/message 或 journalctl -u etcd
注:master节点操作
# cd /root/TLS/k8s/
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 -
ls *pem
ca-key.pem ca.pem
创建证书申请文件:
# cd /root/TLS/k8s/
cat > server-csr.json << EOF
{
"CN": "kubernetes",
"hosts": [
"10.0.0.1",
"127.0.0.1",
"10.20.17.20",
"10.20.17.21",
"10.20.17.22",
"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
注:上述文件hosts字段中IP为所有Master/LB/VIP IP,一个都不能少!为了方便后期扩容可以多写几个预留的IP。
生成证书:
# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes server-csr.json | cfssljson -bare server
# ls server*pem
server-key.pem server.pem
下载地址: https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.18.md#v1183
注:打开链接你会发现里面有很多包,下载一个server包就够了,包含了Master和Worker Node二进制文件。
注:master节点操作
mkdir -p /opt/kubernetes/{bin,cfg,ssl,logs}
cd /opt/tools/
tar zxvf kubernetes-server-linux-amd64.tar.gz
cd kubernetes/server/bin/
cp kube-apiserver kube-scheduler kube-controller-manager /opt/kubernetes/bi
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://10.20.17.20:2379,https://10.20.17.21:2379,https://10.20.17.22:2379 \\
--bind-address=10.20.17.20 \\
--secure-port=6443 \\
--advertise-address=10.20.17.20 \\
--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=1000-65535 \\
--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 /root/TLS/k8s/ca*pem /root/TLS/k8s/server*pem /opt/kubernetes/ssl/
生成token
head -c 16 /dev/urandom | od -An -t x | tr -d ' '
创建token文件:
cat > /opt/kubernetes/cfg/token.csv << EOF
063e91e42837f2a2b36860457f515053,kubelet-bootstrap,10001,"system:node-bootstrapper"
EOF
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 enable kube-apiserver
kubectl create clusterrolebinding kubelet-bootstrap \
--clusterrole=system:node-bootstrapper \
--user=kubelet-bootstrap
注:master节点操作
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
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
注:master节点操作
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
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
所有组件都已经启动成功,通过kubectl工具查看当前集群组件状态:
[root@k8s-master ~]# kubectl get cs
NAME STATUS MESSAGE ERROR
scheduler Healthy ok
controller-manager Healthy ok
etcd-0 Healthy {"health":"true"}
etcd-2 Healthy {"health":"true"}
etcd-1 Healthy {"health":"true"}
下面还是在Master Node上操作,即同时作为Worker Node
在所有worker node创建工作目录: (node节点操作)
mkdir -p /opt/kubernetes/{bin,cfg,ssl,logs}
从master节点拷贝:(master节点操作)
cd /opt/tools/kubernetes/server/bin/
cp kubelet kube-proxy /opt/kubernetes/bin/
scp kubelet kube-proxy k8s-node1:/opt/kubernetes/bin/
scp kubelet kube-proxy k8s-node2:/opt/kubernetes/bin/
注:master节点操作
cat > /opt/kubernetes/cfg/kubelet.conf << EOF
KUBELET_OPTS="--logtostderr=false \\
--v=2 \\
--log-dir=/opt/kubernetes/logs \\
--hostname-override=k8s-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=mirrorgooglecontainers/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
KUBE_APISERVER="https://10.20.17.20:6443" # apiserver IP:PORT
TOKEN="063e91e42837f2a2b36860457f515053" # 与token.csv里保持一致
cd /root/TLS/k8s
# 生成 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
拷贝到配置文件路径:
cp /root/TLS/k8s/bootstrap.kubeconfig /opt/kubernetes/cfg
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
注:若无法启动,可通过查看系统日志排查问题原因:cat /var/log/messages
# 查看kubelet证书请求
[root@k8s-master ~]# kubectl get csr
NAME AGE SIGNERNAME REQUESTOR CONDITION
node-csr-LHEDjWtPT39E8gkKemznF7a5GgEfX4Y5Q34E-MgzJbw 9m53s kubernetes.io/kube-apiserver-client-kubelet kubelet-bootstrap Pending
# 批准申请
kubectl certificate approve node-csr-LHEDjWtPT39E8gkKemznF7a5GgEfX4Y5Q34E-MgzJbw
# 查看节点
[root@k8s-master ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
k8s-master NotReady 21s v1.18.3
注:由于网络插件还没有部署,节点会没有准备就绪 NotReady
注:master节点操作
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
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: k8s-master
clusterCIDR: 10.0.0.0/24
EOF
生成kube-proxy证书:
# 切换工作目录
cd /root/TLS/k8s
# 创建证书请求文件
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
kube-proxy-key.pem kube-proxy.pem
生成kubeconfig文件:
KUBE_APISERVER="https://10.20.17.20:6443"
cd /root/TLS/k8s
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=./kube-proxy.pem \
--client-key=./kube-proxy-key.pem \
--embed-certs=true \
--kubeconfig=kube-proxy.kubeconfig
kubectl config set-context default \
--cluster=kubernetes \
--user=kube-proxy \
--kubeconfig=kube-proxy.kubeconfig
kubectl config use-context default --kubeconfig=kube-proxy.kubeconfig
拷贝到配置文件指定路径:
cp /root/TLS/k8s/kube-proxy.kubeconfig /opt/kubernetes/cfg/
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
注:master节点操作
下载地址:https://github.com/containernetworking/plugins/releases/download/v0.8.6/cni-plugins-linux-amd64-v0.8.6.tgz
mkdir -p /opt/cni/bin
cd /opt/tools/
tar zxvf cni-plugins-linux-amd64-v0.8.6.tgz -C /opt/cni/bin
wget https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
# 若默认镜像地址无法访问,修改为docker hub镜像仓库。此处我们不进行修改
sed -i -r "s#quay.io/coreos/flannel:.*-amd64#lizhenliang/flannel:v0.12.0-amd64#g" kube-flannel.yml
生成flannel网络容器:
# kubectl apply -f kube-flannel.yml
# kubectl get pods -n kube-system
NAME READY STATUS RESTARTS AGE
kube-flannel-ds-amd64-c4t2v 1/1 Running 0 25s
# kubectl get node
NAME STATUS ROLES AGE VERSION
k8s-master Ready 36m v1.18.3
部署好网络插件,Node准备就绪。
注:master节点操作
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
kubectl apply -f apiserver-to-kubelet-rbac.yaml
master节点操作
在master节点将Worker Node涉及文件拷贝到新节点:node1 、node2
scp -r /opt/kubernetes k8s-node1:/opt/
scp -r /usr/lib/systemd/system/{kubelet,kube-proxy}.service k8s-node1:/usr/lib/systemd/system
scp -r /opt/cni/ k8s-node1:/opt/
scp /opt/kubernetes/ssl/ca.pem k8s-node1:/opt/kubernetes/ssl
node节点操作
rm /opt/kubernetes/cfg/kubelet.kubeconfig
rm -f /opt/kubernetes/ssl/kubelet*
注:这几个文件是证书申请审批后自动生成的,每个Node不同,必须删除重新生成。
node节点操作
vim /opt/kubernetes/cfg/kubelet.conf
--hostname-override=k8s-node1
vim /opt/kubernetes/cfg/kube-proxy-config.yml
hostnameOverride: k8s-node1
node 节点操作
systemctl daemon-reload
systemctl start kubelet
systemctl enable kubelet
systemctl start kube-proxy
systemctl enable kube-proxy
master节点操作
# kubectl get csr
NAME AGE SIGNERNAME REQUESTOR CONDITION
node-csr-LHEDjWtPT39E8gkKemznF7a5GgEfX4Y5Q34E-MgzJbw 68m kubernetes.io/kube-apiserver-client-kubelet kubelet-bootstrap Approved,Issued
node-csr-eFXMlBTEP1jYeRrMur_ZdpMeWyKmtyQ-A_LGOQZ74a0 57s kubernetes.io/kube-apiserver-client-kubelet kubelet-bootstrap Pending
kubectl certificate approve node-csr-eFXMlBTEP1jYeRrMur_ZdpMeWyKmtyQ-A_LGOQZ74a0
master节点操作
[root@k8s-master ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
k8s-master Ready 60m v1.18.3
k8s-node1 Ready 62s v1.18.3
注:若新加的节点状态为NotReady时,可使用journalctl -f -u kubelet 检查问题,若为以下报错:
Container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:docker: network plugin is not ready: cni config uninitialized
此问题为网络插件没有准备好,我们可以执行命令docker images|grep flannel来查看flannel镜像是否已经成功拉取下来.经过排查,flannel镜像拉取的有点慢,稍等一会以后就可以了,或者手动执行命令下载镜像:docker pull quay.io/coreos/flannel:v0.12.0-amd64
若需要继续添加node节点2,同上操作即可,记得修改主机名!
mkdir /opt/k8s-yaml
# cat test-sea-pc-qianduan-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: test-sea-pc-qianduan
name: test-sea-pc-qianduan-deployment
spec:
replicas: 1
selector:
matchLabels:
app: test-sea-pc-qianduan
template:
metadata:
labels:
app: test-sea-pc-qianduan
spec:
containers:
- image: test-sea-pc-qianduan:test01
imagePullPolicy: Never
#command: [ "/bin/bash", "-ce", "tail -f /dev/null" ]
livenessProbe:
initialDelaySeconds: 30
periodSeconds: 30
tcpSocket:
port: 15190
name: test-sea-pc-qianduan
ports:
- containerPort: 15190
readinessProbe:
initialDelaySeconds: 30
periodSeconds: 30
tcpSocket:
port: 15190
volumeMounts:
- mountPath: /etc/localtime
name: host-time
- mountPath: /opt/data/
name: file
imagePullSecrets:
- name: harbor-secret
restartPolicy: Always
volumes:
- hostPath:
path: /etc/localtime
name: host-time
- hostPath:
path: /opt/logs/gfs/test-sea/pc-qianduan
name: file
# cat test-sea-pc-qianduan-service.yaml
apiVersion: v1
kind: Service
metadata:
name: test-sea-pc-qianduan-service-nodeport
namespace: default
spec:
clusterIP: 10.0.0.6
ports:
- name: http
nodePort: 25210
port: 15190
protocol: TCP
targetPort: 15190
selector:
app: test-sea-pc-qianduan
type: NodePort
# kubectl create -f test-sea-pc-qianduan-deployment.yaml
deployment.apps/test-sea-pc-qianduan-deployment created
# kubectl get pod
NAME READY STATUS RESTARTS AGE
test-sea-pc-qianduan-deployment-566b7697f9-4xxh2 1/1 Running 0 61s
# kubectl create -f test-sea-pc-qianduan-service.yaml
service/test-sea-pc-qianduan-service-nodeport created
# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.0.0.1 443/TCP 3h42m
test-sea-pc-qianduan-service-nodeport NodePort 10.0.0.6 15190:25210/TCP 17s
注:启动漫service时若报错:
The Service "test-sea-pc-qianduan-service-nodeport" is invalid: spec.ports[0].nodePort: Invalid value: 25210: provided port is not in the valid range. The range of valid ports is 30000-32767
解决方法 : 编辑 kube-apiserver.yaml文件
vim /opt/kubernetes/cfg/kube-apiserver.conf
找到 --service-cluster-ip-range 这一行,在这一行的下一行修改 如下内容
--service-node-port-range=1-65535
重启kube-apiserver
systemctl restart kube-apiserver
服务器测试:
curl http://127.0.0.1:25210
或在浏览器中测试:
http://10.20.17.20:25210/
wget https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta8/aio/deploy/recommended.yaml
默认Dashboard只能集群内部访问,修改Service为NodePort类型,暴露到外部:
vim recommended.yaml
kind: Service
apiVersion: v1
metadata:
labels:
k8s-app: kubernetes-dashboard
name: kubernetes-dashboard
namespace: kubernetes-dashboard
spec:
ports:
- port: 443
targetPort: 8443
nodePort: 30001
type: NodePort
selector:
k8s-app: kubernetes-dashboard
# kubectl apply -f recommended.yaml
# kubectl get pods,svc -n kubernetes-dashboard
NAME READY STATUS RESTARTS AGE
pod/dashboard-metrics-scraper-694557449d-pzjvv 1/1 Running 0 20s
pod/kubernetes-dashboard-9774cc786-8mprh 1/1 Running 0 20s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/dashboard-metrics-scraper ClusterIP 10.0.0.230 8000/TCP 20s
service/kubernetes-dashboard NodePort 10.0.0.24 443:30001/TCP 20s
访问地址:https://NodeIP:30001
# kubectl create serviceaccount dashboard-admin -n kube-system
# kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin
# kubectl describe secrets -n kube-system $(kubectl -n kube-system get secret | awk '/dashboard-admin/{print $1}')
使用输出的token登录Dashboard。
注:CoreDNS用于集群内部Service名称解析。
mkdir /opt/tools/coredns && cd /opt/tools/coredns/
wget https://raw.githubusercontent.com/coredns/deployment/master/kubernetes/coredns.yaml.sed
wget https://raw.githubusercontent.com/coredns/deployment/master/kubernetes/deploy.sh
chmod +x deploy.sh
./deploy.sh -i 10.0.0.2 > coredns.yml
注:10.0.0.2应该是k8s集群中pod地址段中的IP
注:生成CoreDNS的yaml文件需要jq命令
CentOS7安装 jq
#安装EPEL源:
yum install epel-release
#安装jq:
yum install jq
kubectl apply -f coredns.yml
# kubectl get pods -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-6fdfb45d56-qv8hl 1/1 Running 0 2m7s
kube-flannel-ds-amd64-bnbrf 1/1 Running 3 43h
kube-flannel-ds-amd64-mtn2f 1/1 Running 2 44h
# kubectl run -it --rm dns-test --image=busybox:1.28.4 sh
If you don't see a command prompt, try pressing enter.
/ # nslookup kubernetes
Server: 10.0.0.2
Address 1: 10.0.0.2 kube-dns.kube-system.svc.cluster.local
Name: kubernetes
Address 1: 10.0.0.1 kubernetes.default.svc.cluster.local
/ # nslookup www.baidu.com
Server: 10.0.0.2
Address 1: 10.0.0.2 kube-dns.kube-system.svc.cluster.local
Name: www.baidu.com
Address 1: 240e:83:205:59:0:ff:b09b:159e
Address 2: 240e:83:205:58:0:ff:b09f:36bf
Address 3: 220.181.38.150
Address 4: 220.181.38.149
/ # nslookup www.zhihu.com
Server: 10.0.0.2
Address 1: 10.0.0.2 kube-dns.kube-system.svc.cluster.local
Name: www.zhihu.com
Address 1: 42.81.85.241
Address 2: 42.81.92.66
Address 3: 42.81.92.60
解析没问题。