文章目录

  • 一、系统环境初始化
    • 1.1 k8s组件图
      • 1.1.1 Master组件
      • 1.1.2 Node组件
    • 1.2 生产环境可部署Kubernetes集群的两种方式
    • 1.3 安装要求
    • 1.4 环境准备
    • 1.5 操作系统初始化配置
      • 1.5.1 设置主机名
      • 1.5.2 设置hosts解析主机名
      • 1.5.3 关闭SELinux和防火墙
      • 1.5.4 关闭swap
      • 1.5.5 设置系统参数
      • 1.5.6 设置节点间的SSH免密码登录
      • 1.5.7 安装docker环境
  • 二、部署etcd集群
    • 2.1 准备cfssl证书生成工具
    • 2.2 生成Etcd证书
      • 2.2.1 自签证书颁发机构(CA)
      • 2.2.2 使用自签CA签发Etcd HTTPS证书
    • 2.3 从Github下载etcd二进制文件
    • 2.4 部署Etcd集群
      • 2.4.1 创建工作目录并解压二进制包
      • 2.4.2 创建etcd配置文件
      • 2.4.3 systemd管理etcd
      • 2.4.4 拷贝刚才生成的证书
      • 2.4.5 将上面节点1所有生成的文件拷贝到节点2和节点3
      • 2.4.6 启动etcd服务并设置开机启动
      • 2.4.7 查看集群状态
  • 三、部署Master Node
    • 3.1 生成kube-apiserver证书
      • 3.1.1 自签证书颁发机构(CA)
      • 3.2.2 使用自签CA签发kube-apiserver HTTPS证书
    • 3.2 从Github下载二进制文件
    • 3.3 解压二进制包
    • 3.4 部署kube-apiserver (master节点操作)
      • 3.4.1 创建配置文件
      • 3.4.2 拷贝刚才生成的证书
      • 3.4.3 创建上述配置文件中token文件:
      • 3.4.4 systemd管理apiserver
      • 3.4.5 启动并设置开机启动
      • 3.4.6 授权kubelet-bootstrap用户允许请求证书
    • 3.5 部署kube-controller-manager
      • 3.5.1 创建配置文件
      • 3.5.2 systemd管理controller-manager
      • 3.5.3 启动并设置开机启动
    • 3.6 部署kube-scheduler
      • 3.6.1 创建配置文件
      • 3.6.2 systemd管理scheduler
      • 3.6.3 启动并设置开机启动
      • 3.6.4 查看集群状态
  • 四、部署Worker Node
    • 4.1 创建工作目录并拷贝二进制文件
    • 4.2 部署kubelet
      • 4.2.1 创建配置文件
      • 4.2.2 配置参数文件
      • 4.2.3 生成bootstrap.kubeconfig文件
      • 4.2.4 systemd管理kubelet
      • 4.2.5 启动并设置开机启动
    • 4.3 批准kubelet证书申请并加入集群
    • 4.4 部署kube-proxy
      • 4.4.1 创建配置文件
      • 4.4.2 配置参数文件
      • 4.4.3 生成kube-proxy.kubeconfig文件
      • 4.4.4 systemd管理kube-proxy
      • 4.4.5 启动并设置开机启动
    • 4.5 部署CNI网络
      • 4.5.1 准备CNI二进制文件
      • 4.5.2 解压二进制包并移动到默认工作目录
      • 4.5.3 部署CNI网络
    • 4.6 授权apiserver访问kubelet
    • 4.7 新增加Worker Node
      • 4.7.1 拷贝已部署好的Node相关文件到新节点
      • 4.7.2 删除kubelet证书和kubeconfig文件
      • 4.7.3 修改主机名
      • 4.7.4 启动并设置开机启动
      • 4.7.5 在Master上批准新Node kubelet证书申请
      • 4.7.6 查看Node状态
  • 五、部署一个应用
    • 5.1 创建一个yaml文件存放目录
    • 5.2 编写deployment的yaml文件
    • 5.3 编写service的yaml文件
    • 5.4 生成应用pod容器
    • 5.5 生成应用service
    • 5.6 访问验证
  • 六、部署Dashboard和CoreDNS
    • 6.1 部署 Dashboard
      • 6.1.1 下载Dashboard的yaml文件
      • 6.1.2 部署Dashboard服务
      • 6.1.3 创建service account并绑定默认cluster-admin管理员集群角色
    • 6.2 部署CoreDNS
      • 6.2.1 生成CoreDNS的yaml文件
      • 6.2.2 部署coredns服务
      • 6.2.3 查看coredns服务是否成功创建
      • 6.2.4 DNS解析测试

一、系统环境初始化

1.1 k8s组件图

1.1.1 Master组件

  • kubectl

控制kubernetes集群

  • API Server

主要负责接收、校验并响应所有的REST请求,结果状态被持久存储在etcd当中,所有资源增删改查的唯一入口

  • Controller Manager

负责管理集群各种资源,保证资源处于预期的状态

  • Schedule

资源调度,负责决定将Pod放到哪个Node上运行

1.1.2 Node组件

  • kubelet

接收Schedule发送的node信息,根据信息创建和运行容器,并向master报告运行状态

  • Kube-proxy

负责将访问的service的数据请求转发到后端的pod容器

1.2 生产环境可部署Kubernetes集群的两种方式

目前生产部署Kubernetes集群主要有两种方式:

  • kubeadm

Kubeadm是一个K8s部署工具,提供kubeadm init和kubeadm join,用于快速部署Kubernetes集群。

官方地址:https://kubernetes.io/docs/reference/setup-tools/kubeadm/kubeadm/

  • 二进制包

从github下载发行版的二进制包,手动部署每个组件,组成Kubernetes集群。

Kubeadm降低部署门槛,但屏蔽了很多细节,遇到问题很难排查。如果想更容易可控,推荐使用二进制包部署Kubernetes集群,虽然手动部署麻烦点,期间可以学习很多工作原理,也利于后期维护。

1.3 安装要求

在开始之前,部署Kubernetes集群机器需要满足以下几个条件:

  • 一台或多台机器,操作系统 CentOS7.x-86_x64
  • 硬件配置:2GB或更多RAM,2个CPU或更多CPU,硬盘30GB或更多
  • 集群中所有机器之间网络互通
  • 可以访问外网,需要拉取镜像,如果服务器不能上网,需要提前下载镜像并导入节点
  • 禁止swap分区

1.4 环境准备

软件版本
操作系统CentOS Linux release 7.7.1611 (Core)
Docker19-ce
Kubernetes1.18

服务器整体规划:

角色IP组件
k8s-master10.20.17.20kube-apiserver,kube-controller-manager,kube-scheduler,etcd
k8s-node110.20.17.21kubelet,kube-proxy,docker etcd
k8s-node210.20.17.22kubelet,kube-proxy,docker,etcd

1.5 操作系统初始化配置

1.5.1 设置主机名

根据规划设置主机名 (所有节点)

hostnamectl set-hostname 

1.5.2 设置hosts解析主机名

设置/etc/hosts保证主机名能够解析 (所有节点)

# cat /etc/hosts10.20.17.20 k8s-master10.20.17.21 k8s-node110.20.17.22 k8s-node2

1.5.3 关闭SELinux和防火墙

所有节点

# 关闭防火墙systemctl disable firewalld永久systemctl stop firewalld 临时# 关闭selinuxsed -i 's/enforcing/disabled/' /etc/selinux/config# 永久setenforce 0# 临时

1.5.4 关闭swap

所有节点

swapoff -a# 临时sed -ri 's/.*swap.*/#&/' /etc/fstab# 永久

1.5.5 设置系统参数

将桥接的IPv4流量传递到iptables的链 (所有节点)

cat > /etc/sysctl.d/k8s.conf << EOFnet.bridge.bridge-nf-call-ip6tables = 1net.bridge.bridge-nf-call-iptables = 1EOFsysctl --system# 生效

1.5.6 设置节点间的SSH免密码登录

所有节点

ssh-keygen -t rsassh-copy-id k8s-masterssh-copy-id k8s-node1ssh-copy-id k8s-node2

1.5.7 安装docker环境

所有节点
可为docker设置一个阿里云镜像加速器

# cat /etc/docker/daemon.json{"registry-mirrors": ["https://zn14eon5.mirror.aliyuncs.com"]}

启动并设置开机启动

systemctl daemon-reloadsystemctl start dockersystemctl enable docker

注:注册阿里云账号,获取专属加速地址阿里云镜像仓库

二、部署etcd集群

Etcd 是一个分布式键值存储系统,Kubernetes使用Etcd进行数据存储,所以先准备一个Etcd数据库,为解决Etcd单点故障,应采用集群方式部署,这里使用3台组建集群,可容忍1台机器故障,当然,你也可以使用5台组建集群,可容忍2台机器故障。

节点名称IP
etcd-110.20.17.20
etcd-210.20.17.21
etcd-310.20.17.22

注:为了节省机器,这里与K8s节点机器复用。也可以独立于k8s集群之外部署,只要apiserver能连接到就行

2.1 准备cfssl证书生成工具

cfssl是一个开源的证书管理工具,使用json文件生成证书,相比openssl更方便使用。

找任意一台服务器操作,这里用Master节点。

mkdir -p /opt/toolsmkdir -p /opt/tools/cfsslcd /opt/tools/cfssl/wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64chmod +x cfssl_linux-amd64 cfssljson_linux-amd64 cfssl-certinfo_linux-amd64mv cfssl_linux-amd64 /usr/local/bin/cfsslmv cfssljson_linux-amd64 /usr/local/bin/cfssljsonmv cfssl-certinfo_linux-amd64 /usr/bin/cfssl-certinfo

2.2 生成Etcd证书

2.2.1 自签证书颁发机构(CA)

创建工作目录:

mkdir -p /root/TLS/{etcd,k8s}mkdir -p /root/TLS/{etcd,k8s}cd /root/TLS/etcd

自签CA:

cat > ca-config.json < 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 *pemca-key.pemca.pem

2.2.2 使用自签CA签发Etcd HTTPS证书

创建证书申请文件:

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 serverls server*pemserver-key.pemserver.pem

2.3 从Github下载etcd二进制文件

下载地址:https://github.com/etcd-io/etcd/releases/download/v3.4.9/etcd-v3.4.9-linux-amd64.tar.gz

2.4 部署Etcd集群

以下在etcd 节点1上操作,为简化操作,待会将节点1生成的所有文件拷贝到节点2和节点3。

2.4.1 创建工作目录并解压二进制包

mkdir -p /opt/etcd/{bin,cfg,ssl} tar zxvf /opt/tools/etcd-v3.4.9-linux-amd64.tar.gzmv /opt/tools/etcd-v3.4.9-linux-amd64/{etcd,etcdctl} /opt/etcd/bin/

2.4.2 创建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://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
  • ETCD_NAME:节点名称,集群中唯一
  • ETCD_DATA_DIR:数据目录
  • ETCD_LISTEN_PEER_URLS:集群通信监听地址
  • ETCD_LISTEN_CLIENT_URLS:客户端访问监听地址
  • ETCD_INITIAL_ADVERTISE_PEER_URLS:集群通告地址
  • ETCD_ADVERTISE_CLIENT_URLS:客户端通告地址
  • ETCD_INITIAL_CLUSTER:集群节点地址
  • ETCD_INITIAL_CLUSTER_TOKEN:集群Token
  • ETCD_INITIAL_CLUSTER_STATE:加入集群的当前状态,new是新集群,existing表示加入已有集群

2.4.3 systemd管理etcd

cat > /usr/lib/systemd/system/etcd.service << EOF[Unit]Description=Etcd ServerAfter=network.targetAfter=network-online.targetWants=network-online.target[Service]Type=notifyEnvironmentFile=/opt/etcd/cfg/etcd.confExecStart=/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=zapRestart=on-failureLimitNOFILE=65536[Install]WantedBy=multi-user.targetEOF

2.4.4 拷贝刚才生成的证书

# cp /root/TLS/etcd/ca*pem /root/TLS/etcd/server*pem /opt/etcd/ssl/

2.4.5 将上面节点1所有生成的文件拷贝到节点2和节点3

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-3ETCD_DATA_DIR="/var/lib/etcd/default.etcd"ETCD_LISTEN_PEER_URLS="https://10.20.17.20:2380"# 修改此处为当前服务器IPETCD_LISTEN_CLIENT_URLS="https://10.20.17.20:2379"# 修改此处为当前服务器IP#[Clustering]ETCD_INITIAL_ADVERTISE_PEER_URLS="https://10.20.17.20:2380"# 修改此处为当前服务器IPETCD_ADVERTISE_CLIENT_URLS="https://10.20.17.20:2379"# 修改此处为当前服务器IPETCD_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"

2.4.6 启动etcd服务并设置开机启动

systemctl daemon-reload# 配置生效systemctl start etcd # 启动etcdsystemctl 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。

2.4.7 查看集群状态

# 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 healthhttps://10.20.17.20:2379 is healthy: successfully committed proposal: took = 11.989312mshttps://10.20.17.21:2379 is healthy: successfully committed proposal: took = 12.942844mshttps://10.20.17.22:2379 is healthy: successfully committed proposal: took = 29.3212ms

如果输出上面信息,就说明集群部署成功。如果有问题第一步先看日志:/var/log/message 或 journalctl -u etcd

三、部署Master Node

3.1 生成kube-apiserver证书

注:master节点操作

3.1.1 自签证书颁发机构(CA)

# cd /root/TLS/k8s/cat > ca-config.json < 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 *pemca-key.pemca.pem

3.2.2 使用自签CA签发kube-apiserver HTTPS证书

创建证书申请文件:

# 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*pemserver-key.pemserver.pem

3.2 从Github下载二进制文件

下载地址: https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.18.md#v1183

注:打开链接你会发现里面有很多包,下载一个server包就够了,包含了Master和Worker Node二进制文件。

3.3 解压二进制包

注:master节点操作

mkdir -p /opt/kubernetes/{bin,cfg,ssl,logs} cd /opt/tools/tar zxvf kubernetes-server-linux-amd64.tar.gzcd kubernetes/server/bin/cp kube-apiserver kube-scheduler kube-controller-manager /opt/kubernetes/bicp kubectl /usr/bin/

3.4 部署kube-apiserver (master节点操作)

3.4.1 创建配置文件

cat > /opt/kubernetes/cfg/kube-apiserver.conf << EOFKUBE_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保留换行符。

  • –logtostderr:启用日志
  • —v:日志等级
  • –log-dir:日志目录
  • –etcd-servers:etcd集群地址
  • –bind-address:监听地址
  • –secure-port:https安全端口
  • –advertise-address:集群通告地址
  • –allow-privileged:启用授权
  • –service-cluster-ip-range:Service虚拟IP地址段
  • –enable-admission-plugins:准入控制模块
  • –authorization-mode:认证授权,启用RBAC授权和节点自管理
  • –enable-bootstrap-token-auth:启用TLS bootstrap机制
  • –token-auth-file:bootstrap token文件
  • –service-node-port-range:Service nodeport类型默认分配端口范围
  • –kubelet-client-xxx:apiserver访问kubelet客户端证书
  • –tls-xxx-file:apiserver https证书
  • –etcd-xxxfile:连接Etcd集群证书
  • –audit-log-xxx:审计日志

3.4.2 拷贝刚才生成的证书

把刚才生成的证书拷贝到配置文件中的路径:

cp /root/TLS/k8s/ca*pem /root/TLS/k8s/server*pem /opt/kubernetes/ssl/

3.4.3 创建上述配置文件中token文件:

生成token

head -c 16 /dev/urandom | od -An -t x | tr -d ' '

创建token文件:

cat > /opt/kubernetes/cfg/token.csv << EOF063e91e42837f2a2b36860457f515053,kubelet-bootstrap,10001,"system:node-bootstrapper"EOF

3.4.4 systemd管理apiserver

cat > /usr/lib/systemd/system/kube-apiserver.service << EOF[Unit]Description=Kubernetes API ServerDocumentation=https://github.com/kubernetes/kubernetes[Service]EnvironmentFile=/opt/kubernetes/cfg/kube-apiserver.confExecStart=/opt/kubernetes/bin/kube-apiserver \$KUBE_APISERVER_OPTSRestart=on-failure[Install]WantedBy=multi-user.targetEOF

3.4.5 启动并设置开机启动

systemctl daemon-reloadsystemctl start kube-apiserversystemctl enable kube-apiserver

3.4.6 授权kubelet-bootstrap用户允许请求证书

kubectl create clusterrolebinding kubelet-bootstrap \--clusterrole=system:node-bootstrapper \--user=kubelet-bootstrap

3.5 部署kube-controller-manager

注:master节点操作

3.5.1 创建配置文件

cat > /opt/kubernetes/cfg/kube-controller-manager.conf << EOFKUBE_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
  • –master:通过本地非安全本地端口8080连接apiserver。
  • –leader-elect:当该组件启动多个时,自动选举(HA)
  • –cluster-signing-cert-file/–cluster-signing-key-file:自动为kubelet颁发证书的CA,与apiserver保持一致

3.5.2 systemd管理controller-manager

cat > /usr/lib/systemd/system/kube-controller-manager.service << EOF[Unit]Description=Kubernetes Controller ManagerDocumentation=https://github.com/kubernetes/kubernetes[Service]EnvironmentFile=/opt/kubernetes/cfg/kube-controller-manager.confExecStart=/opt/kubernetes/bin/kube-controller-manager \$KUBE_CONTROLLER_MANAGER_OPTSRestart=on-failure[Install]WantedBy=multi-user.targetEOF

3.5.3 启动并设置开机启动

systemctl daemon-reloadsystemctl start kube-controller-managersystemctl enable kube-controller-manager

3.6 部署kube-scheduler

注:master节点操作

3.6.1 创建配置文件

cat > /opt/kubernetes/cfg/kube-scheduler.conf << EOFKUBE_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
  • –master:通过本地非安全本地端口8080连接apiserver。
  • –leader-elect:当该组件启动多个时,自动选举(HA)

3.6.2 systemd管理scheduler

cat > /usr/lib/systemd/system/kube-scheduler.service << EOF[Unit]Description=Kubernetes SchedulerDocumentation=https://github.com/kubernetes/kubernetes[Service]EnvironmentFile=/opt/kubernetes/cfg/kube-scheduler.confExecStart=/opt/kubernetes/bin/kube-scheduler \$KUBE_SCHEDULER_OPTSRestart=on-failure[Install]WantedBy=multi-user.targetEOF

3.6.3 启动并设置开机启动

systemctl daemon-reloadsystemctl start kube-schedulersystemctl enable kube-scheduler

3.6.4 查看集群状态

所有组件都已经启动成功,通过kubectl工具查看当前集群组件状态:

[root@k8s-master ~]# kubectl get csNAME STATUSMESSAGE ERRORschedulerHealthy okcontroller-manager Healthy oketcd-0 Healthy {"health":"true"} etcd-2 Healthy {"health":"true"} etcd-1 Healthy {"health":"true"} 

四、部署Worker Node

下面还是在Master Node上操作,即同时作为Worker Node

4.1 创建工作目录并拷贝二进制文件

在所有worker node创建工作目录: (node节点操作)

mkdir -p /opt/kubernetes/{bin,cfg,ssl,logs} 

从master节点拷贝:(master节点操作)

cd /opt/tools/kubernetes/server/bin/cp kubeletkube-proxy /opt/kubernetes/bin/scp kubeletkube-proxy k8s-node1:/opt/kubernetes/bin/scp kubeletkube-proxy k8s-node2:/opt/kubernetes/bin/

4.2 部署kubelet

注:master节点操作

4.2.1 创建配置文件

cat > /opt/kubernetes/cfg/kubelet.conf << EOFKUBELET_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
  • –hostname-override:显示名称,集群中唯一
  • –network-plugin:启用CNI
  • –kubeconfig:空路径,会自动生成,后面用于连接apiserver
  • –bootstrap-kubeconfig:首次启动向apiserver申请证书
  • –config:配置参数文件
  • –cert-dir:kubelet证书生成目录
  • –pod-infra-container-image:管理Pod网络容器的镜像

4.2.2 配置参数文件

cat > /opt/kubernetes/cfg/kubelet-config.yml << EOFkind: KubeletConfigurationapiVersion: kubelet.config.k8s.io/v1beta1address: 0.0.0.0port: 10250readOnlyPort: 10255cgroupDriver: cgroupfsclusterDNS:- 10.0.0.2clusterDomain: cluster.local failSwapOn: falseauthentication:anonymous:enabled: falsewebhook:cacheTTL: 2m0senabled: truex509:clientCAFile: /opt/kubernetes/ssl/ca.pem authorization:mode: Webhookwebhook:cacheAuthorizedTTL: 5m0scacheUnauthorizedTTL: 30sevictionHard:imagefs.available: 15%memory.available: 100Minodefs.available: 10%nodefs.inodesFree: 5%maxOpenFiles: 1000000maxPods: 110EOF

4.2.3 生成bootstrap.kubeconfig文件

KUBE_APISERVER="https://10.20.17.20:6443" # apiserver IP:PORTTOKEN="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.kubeconfigkubectl config set-credentials "kubelet-bootstrap" \--token=${TOKEN} \--kubeconfig=bootstrap.kubeconfigkubectl config set-context default \--cluster=kubernetes \--user="kubelet-bootstrap" \--kubeconfig=bootstrap.kubeconfigkubectl config use-context default --kubeconfig=bootstrap.kubeconfig

拷贝到配置文件路径:

cp /root/TLS/k8s/bootstrap.kubeconfig /opt/kubernetes/cfg

4.2.4 systemd管理kubelet

cat > /usr/lib/systemd/system/kubelet.service << EOF[Unit]Description=Kubernetes KubeletAfter=docker.service[Service]EnvironmentFile=/opt/kubernetes/cfg/kubelet.confExecStart=/opt/kubernetes/bin/kubelet \$KUBELET_OPTSRestart=on-failureLimitNOFILE=65536[Install]WantedBy=multi-user.targetEOF

4.2.5 启动并设置开机启动

systemctl daemon-reloadsystemctl start kubeletsystemctl enable kubelet

注:若无法启动,可通过查看系统日志排查问题原因:cat /var/log/messages

4.3 批准kubelet证书申请并加入集群

# 查看kubelet证书请求[root@k8s-master ~]# kubectl get csrNAME AGE SIGNERNAMEREQUESTOR CONDITIONnode-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 nodeNAME STATUS ROLESAGE VERSIONk8s-master NotReady  21s v1.18.3

注:由于网络插件还没有部署,节点会没有准备就绪 NotReady

4.4 部署kube-proxy

注:master节点操作

4.4.1 创建配置文件

cat > /opt/kubernetes/cfg/kube-proxy.conf << EOFKUBE_PROXY_OPTS="--logtostderr=false \\--v=2 \\--log-dir=/opt/kubernetes/logs \\--config=/opt/kubernetes/cfg/kube-proxy-config.yml"EOF

4.4.2 配置参数文件

cat > /opt/kubernetes/cfg/kube-proxy-config.yml << EOFkind: KubeProxyConfigurationapiVersion: kubeproxy.config.k8s.io/v1alpha1bindAddress: 0.0.0.0metricsBindAddress: 0.0.0.0:10249clientConnection:kubeconfig: /opt/kubernetes/cfg/kube-proxy.kubeconfighostnameOverride: k8s-masterclusterCIDR: 10.0.0.0/24EOF

4.4.3 生成kube-proxy.kubeconfig文件

生成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-proxyls kube-proxy*pemkube-proxy-key.pemkube-proxy.pem

生成kubeconfig文件:

KUBE_APISERVER="https://10.20.17.20:6443"cd /root/TLS/k8skubectl config set-cluster kubernetes \--certificate-authority=/opt/kubernetes/ssl/ca.pem \--embed-certs=true \--server=${KUBE_APISERVER} \--kubeconfig=kube-proxy.kubeconfigkubectl config set-credentials kube-proxy \--client-certificate=./kube-proxy.pem \--client-key=./kube-proxy-key.pem \--embed-certs=true \--kubeconfig=kube-proxy.kubeconfigkubectl config set-context default \--cluster=kubernetes \--user=kube-proxy \--kubeconfig=kube-proxy.kubeconfigkubectl config use-context default --kubeconfig=kube-proxy.kubeconfig

拷贝到配置文件指定路径:

cp /root/TLS/k8s/kube-proxy.kubeconfig /opt/kubernetes/cfg/

4.4.4 systemd管理kube-proxy

cat > /usr/lib/systemd/system/kube-proxy.service << EOF[Unit]Description=Kubernetes ProxyAfter=network.target[Service]EnvironmentFile=/opt/kubernetes/cfg/kube-proxy.confExecStart=/opt/kubernetes/bin/kube-proxy \$KUBE_PROXY_OPTSRestart=on-failureLimitNOFILE=65536[Install]WantedBy=multi-user.targetEOF

4.4.5 启动并设置开机启动

systemctl daemon-reloadsystemctl start kube-proxysystemctl enable kube-proxy

4.5 部署CNI网络

注:master节点操作

4.5.1 准备CNI二进制文件

下载地址:https://github.com/containernetworking/plugins/releases/download/v0.8.6/cni-plugins-linux-amd64-v0.8.6.tgz

4.5.2 解压二进制包并移动到默认工作目录

mkdir -p /opt/cni/bincd /opt/tools/tar zxvf cni-plugins-linux-amd64-v0.8.6.tgz -C /opt/cni/bin

4.5.3 部署CNI网络

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-systemNAMEREADY STATUSRESTARTS AGEkube-flannel-ds-amd64-c4t2v 1/1 Running 025s# kubectl get nodeNAME STATUS ROLESAGE VERSIONk8s-master Ready 36m v1.18.3

部署好网络插件,Node准备就绪。

4.6 授权apiserver访问kubelet

注:master节点操作

cat > apiserver-to-kubelet-rbac.yaml << EOFapiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata:annotations:rbac.authorization.kubernetes.io/autoupdate: "true"labels:kubernetes.io/bootstrapping: rbac-defaultsname: system:kube-apiserver-to-kubeletrules:- apiGroups:- ""resources:- nodes/proxy- nodes/stats- nodes/log- nodes/spec- nodes/metrics- pods/logverbs:- "*"---apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata:name: system:kube-apiservernamespace: ""roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: system:kube-apiserver-to-kubeletsubjects:- apiGroup: rbac.authorization.k8s.iokind: Username: kubernetesEOFkubectl apply -f apiserver-to-kubelet-rbac.yaml

4.7 新增加Worker Node

4.7.1 拷贝已部署好的Node相关文件到新节点

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/systemscp -r /opt/cni/ k8s-node1:/opt/scp /opt/kubernetes/ssl/ca.pem k8s-node1:/opt/kubernetes/ssl

4.7.2 删除kubelet证书和kubeconfig文件

node节点操作

rm /opt/kubernetes/cfg/kubelet.kubeconfig rm -f /opt/kubernetes/ssl/kubelet*

注:这几个文件是证书申请审批后自动生成的,每个Node不同,必须删除重新生成。

4.7.3 修改主机名

node节点操作

vim /opt/kubernetes/cfg/kubelet.conf--hostname-override=k8s-node1vim /opt/kubernetes/cfg/kube-proxy-config.ymlhostnameOverride: k8s-node1

4.7.4 启动并设置开机启动

node 节点操作

systemctl daemon-reloadsystemctl start kubeletsystemctl enable kubeletsystemctl start kube-proxysystemctl enable kube-proxy

4.7.5 在Master上批准新Node kubelet证书申请

master节点操作

# kubectl get csrNAME AGE SIGNERNAMEREQUESTOR CONDITIONnode-csr-LHEDjWtPT39E8gkKemznF7a5GgEfX4Y5Q34E-MgzJbw 68m kubernetes.io/kube-apiserver-client-kubelet kubelet-bootstrap Approved,Issuednode-csr-eFXMlBTEP1jYeRrMur_ZdpMeWyKmtyQ-A_LGOQZ74a0 57s kubernetes.io/kube-apiserver-client-kubelet kubelet-bootstrap Pendingkubectl certificate approve node-csr-eFXMlBTEP1jYeRrMur_ZdpMeWyKmtyQ-A_LGOQZ74a0

4.7.6 查看Node状态

master节点操作

[root@k8s-master ~]# kubectl get nodeNAME STATUS ROLESAGE VERSIONk8s-master Ready 60m v1.18.3k8s-node1Ready 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,同上操作即可,记得修改主机名!

五、部署一个应用

5.1 创建一个yaml文件存放目录

mkdir /opt/k8s-yaml

5.2 编写deployment的yaml文件

# cat test-sea-pc-qianduan-deployment.yamlapiVersion: apps/v1kind: Deploymentmetadata:labels:app: test-sea-pc-qianduanname: test-sea-pc-qianduan-deploymentspec:replicas: 1selector:matchLabels:app: test-sea-pc-qianduantemplate:metadata:labels:app: test-sea-pc-qianduanspec:containers:- image: test-sea-pc-qianduan:test01imagePullPolicy: Never#command: [ "/bin/bash", "-ce", "tail -f /dev/null" ]livenessProbe:initialDelaySeconds: 30periodSeconds: 30tcpSocket:port: 15190name: test-sea-pc-qianduanports:- containerPort: 15190readinessProbe:initialDelaySeconds: 30periodSeconds: 30tcpSocket:port: 15190volumeMounts:- mountPath: /etc/localtimename: host-time- mountPath: /opt/data/name: fileimagePullSecrets:- name: harbor-secretrestartPolicy: Alwaysvolumes:- hostPath:path: /etc/localtimename: host-time- hostPath:path: /opt/logs/gfs/test-sea/pc-qianduanname: file

5.3 编写service的yaml文件

# cat test-sea-pc-qianduan-service.yaml apiVersion: v1kind: Servicemetadata:name: test-sea-pc-qianduan-service-nodeportnamespace: defaultspec:clusterIP: 10.0.0.6ports:- name: httpnodePort: 25210port: 15190protocol: TCPtargetPort: 15190selector:app: test-sea-pc-qianduantype: NodePort

5.4 生成应用pod容器

# kubectl create -f test-sea-pc-qianduan-deployment.yamldeployment.apps/test-sea-pc-qianduan-deployment created# kubectl get podNAME READY STATUSRESTARTS AGEtest-sea-pc-qianduan-deployment-566b7697f9-4xxh2 1/1 Running 061s

5.5 生成应用service

# kubectl create -f test-sea-pc-qianduan-service.yamlservice/test-sea-pc-qianduan-service-nodeport created# kubectl get svcNAMETYPECLUSTER-IP EXTERNAL-IP PORT(S) AGEkubernetesClusterIP 10.0.0.1 443/TCP 3h42mtest-sea-pc-qianduan-service-nodeport NodePort10.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-apiserversystemctl restart kube-apiserver

5.6 访问验证

服务器测试:curl http://127.0.0.1:25210或在浏览器中测试:http://10.20.17.20:25210/

六、部署Dashboard和CoreDNS

6.1 部署 Dashboard

6.1.1 下载Dashboard的yaml文件

wget https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta8/aio/deploy/recommended.yaml

默认Dashboard只能集群内部访问,修改Service为NodePort类型,暴露到外部:

vim recommended.yamlkind: ServiceapiVersion: v1metadata:labels:k8s-app: kubernetes-dashboardname: kubernetes-dashboardnamespace: kubernetes-dashboardspec:ports: - port: 443 targetPort: 8443 nodePort: 30001type: NodePortselector:k8s-app: kubernetes-dashboard

6.1.2 部署Dashboard服务

# kubectl apply -f recommended.yaml
# kubectl get pods,svc -n kubernetes-dashboardNAME READY STATUSRESTARTS AGEpod/dashboard-metrics-scraper-694557449d-pzjvv 1/1 Running 020spod/kubernetes-dashboard-9774cc786-8mprh 1/1 Running 020sNAMETYPECLUSTER-IP EXTERNAL-IP PORT(S) AGEservice/dashboard-metrics-scraper ClusterIP 10.0.0.230 8000/TCP20sservice/kubernetes-dashboardNodePort10.0.0.24443:30001/TCP 20s

访问地址:https://NodeIP:30001

6.1.3 创建service account并绑定默认cluster-admin管理员集群角色

# 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。

6.2 部署CoreDNS

注:CoreDNS用于集群内部Service名称解析。

6.2.1 生成CoreDNS的yaml文件

mkdir /opt/tools/coredns &&cd /opt/tools/coredns/ wget https://raw.githubusercontent.com/coredns/deployment/master/kubernetes/coredns.yaml.sedwget https://raw.githubusercontent.com/coredns/deployment/master/kubernetes/deploy.shchmod +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

6.2.2 部署coredns服务

kubectl apply -f coredns.yml 

6.2.3 查看coredns服务是否成功创建

# kubectl get pods -n kube-system NAMEREADY STATUSRESTARTS AGEcoredns-6fdfb45d56-qv8hl1/1 Running 02m7skube-flannel-ds-amd64-bnbrf 1/1 Running 343hkube-flannel-ds-amd64-mtn2f 1/1 Running 244h

6.2.4 DNS解析测试

# kubectl run -it --rm dns-test --image=busybox:1.28.4 shIf you don't see a command prompt, try pressing enter./ # nslookup kubernetesServer:10.0.0.2Address 1: 10.0.0.2 kube-dns.kube-system.svc.cluster.localName:kubernetesAddress 1: 10.0.0.1 kubernetes.default.svc.cluster.local/ # nslookup www.baidu.comServer:10.0.0.2Address 1: 10.0.0.2 kube-dns.kube-system.svc.cluster.localName:www.baidu.comAddress 1: 240e:83:205:59:0:ff:b09b:159eAddress 2: 240e:83:205:58:0:ff:b09f:36bfAddress 3: 220.181.38.150Address 4: 220.181.38.149/ # nslookup www.zhihu.comServer:10.0.0.2Address 1: 10.0.0.2 kube-dns.kube-system.svc.cluster.localName:www.zhihu.comAddress 1: 42.81.85.241Address 2: 42.81.92.66Address 3: 42.81.92.60

解析没问题。