《第一篇》二进制部署高可用K8S集群v1.24.2及运维(亲测无坑)

1. 致谢

这篇文章参考了B站/CSDN/博客园等大神们的无私分享,在此表示感谢和致敬!
备注:请严格按照安装顺利执行,执行顺序不一致会出现各种异常~

2. 安装CentOS操作系统

模拟器:VMware-workstation-full-14.1.3-9474260 (单台笔记本 4C/16G/512G)
系统镜像:CentOS-7-x86_64-DVD-2009.iso 安装过程略~

3. 环境准备

在这里插入图片描述

K8S集群组件规划:

主机名IP地址角色系统硬件组件
master_vip10.0.0.8--ETCD版本(v3.5.4)
YonXin-SIT-Master0110.0.0.1etcd,master,ingress,dnsCentOS7.9内核5.6.42C4GDNS/Keepalived/ipvs/haproxy/kube-apiserver/kube-scheduler/kube-controller-manager/kubelet/kube-proxy/etcd/docker/containerd/runc
YonXin-SIT-Master0210.0.0.2etcd,master,ingressCentOS7.9内核5.6.42C4GKeepalived/ipvs/haproxy/kube-apiserver/kube-scheduler/kube-controller-manager/kubelet/kube-proxy/etcd/docker/containerd/runc
YonXin-SIT-Node0110.0.0.3etcd,node,harborCentOS7.9内核5.6.42C2Gkubelet/kube-proxy/etcd/docker/containerd/runc/ipvs/harbor
YonXin-SIT-Node0210.0.0.4node,nginxCentOS7.9内核5.6.42C2GKubelet/Kube-proxy/docker/containerd/runc/ipvs/nginx

K8S集群网段规划:

主机网段Docker网段cluster-ip网段calico网段
10.0.0.0/24172.17.0.1/1610.96.0.0/1610.244.0.0/16

3.1 主机名和IP地址配置

主机名以YonXin-SIT-Master01为例:

[root@server ~]# hostnamectl --static set-hostname  "YonXin-SIT-Master01"
[root@server ~]# echo "10.0.0.1 YonXin-SIT-Master01 YonXin-SIT-Master01.hostname.com" >> /etc/hosts

IP地址以YonXin-SIT-Master01为例:

[root@YonXin-SIT-Master01 ~]# systemctl disable NetworkManager && service NetworkManager stop
[root@YonXin-SIT-Master01 ~]# vi  /etc/sysconfig/network-scripts/ifcfg-bond0  #创建主备模式bond0接口
TYPE=Ethernet
DEVICE=bond0
ONBOOT=yes
BOOTPROTO=static
IPADDR=10.0.0.1
NETMASK=255.255.255.0
GATEWAY=10.0.0.254
BONDING_OPTS="mode=1 miimon=100"

[root@YonXin-SIT-Master01 ~]# vi  /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
DEVICE=ens33
NAME=ens33
ONBOOT=yes
BOOTPROTO=none
MASTER=bond0
SLAVE=yes
NM_CONTROLLED=no

[root@YonXin-SIT-Master01 ~]# service network restart           #重启网络状态

3.2 操作系统初始化

(1) 在YonXin-SIT-Master01上启用tomcat8服务
下载tomcat服务包安装并启动,下载初始化文件包放入tomcat的webapps目录解压~

Java8 百度网盘下载链接:https://pan.baidu.com/s/10fGFaP-hZq0fXJt3Z7a_Gw 提取码:6zu9
Tomcat8 百度网盘下载链接:https://pan.baidu.com/s/1ljnnXtcrndAxAF0L35qvyA 提取码:9qmc
初始化文件包百度网盘下载链接:https://pan.baidu.com/s/1O4VOHxSS5ZF8M9Ec32_dCg 提取码:d5hp

[root@YonXin-SIT-Master01 ~]# tar zxf Yonxin-oracle-jdk8-data.tar.gz
[root@YonXin-SIT-Master01 ~]# cd Yonxin-oracle-jdk8-data && ./install_jdk8.sh
[root@YonXin-SIT-Master01 ~]# tar zxf Yonxin-tomcat-8.5.59-data.tar.gz
[root@YonXin-SIT-Master01 ~]# cd Yonxin-tomcat-8.5.59-data && ./install_tomcat.sh
[root@YonXin-SIT-Master01 ~]# cd /data/download/ && unzip init-centos7-file.zip

(2) 所有服务器执行初始化脚本

[root@server ~]# vim /etc/resolv.conf
# Generated by NetworkManager
search hostname.com
nameserver 10.0.0.1
[root@server ~]# vim ~/init-centos7.sh
#!/usr/bin/bash
red_col="\e[1;31m"
green_col="\e[1;32m"
blue_col="\e[1;34m"
reset_col="\e[0m"
CURRENT_DIR=$(cd $(dirname $0); pwd)
AZQ_IP='10.0.0.1'
AZQ_PORT='8080'
IP_ADDR=`ip add |grep -Ev "lo:|docker|br-|veth|tun|cali" |grep 'inet ' |grep -Ev "127.0.0.1|/32" |awk '{print $2}' |awk -F'/' '{print $1}'`
##################################################################################################
use_root() {
  #(0)使用root账号执行脚本
  if [ $USER != "root" ];then
  	echo -e "$red_col     请使用root用户执行环境检查清单脚本 $reset_col"
  	exit 0
  else
    yum install -y vim lrzsz curl htop wget unzip lsof yum-utils sshpass >/dev/null 2>&1
    wget http://mirrors.aliyun.com/repo/Centos-7.repo  -O /etc/yum.repos.d/CentOS-Base.repo >/dev/null 2>&1
    wget http://mirrors.aliyun.com/repo/epel-7.repo  -O /etc/yum.repos.d/epel.repo >/dev/null 2>&1
  fi
}

set_hostname() {
  #(1)设置服务器主机名
  echo -ne "$blue_col(1)是否需要本工具来为您设置主机名[yes/no]:$reset_col"
  while read ooo
  do
  	if [ "$ooo" == "y" -o "$ooo" == "Y" -o "$ooo" == "yes" ];then
  		echo -ne "$blue_col     请输入该主机规划的主机名(安装器主机请直接enter,使用installer名字)$reset_col"
  		read host_name
  		host_name=${host_name:-installer.hostname.com}
  		hostnamectl --static set-hostname $host_name
  		if [ `grep -c ${host_name} /etc/hosts` = "0" ];then
  		    echo "${IP_ADDR}   ${host_name}" >> /etc/hosts
  		fi
		echo -e "$green_col     服务器名称设置完成! $reset_col"
  		break
  	elif [ "$ooo" == "n" -o "$ooo" == "N" -o "$ooo" == "no" ];then
	    echo -e "$green_col     不进行服务器名称设置! $reset_col"
  		break
  	else
  		echo -e "$red_col     输入错误,请重新输入$reset_col"
  		echo -ne "$blue_col     是否需要本工具来为您设置主机名[yes/no]: $reset_col"
  	fi
  done
}

set_ssh() {
  #(2)优化SSH登录
  echo -e "$blue_col(2)优化SSH登录$reset_col"
  if ! grep '^ *StrictHostKeyChecking no' /etc/ssh/ssh_config &> /dev/null
  then
    sed -ri '$a StrictHostKeyChecking no' /etc/ssh/ssh_config
  fi
  sed -ri 's/^[ \t]*#[ \t]*UseDNS.*yes/UseDNS no/' /etc/ssh/sshd_config
  sed -ri 's/^[ \t]*GSSAPIAuthentication.*/GSSAPIAuthentication no/' /etc/ssh/sshd_config
  echo -e "$green_col     优化SSH登录完成! $reset_col"
  systemctl restart sshd
}

set_sysctl() {
  #(3)系统参数优化
  echo -e "$blue_col(3)系统参数优化$reset_col"
  if [ `grep -c '* soft nproc 65535' /etc/security/limits.conf` = "0" ];then
  	echo '* soft nproc 65535' >> /etc/security/limits.conf
  fi
  if [ `grep -c '* hard nproc 65535' /etc/security/limits.conf` = "0" ];then
  	echo '* hard nproc 65535' >> /etc/security/limits.conf
  fi
  if [ `grep -c '* soft nofile 204800' /etc/security/limits.conf` = "0" ];then
  	echo '* soft nofile 204800' >> /etc/security/limits.conf
  fi
  if [ `grep -c '* hard nofile 204800' /etc/security/limits.conf` = "0" ];then
  	echo '* hard nofile 204800' >> /etc/security/limits.conf
  fi
  if [ `grep -c '* soft memlock unlimited' /etc/security/limits.conf` = "0" ];then
  	echo '* soft memlock unlimited' >> /etc/security/limits.conf
  fi
  if [ `grep -c '* hard memlock unlimited' /etc/security/limits.conf` = "0" ];then
  	echo '* hard memlock unlimited' >> /etc/security/limits.conf
  fi
  ulimit -SHn 204800
  ulimit -SHu 65535
  if [ `grep -c 'kernel.sysrq = 0' /etc/sysctl.conf` = "0" ];then
  	echo '#关闭sysrq功能' >> /etc/sysctl.conf
  	echo 'kernel.sysrq = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'kernel.core_uses_pid = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#core文件名中添加pid作为扩展名' >> /etc/sysctl.conf
  	echo 'kernel.core_uses_pid = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'kernel.msgmnb = 65536' /etc/sysctl.conf` = "0" ];then
  	echo '#修改消息队列长度' >> /etc/sysctl.conf
  	echo 'kernel.msgmnb = 65536' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'kernel.msgmax = 65536' /etc/sysctl.conf` = "0" ];then
  	echo 'kernel.msgmax = 65536' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'kernel.shmmax = 68719476736' /etc/sysctl.conf` = "0" ];then
  	echo '#设置最大内存共享段大小bytes' >> /etc/sysctl.conf
  	echo 'kernel.shmmax = 68719476736' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'kernel.shmall = 4294967296' /etc/sysctl.conf` = "0" ];then
  	echo 'kernel.shmall = 4294967296' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'vm.swappiness = 10' /etc/sysctl.conf` = "0" ];then
  	echo '#swap缓存' >> /etc/sysctl.conf
  	echo 'vm.swappiness = 10' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'vm.max_map_count = 655365' /etc/sysctl.conf` = "0" ];then
  	echo 'vm.max_map_count = 655365' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'fs.inotify.max_user_watches = 8192000' /etc/sysctl.conf` = "0" ];then
  	echo '#修改最大文件同步数默认为8192' >> /etc/sysctl.conf
  	echo 'fs.inotify.max_user_watches = 8192000' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.core.netdev_max_backlog = 262144' /etc/sysctl.conf` = "0" ];then
  	echo '#每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目' >> /etc/sysctl.conf
  	echo 'net.core.netdev_max_backlog = 262144' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.core.somaxconn = 65535' /etc/sysctl.conf` = "0" ];then
  	echo '#listen挂起请求的最大数量,默认128' >> /etc/sysctl.conf
  	echo 'net.core.somaxconn = 65535' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.core.rps_sock_flow_entries = 65535' /etc/sysctl.conf` = "0" ];then
  	echo 'net.core.rps_sock_flow_entries = 65535' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.core.wmem_default = 8388608' /etc/sysctl.conf` = "0" ];then
  	echo 'net.core.wmem_default = 8388608' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.core.rmem_max = 16777216' /etc/sysctl.conf` = "0" ];then
  	echo 'net.core.rmem_max = 16777216' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.core.wmem_max = 16777216' /etc/sysctl.conf` = "0" ];then
  	echo 'net.core.wmem_max = 16777216' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ip_forward = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#开启内核转发' >> /etc/sysctl.conf
  	echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ip_default_ttl = 64' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.ip_default_ttl = 64' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.all.send_redirects = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.conf.all.send_redirects = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.default.send_redirects = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.conf.default.send_redirects = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.all.rp_filter = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#开启反向路径过滤' >> /etc/sysctl.conf
  	echo 'net.ipv4.conf.all.rp_filter = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.default.rp_filter = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.conf.default.rp_filter = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.inet_peer_maxttl = 600' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.inet_peer_maxttl = 600' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.inet_peer_minttl = 120' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.inet_peer_minttl = 120' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.inet_peer_threshold = 65664' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.inet_peer_threshold = 65664' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.all.accept_source_route = 0' /etc/sysctl.conf` = "0" ];then
  	echo '#处理无源路由的包' >> /etc/sysctl.conf
  	echo 'net.ipv4.conf.all.accept_source_route = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.all.accept_redirects=0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.conf.all.accept_redirects=0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.default.accept_source_route = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.conf.default.accept_source_route = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.conf.all.arp_ignore = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#只回答目标IP地址是来访网络接口本地地址的ARP查询请求' >> /etc/sysctl.conf
  	echo 'net.ipv4.conf.all.arp_ignore = 1' >> /etc/sysctl.conf
    echo "1" > /proc/sys/net/ipv4/conf/all/arp_ignore
  fi
  if [ `grep -c 'net.ipv4.conf.all.arp_announce = 2' /etc/sysctl.conf` = "0" ];then
  	echo '#对网络接口上本地IP地址发出的ARP回应' >> /etc/sysctl.conf
  	echo 'net.ipv4.conf.all.arp_announce = 2' >> /etc/sysctl.conf
    echo "2" > /proc/sys/net/ipv4/conf/all/arp_announce
  fi
  if [ `grep -c 'net.ipv4.conf.all.force_igmp_version = 2' /etc/sysctl.conf` = "0" ];then
  	echo '#更改IGMP版本为V2' >> /etc/sysctl.conf
  	echo 'net.ipv4.conf.all.force_igmp_version = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.cipso_cache_bucket_size = 10' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.cipso_cache_bucket_size = 10' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.cipso_cache_enable = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.cipso_cache_enable = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.cipso_rbm_optfmt = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.cipso_rbm_optfmt = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.cipso_rbm_strictvalid = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.cipso_rbm_strictvalid = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_max_tw_buckets = 6000' /etc/sysctl.conf` = "0" ];then
  	echo '#timewait的数量,默认180000' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_max_tw_buckets = 6000' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_moderate_rcvbuf = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_moderate_rcvbuf = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_mtu_probing = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_mtu_probing = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_no_metrics_save = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_no_metrics_save = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_orphan_retries = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_orphan_retries = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_reordering = 3' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_reordering = 3' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_retrans_collapse = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_retrans_collapse = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_retries1 = 2' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_retries1 = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_retries2 = 2' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_retries2 = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_rfc1337 = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_rfc1337 = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_sack = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_sack = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_slow_start_after_idle = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_slow_start_after_idle = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_stdurg = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_stdurg = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ip_local_port_range = 1024    65000' /etc/sysctl.conf` = "0" ];then
  	echo '#允许系统打开的端口范围' >> /etc/sysctl.conf
  	echo 'net.ipv4.ip_local_port_range = 1024    65000' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ip_nonlocal_bind = 0' /etc/sysctl.conf` = "0" ];then
  	echo '#开启允许绑定非本机的IP' >> /etc/sysctl.conf
  	echo 'net.ipv4.ip_nonlocal_bind = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ip_no_pmtu_disc = 0' /etc/sysctl.conf` = "0" ];then
  	echo '#系统能创建的最大tcp连接数' >> /etc/sysctl.conf
  	echo 'net.ipv4.ip_no_pmtu_disc = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_abort_on_overflow = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_abort_on_overflow = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_adv_win_scale = 2' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_adv_win_scale = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_app_win = 31' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_app_win = 31' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_base_mss = 1024' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_base_mss = 1024' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_dsack = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_dsack = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_ecn = 2' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_ecn = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_fack = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_fack = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_frto = 2' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_frto = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_low_latency = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_low_latency = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_tw_recycle = 0' /etc/sysctl.conf` = "0" ];then
  	echo '#启用timewait 快速回收' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_tw_recycle = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_tw_reuse = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#开启重用,允许将TIME-WAIT sockets 重新用于新的TCP 连接' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_tw_reuse = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_syncookies = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#开启SYN洪水攻击保护' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_syncookies = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_max_orphans = 2000' /etc/sysctl.conf` = "0" ];then
  	echo '#限制仅仅是为了防止简单的DoS 攻击' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_max_orphans = 2000' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_max_ssthresh = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_max_ssthresh = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_max_syn_backlog = 128' /etc/sysctl.conf` = "0" ];then
  	echo '#未收到客户端确认信息的连接请求的最大值' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_max_syn_backlog = 128' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_timestamps = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#时间戳可以避免序列号的卷绕,一个1Gbps的链路肯定会遇到以前用过的序列号,时间戳能够让内核接受这种“异常”的数据包' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_timestamps = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_tso_win_divisor = 3' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_tso_win_divisor = 3' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_synack_retries = 2' /etc/sysctl.conf` = "0" ];then
  	echo '#内核放弃建立连接之前发送SYNACK 包的数量' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_synack_retries = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_syn_retries = 2' /etc/sysctl.conf` = "0" ];then
  	echo '#内核放弃建立连接之前发送SYN 包的数量' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_syn_retries = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_thin_dupack = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_thin_dupack = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_thin_linear_timeouts = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_thin_linear_timeouts = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_fin_timeout = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#保持在FIN-WAIT-2状态的时间' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_fin_timeout = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_keepalive_time = 2' /etc/sysctl.conf` = "0" ];then
  	echo '#当keepalive起用的时候,TCP发送keepalive消息的频度,缺省是2小时' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_keepalive_time = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_keepalive_intvl = 2' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_keepalive_intvl = 2' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_keepalive_probes = 3' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_keepalive_probes = 3' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ipfrag_high_thresh = 262144' /etc/sysctl.conf` = "0" ];then
  	echo '#IP分片' >> /etc/sysctl.conf
  	echo 'net.ipv4.ipfrag_high_thresh = 262144' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ipfrag_low_thresh = 196608' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.ipfrag_low_thresh = 196608' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ipfrag_max_dist = 64' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.ipfrag_max_dist = 64' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ipfrag_secret_interval = 600' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.ipfrag_secret_interval = 600' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.ipfrag_time = 30' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.ipfrag_time = 30' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_sack = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#关闭tcp_sack, 通过有选择地应答乱序接收到的报文来提高性能' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_sack = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_window_scaling = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_window_scaling = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_workaround_signed_windows = 0' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_workaround_signed_windows = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_rmem = 4096 8388608 16777216' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_rmem = 4096 8388608 16777216' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_wmem = 4096 8388608 16777216' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.tcp_wmem = 4096 8388608 16777216' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.tcp_mem = 94500000 915000000 927000000' /etc/sysctl.conf` = "0" ];then
  	echo '#确定TCP栈应该如何反映内存使用;每个值的单位都是内存页(通常是 4KB)' >> /etc/sysctl.conf
  	echo '#第一个值是内存使用的下限,第二个值是内存压力模式开始对缓冲区使用应用压力的上限' >> /etc/sysctl.conf
  	echo '#第三个值是内存上限。在这个层次上可以将报文丢弃,从而减少对内存的使用' >> /etc/sysctl.conf
  	echo 'net.ipv4.tcp_mem = 94500000 915000000 927000000' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.icmp_echo_ignore_all = 0' /etc/sysctl.conf` = "0" ];then
  	echo '#是否禁止系统回复ICMP包,其实就是禁PING' >> /etc/sysctl.conf
  	echo 'net.ipv4.icmp_echo_ignore_all = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.igmp_max_memberships = 20' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.igmp_max_memberships = 20' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.igmp_max_msf = 10' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.igmp_max_msf = 10' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.icmp_echo_ignore_broadcasts = 1' /etc/sysctl.conf` = "0" ];then
  	echo '#避免放大攻击' >> /etc/sysctl.conf
  	echo 'net.ipv4.icmp_echo_ignore_broadcasts = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.icmp_errors_use_inbound_ifaddr = 0' /etc/sysctl.conf` = "0" ];then
  	echo '#开启恶意icmp错误消息保护' >> /etc/sysctl.conf
  	echo 'net.ipv4.icmp_errors_use_inbound_ifaddr = 0' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.icmp_ignore_bogus_error_responses = 1' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.icmp_ignore_bogus_error_responses = 1' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.icmp_ratelimit = 1000' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.icmp_ratelimit = 1000' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.icmp_ratemask = 6168' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.icmp_ratemask = 6168' >> /etc/sysctl.conf
  fi
  if [ `grep -c 'net.ipv4.xfrm4_gc_thresh = 4194304' /etc/sysctl.conf` = "0" ];then
  	echo 'net.ipv4.xfrm4_gc_thresh = 4194304' >> /etc/sysctl.conf
  fi
  sysctl -p >/dev/null 2>&1
  echo -e "$green_col     系统参数优化完成! $reset_col"
}

set_dynmotd() {
  #(4)SSH登录信息提示
  echo -e "$blue_col(4)SSH登录信息提示$reset_col"
  flag=`curl -I "http://${AZQ_IP}:${AZQ_PORT}" 2>&1 |grep -c 'HTTP/1.1 200'`
  if [ "${flag}" == "1" ];then
        if [ ! -f /usr/local/bin/dynmotd ];then
  	        curl -s http://${AZQ_IP}:${AZQ_PORT}/ssh_login_tip.tar.gz -o ssh_login_tip.tar.gz && tar zxf ssh_login_tip.tar.gz && tar zxf cowsay.tar.gz && cp -rf cowsay/usr/bin/cowsay /usr/bin/ && cp -rf cowsay/usr/share/* /usr/share/ && tar zxf figlet.tar.gz && cp -rf figlet/usr/bin/figlet /usr/bin/ && cp -rf figlet/usr/share/* /usr/share/ && cp -rf color.awk /usr/local/bin/ && chmod 755 /usr/local/bin/color.awk && cp -rf dynmotd /usr/local/bin/dynmotd && chmod 755 /usr/local/bin/dynmotd && echo '###########################################################' >> /etc/profile && echo '/usr/local/bin/dynmotd' >> /etc/profile && source /etc/profile >/dev/null 2>&1
            echo -e "$green_col     SSH登录信息提示已配置,满足要求$reset_col"
        else
            echo -e "$green_col     SSH登录信息提示已配置,满足要求$reset_col"
        fi
  else
  	echo -e "$red_col    =>请启动安装器后执行命令[curl -s http://${AZQ_IP}:${AZQ_PORT}/ssh_login_tip.tar.gz -o ssh_login_tip.tar.gz && tar zxf ssh_login_tip.tar.gz && tar zxf cowsay.tar.gz && cp -rf cowsay/usr/bin/cowsay /usr/bin/ && cp -rf cowsay/usr/share/* /usr/share/ && tar zxf figlet.tar.gz && cp -rf figlet/usr/bin/figlet /usr/bin/ && cp -rf figlet/usr/share/* /usr/share/ && cp -rf color.awk /usr/local/bin/ && chmod 755 /usr/local/bin/color.awk && cp -rf dynmotd /usr/local/bin/dynmotd && chmod 755 /usr/local/bin/dynmotd && echo '###########################################################' >> /etc/profile && echo '/usr/local/bin/dynmotd' >> /etc/profile && source /etc/profile $reset_col]完成配置!"
  fi
}

check_volume() {
  #(5)检查根分区的大小
  echo -e "$blue_col(5)检查根分区的大小$reset_col"
  gen_size=`df -Th |grep /$ |awk '{print $3}' |awk -F"G" '{print $1}' |awk -F"." '{print $1}'`
  if [ "$gen_size" -lt 48 ];then
      echo -e "$red_col     根分区的空间是$gen_size,不足50G$reset_col"
  else
  	echo -e "$green_col     根分区的空间是$gen_size,满足要求$reset_col"
  fi
}


check_selinux() {
  #(6)检查selinux并关闭
  echo -e "$blue_col(6)检查selinux并关闭$reset_col"
  value=`getenforce`
  if [ "$value" == "Disabled" ];then
  	echo -e "$green_col     selinux已关闭$reset_col"
  else
  	echo -e "$red_col     selinux未关闭,将为您关闭selinux$reset_col"
  	setenforce 0
  	sed -ri 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
  	sed -ri 's/SELINUX=permissive/SELINUX=disabled/' /etc/selinux/config
  fi
}

check_timezone() {
  #(7)检查时区
  echo -e "$blue_col(7)检查时区$reset_col"
  time_zone=`timedatectl |grep "Time zone" |awk '{print $3}'`
  if [ "$time_zone" == "Asia/Shanghai" ];then
  	echo -e "$green_col     时区是Asia/Shanghai,符合要求 $reset_col"
  else
  	echo -e "$red_col     时区是$time_zone,将为您设置为Asia/Shanghai $reset_col"
  	timedatectl set-timezone Asia/Shanghai
  fi
}

check_mtu() {
  #(8)检查mtu值
  echo -e "$blue_col(8)检查mtu值$reset_col"
  need_mtu=1500
  fact_mtu=`ip a |grep "^2:" |awk -F"mtu " '{print $2}' |awk '{print $1}'`
  if [ "$fact_mtu" -eq "$need_mtu" ];then
      echo -e "$green_col     mtu值是1500,符合要求 $reset_col"
  else
      echo -e "$red_col      mtu值不是1500,而是$fact_mtu,请注意 $reset_col"
  fi
}

check_LANG() {
  #(9)检查字符集
  echo -e "$blue_col(9)检查字符集$reset_col"
  if [ "$LANG" == "zh_CN.utf8" ];then
  	echo -e "$green_col     字符集是zh_CN.utf8,符合要求 $reset_col"
  else
  	echo -e "$red_col     字符集是$LANG,建议是zh_CN.utf8$reset_col"
  	echo -en "$blue_col     是否需要为您设置为中文字符集[yes/no]: $reset_col"
  	while read var
  	do
  		if [ "$var" == "y" -o "$var" == "Y" -o "$var" == "yes" ];then
  			export LANG=zh_CN.utf8
  			echo "LANG=zh_CN.utf8" > /etc/locale.conf
  			echo "LANG=zh_CN.utf8" > /etc/profile.d/locale.sh
  			break
  		elif [ "$var" == "n" -o "$var" == "N" -o "$var" == "no" ];then
  			break
  		else
  			echo -e "$red_col        输入错误,请重新输入$reset_col"
  		fi
  	done
  fi
}

set_fonts() {
  #(10)安装中文字体
  echo -e "$blue_col(10)安装中文字体$reset_col"
  yum install -y net-tools gcc gcc-c++ automake make kernel-devel m4 ncurses-devel unixODBC-devel crontabs chrony >/dev/null 2>&1
  yum install -y bind bind-utils lua lua-devel pcre pcre-devel zlib zlib-devel openssl openssl-devel lvm2 gd-devel mkfontscale rsync >/dev/null 2>&1
  yum install -y python-devel perl-devel policycoreutils-python glibc-common xorg-x11-xauth tigervnc-server libXtst postgresql-libs >/dev/null 2>&1
  yum install -y libXrender libXft libXtst xorg-x11-xauth kde-l10n-Chinese liberation-fonts-common cjkuni-uming-fonts fontconfig >/dev/null 2>&1
  #添加字体:
  flag=`curl -I "http://${AZQ_IP}:${AZQ_PORT}" 2>&1 |grep -c 'HTTP/1.1 200'`
  if [ "${flag}" == "1" ];then
      if [ ! -d /usr/share/fonts/MicrosoftYahei -o ! -d /usr/share/fonts/song ];then
  	    curl -s http://${AZQ_IP}:8080/fonts_2.tar.gz -o fonts_2.tar.gz && tar zxf fonts_2.tar.gz -C /usr/share/fonts && cd /usr/share/fonts && mkfontscale && mkfontdir && fc-cache && fc-list :lang=zh >/dev/null 2>&1
        echo -e "$green_col     MicrosoftYahei和song字体已经安装,符合要求!"
      else
        echo -e "$green_col     MicrosoftYahei和song字体已经安装,符合要求!"
      fi
  else
  	echo -e "$red_col     =>请启动安装器后执行命令[curl -s http://${AZQ_IP}:${AZQ_PORT}/fonts_2.tar.gz -o fonts_2.tar.gz && tar zxf fonts_2.tar.gz -C /usr/share/fonts && cd /usr/share/fonts && mkfontscale && mkfontdir && fc-cache && fc-list :lang=zh]完成配置!$reset_col"
  fi
}

check_ipnet() {
  #(11)检查物理地址的网段
  echo -e "$blue_col(11)检查物理地址的网段$reset_col"
  ip_net=`ip add |grep "inet " |grep -Ev "127.0.0.1|/32" |awk '{print $2}' |awk -F'/' '{print $1}' |awk -F'.' '{print $1"."$2}'`
  if [ "$ip_net" == "172.23" -o "$ip_net" == "172.17" -o "$ip_net" == "10.96" ]
  then
  	echo -e "$red_col     物理地址网段是$ip_net,请确保没有占用172.23、172.17和10.96网段"
  else
  	echo -e "$green_col     物理地址网段是$ip_net,符合要求"
  fi
}

check_network() {
  #(12)检查主机是否能连外网
  echo -e "$blue_col(12)检查主机是否能连外网$reset_col"
  if ! ping -c2 www.baidu.com &>/dev/null
  then
  	echo -e "$red_col     请确保平台安装期间可以联网,安装完成之后可以根据需求关闭外网$reset_col"
  else
  	echo -e "$green_col     主机可以连外网,符合要求$reset_col"
  fi
}

check_firewalld() {
  #(13)关闭防火墙
  echo -e "$blue_col(13)检查firewalld防火墙$reset_col"
  if systemctl status firewalld &>/dev/null
  then
  	echo -e "$red_col     关闭firewalld防火墙$reset_col"
  	systemctl stop firewalld &>/dev/null
  	systemctl disable firewalld &>/dev/null
  elif systemctl status iptables &>/dev/null
  then
  	echo -e "$red_col     关闭iptables防火墙$reset_col"
  	systemctl stop iptables &>/dev/null
  	systemctl disable iptables &>/dev/null
  else
  	echo -e "$green_col     防火墙已关闭,符合要求$reset_col"
  fi
}

check_swap() {
  #(14)检查swap交换分区
  echo -e "$blue_col(14)检查swap交换分区$reset_col"
  swap_size=`free -m |awk '/^Swap/{print $2}'`
  if [ $swap_size -eq 0 ];then
  	echo -e "$green_col     swap交换分区是关闭的状态,符合要求$reset_col"
  else
  	echo -e "$green_col     swap交换分区是开启的状态,需要关闭$reset_col"
  	while read -p " 是否需要为您关闭交换分区[y/yes]: " var
          do
                  if [ "$var" == "y" -o "$var" == "Y" -o "$var" == "yes" ];then
  			swapoff -a
  			sed -ri '/swap/d' /etc/fstab
                          break
                  elif [ "$var" == "n" -o "$var" == "N" -o "$var" == "no" ];then
                          break
                  else
                          echo -e "$red_col       输入错误,请重新输入$reset_col"
                  fi
          done
  fi
}

check_cpu() {
  #(15)检查cpu个数
  echo -e "$blue_col(15)检查cpu个数$reset_col"
  cpu_num=`lscpu |grep ^'CPU(s):' |awk '{print $2}'`
  if [ $cpu_num -lt 8 ];then
  	echo -e "$red_col     CPU个数为$cpu_num,太低$reset_col"
  else
  	echo -e "$green_col    CPU个数为$cpu_num,请根据部署方案规划CPU资源"
  fi
}


check_mem() {
  #(16)检查内存大小
  echo -e "$blue_col(16)检查内存大小$reset_col"
  mem_size=`free -m |awk '/^Mem/{print $2}'`
  if [ $mem_size -lt 15000 ];then
          echo -e "$red_col     内存大小为$mem_size,太低$reset_col"
  else
          echo -e "$green_col    内存大小为$mem_size,请根据部署方案规划内存资源"
  fi
}

check_passwd() {
  #(17)检查/etc/passwd和/etc/group文件属性
  echo -e "$blue_col(17)检查/etc/passwd和/etc/group文件属性$reset_col"
  for name in /etc/passwd /etc/group
  do
  	i=`lsattr $name |awk '{print $1}'`
  	if [ "$i" == "-------------e--" -o "$i" == "----------------" ];then
  		echo -e "$green_col     $name文件属性符合要求$reset_col"
  	else
  		echo -e "$red_col       $name文件属性不符合要求,为您去掉文件属性$reset_col"
  		chattr -i /etc/passwd /etc/group
  		chattr -a /etc/passwd /etc/group
  	fi
  
  done
}

check_umask() {
  #(18)检查root用户的umask值
  echo -e "$blue_col(18)检查root用户的umask值$reset_col"
  if [ `umask` -eq 0022 ];then
  	echo -e "$green_col     root的umask值是0022,符合要求$reset_col"
  else
  	echo -e "$red_col     root的umask值不是0022,直接为您修改$reset_col"
  	umask 0022
  	line_num=`grep -n 'umask' /etc/profile |tail -1 |awk -F":" '{print $1}'`
  	line_value=`grep -n 'umask' /etc/profile |tail -1 |awk -F":" '{print $2}' |awk '{print $2}'`
  	sed -ri "$line_num s/$line_value/022/" /etc/profile
  fi
}

check_python() {
  #(19)检查python版本
  echo -e "$blue_col(19)检查python版本$reset_col"
  var=`python -V 2>&1 |awk -F"." '{print $1"."$2}'`
  var1=`python -V 2>&1`
  if [ "$var" == "Python 2.7" ];then
  	echo -e "$green_col     python的版本是2.7,符合要求$reset_col"
  else
  	echo -e "$red_col     python的版本$var1,不符合要求$reset_col"
  fi
}

check_openssl() {
  #(20)检查openssl版本
  echo -e "$blue_col(20)检查openssl版本$reset_col"
  ssh_var=`ssh -V 2>&1 |awk -F", " '{print $1}' |awk -F"_" '{print $2}'`
  ssh_var1=`python -V 2>&1`
  if [ "$ssh_var" == "7.4p1" ];then
  	echo -e "$green_col     python的版本是7.4p1,符合要求$reset_col"
  else
  	echo -e "$red_col     python的版本$ssh_var1,不符合要求,可能导致安装器添加主机失败!$reset_col"
  fi
}

check_http() {
  #(21)检查本机是否支持127.0.0.1:port的方式访问自身服务
  echo -e "$blue_col(21)检查本机是否支持127.0.0.1:port的方式访问自身服务,请稍等$reset_col"
  if ss -anlt |awk '{print $4}' |awk -F":" '{print $NF}' |sort |uniq |grep 80 &>/dev/null
  then
  	curl -I http://127.0.0.1:80 &>/dev/null
  	if [ $? -ne 0 ];then
  		echo -e "$red_col     curl -I http://127.0.0.1:80命令未执行成功,请确认本机是否支持127.0.0.1:port的方式访问自身服务$reset_col"
  	else
  		echo -e "$green_col     本机支持127.0.0.1:port的方式访问自身服务,符合要求$reset_col"
  	fi
  else
  	if yum -y install httpd &>/dev/null || yum -y install nginx &>/dev/null
  	then
  		systemctl start httpd &>/dev/null || systemctl start nginx &>/dev/null
  		curl -I http://127.0.0.1:80 &>/dev/null
  	        if [ $? -ne 0 ];then
          	        echo -e "$red_col     curl -I http://127.0.0.1:80命令未执行成功,请确认本机是否支持127.0.0.1:port的方式访问自身服务$reset_col"
          	else
                  	echo -e "$green_col     本机支持127.0.0.1:port的方式访问自身服务,符合要求$reset_col"
          	fi
  		num=`yum history |egrep '^ *[0-9]' |head -1 |awk '{print $1}'`
  		yum -y history undo $num &>/dev/null
  	else
  		echo -e "$red_col     无法确认机是否支持127.0.0.1:port的方式访问自身服务,请自行检查$reset_col"
  	fi
  fi
}

data_size() {
  disk_name=`echo $disk_name |sed -r 's#/dev/(.*)#\1#'`
  disk=/dev/$disk_name
  disk_size=`lsblk |grep $disk_name |awk '{print $4}'`
  if lsblk |grep $disk_name |awk '{print $4}' |grep T$ &>/dev/null
  then
  	echo -e "$green_col     数据盘的大小为$disk_size,符合要求$reset_col"
  elif lsblk |grep $disk_name |awk '{print $4}' |grep M$ &>/dev/null
  then
  	echo -e "$red_col      数据盘的大小为$disk_size,严重不符合要求$reset_col"
  elif lsblk |grep $disk_name |awk '{print $4}' |grep G$ &>/dev/null
  then
  	size=`lsblk |grep $disk_name |awk '{print $4}' |grep G$ |awk -F"G" '{print $1}' |awk -F"." '{print $1}'`
  	if [ $size -lt 200 ];then
  		echo -e "$red_col     数据盘的大小为$disk_size,不符合要求$reset_col"
  	else
  		echo -e "$green_col    数据盘的大小为$disk_size,符合要求$reset_col"
  	fi
  else
  	echo -e "$red_col     未获取到数据盘的大小$reset_col"
  fi
}
lvm_mount() {
  echo -e "$blue_col将数据盘格式化并挂载到/data $reset_col"
  lvchange -ay /dev/vg_data/lv_data &> /dev/null	
  if [ -e /dev/vg_data/lv_data ];then
  	mkdir -p /data
  	mkfs.xfs -f /dev/vg_data/lv_data
  	UUID=`blkid /dev/vg_data/lv_data |awk '{print $2}' |sed -r 's/"//g'`
  	if ! awk '{print $2}'  /etc/fstab  |grep -E "^/data$|^/data/$" &>/dev/null
  	then
  		echo "$UUID /data xfs defaults 0 0" >> /etc/fstab 
  		mount -a
  	fi
  else
  	echo -e  "$red_col没有发现对应的lvm $reset_col"
  fi
}
check_datadisk() {
  #(22)检查数据盘大小或挂载数据盘
  echo -e "$blue_col(22)检查数据盘大小$reset_col"
  echo -e "$blue_col     检查数据盘是否存在且是独立磁盘$reset_col"
  if ! lsblk |grep disk |egrep -v "vda|sda" &>/dev/null
  then
  	echo -e "red_col      未检测到数据盘,请为主机添加独立数据盘后重新执行脚本,否则无法安装环境$reset_col"
  	exit
  else
  	disk_name=`lsblk |grep disk |egrep -v "vda|sda" |awk '{print $1}' |head -1`
  	echo -ne "$green_col     检测到 $disk_name ,请确认这是否是要挂载到/data的硬盘或分区[yes|no]: $reset_col"
  	while read aaa
  	do
        if [ "$aaa" == "y" -o "$aaa" == "Y" -o "$aaa" == "yes" ];then
  			data_size		
            break
        elif [ "$aaa" == "n" -o "$aaa" == "N" -o "$aaa" == "no" ];then
  			echo -ne "$blue_col请输入您要挂载到/data目录的数据盘名或分区(如:vdc1,默认是vdc): "
  			read disk_name
  			disk_name=${disk_name:-vdc}
  			data_size
            break
        else
            echo -e "$red_col       输入错误,请重新输入$reset_col"
  			echo -ne "$green_col     检测到 $disk_name ,请确认这是否是要挂载到/data的硬盘或分区[yes|no]: $reset_col"
        fi			
  	done
  fi
  echo -e "$blue_col     检查数据盘是否以逻辑卷形式挂载$reset_col"
  if df -Th |egrep  '^/dev/mapper/.*/data$' &>/dev/null
  then
  	echo -e "$green_col     数据盘已做成lvm,并挂载到/data,符合要求$reset_col"
  elif df -Th |grep /data$ &>/dev/null
  then
  	echo -e "$red_col      数据盘已挂载到/data,但未做成lvm,建议做成lvm $reset_col"
  else
  	echo -e "$red_col     数据盘未挂载到/data,做其他检查,请稍等$reset_col"
  	if  rpm -q lvm2 &>/dev/null
  	then
  		vg_name=`pvs |grep $disk |awk '{print $2}'`
  		if [ -z "$vg_name" ];then
  			echo -e "$red_col     数据盘未做成pv,为您制作并挂载到/data $reset_col"
  			pvcreate -f $disk && vgcreate vg_data $disk && lvcreate -l 100%FREE -n lv_data vg_data
            lvm_mount
  		else
  			lvm_num=`vgs |grep $vg_name |awk '{print $3}'`
  			if [ -z "$lvm_num" ];then
  				echo -e "$red_col     数据盘中有pv,无vg和lvm,请制作vg和lvm后将其永久挂载到/data $reset_col"
  			else	
  				if [ $lvm_num -gt 0 ];then
  					echo -e "$red_col     数据盘中有lvm,请确认后将其永久挂载到/data $reset_col"
  				else
  					echo -e "$red_col     数据盘中有vg,但无lvm,请制作后将其永久挂载到/data $reset_col"
  				fi
  			fi
  		fi
  	else
  		yum makecache &>/dev/null && yum -y install lvm2 &>/dev/null
  		if [ $? -ne 0 ];then
  			echo -e "$red_col 无法使用yum安装lvm2,请安装后重试$reset_col"		
  			exit
  		fi
  		echo -en "$blue_col	是否将数据盘做成lvm,并格式化挂载到/data[yes/no]: $reset_col"
  		while read var
  		do
  	        if [ "$var" == "y" -o "$var" == "Y" -o "$var" == "yes" ];then
  				pvcreate -f $disk && vgcreate -f vg_data $disk && lvcreate -l 100%FREE -n lv_data vg_data
  				lvm_mount
  	            break
  	        elif [ "$var" == "n" -o "$var" == "N" -o "$var" == "no" ];then
  	            break
  	        else
  	            echo -e "$red_col       输入错误,请重新输入$reset_col"
  	        fi
  		done
  	fi
  fi
  echo -e "$blue_col     检测是否存在xfs文件系统格式的数据盘挂载$reset_col"
  filesystem=`df -Th |grep /data$ |awk '{print $2}'`
  if [ "$filesystem" == "xfs" ];then
  	echo -e "$green_col     数据盘是xfs文件系统格式,符合要求$reset_col"
  else
  	echo -e "$red_col     未检测到xfs文件系统格式的数据盘挂载,请确认$reset_col"
  fi
  mkdir -p /data
  echo -e "$blue_col     检测数据盘是否永久挂载$reset_col"
  if ! awk '{print $2}'  /etc/fstab  |grep -E "^/data$|^/data/$" &>/dev/null	
  then
  	echo -e "$red_col     未检测到数据盘的永久挂载,请您永久挂载$reset_col"
  else
  	result=$(mount -a 2>&1)
  	if [ -z "$result" ];then
  		echo -e "$green_col     数据盘已永久挂载,符合要求$reset_col"
  	else
  		echo -e "$red_col      数据盘已永久挂载,但/etc/fstab文件中有语法错误$reset_col"	
  	fi
  fi
}

check_root() {
  #(23)检查本机是否禁用了root的远程登录
  echo -e "$blue_col(23)检查本机是否禁用了root的远程登录$reset_col"
  echo -e "$blue_col     如果发现脚本停留在输密码处,请直接敲三次enter,网络内定是禁用了root的远程登录,请检查 $reset_col"
  if egrep '^ *PermitRootLogin *no' /etc/ssh/sshd_config &>/dev/null
  then
  	echo -e "$red_col      检查到本机已禁用了root的远程登录,不符合要求,为您关闭$reset_col"
  	sed -ri '/^ *PermitRootLogin *no/d' /etc/ssh/sshd_config
  	systemctl restart sshd &>/dev/null
  else
  	if [ ! -f ~/.ssh/id_rsa ];then
  		ssh-keygen -t RSA -N '' -f ~/.ssh/id_rsa &>/dev/null
  	fi
  	str=`cat ~/.ssh/id_rsa.pub |awk '{print $2}'`
  	touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys
  	if ! grep $str ~/.ssh/authorized_keys &>/dev/null
  	then
  		cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
  	fi
  	if ssh 127.0.0.1 'date' &>/dev/null
  	then
  		echo -e "$green_col     本机可以使用root远程连接自己,符合要求$reset_col"
  		echo -e "$red_col     但还是无法排除网络是否禁用了root的远程登录,请谨慎$reset_col"
  	fi
  fi
}

check_kernel() {
  #(24)升级服务器内核版本
  echo -e "$blue_col(24)检查内核版本$reset_col"
  need_kernel="5.6"
  fact_kernel=`uname  -r |awk -F"." '{print $1"."$2}'`
  fact_kernel1=`uname  -r |awk -F"." '{print $1"."$2}'`
  zhu=`uname  -r |awk -F"." '{print $1}'`
  ci=`uname  -r |awk -F"." '{print $2}'`
  if [ "$fact_kernel" == "$need_kernel" ];then
  	echo -e "$green_col     内核版本$fack_kernel1,符合大版本$need_kernel的要求 $reset_col"
  elif [ $zhu -lt 5 ] || [ $zhu -eq 5 -a $ci -lt 6 ];then
  	echo -e "$red_col     内核大版本是$fact_kernel,小于$need_kernel,需要升级内核 $reset_col"
    flag=`curl -I "http://${AZQ_IP}:${AZQ_PORT}" 2>&1 |grep -c 'HTTP/1.1 200'`
    if [ "${flag}" == "1" ];then
  	    echo -e "$green_col     操作系统即将升级到5.6.4版本...$reset_col"
  	    curl http://${AZQ_IP}:${AZQ_PORT}/kernel_update-5.6.4_x86_64.tar.gz -o kernel_update-5.6.4_x86_64.tar.gz >/dev/null 2>&1 && tar -zxf kernel_update-5.6.4_x86_64.tar.gz >/dev/null 2>&1 && bash kernel_update.sh
    else
  	    echo -e "$red_col     =>启动安装器后执行命令[curl -s http://${AZQ_IP}:8080/kernel_update-5.6.4_x86_64.tar.gz -o kernel_update-5.6.4_x86_64.tar.gz && tar -zxf kernel_update-5.6.4_x86_64.tar.gz && bash kernel_update.sh]可以自动升级内核到5.6.4版本!$reset_col"
    fi	
  fi
  echo -e "$blue_col     检查操作系统版本$reset_col"
  need_version="CentOS Linux release 7.5.1804"
  need_version1="CentOS Linux release 7.4"
  need_version2="CentOS Linux release 7.5"
  need_version3="CentOS Linux release 7.6"
  need_version4="CentOS Linux release 7.7"
  need_version5="CentOS Linux release 7.8"
  need_version6="CentOS Linux release 7.9"
  fact_version=`cat /etc/redhat-release |awk '{print $1,$2,$3,$4}'`
  fact_version1=`cat /etc/redhat-release |awk -F"." '{print $1"."$2}'`
  if [ "$fact_version" == "$need_version" ];then
      echo -e "$green_col     操作系统版本完全符合$need_version $reset_col"
  elif [ "$fact_version1" == "$need_version1" -o "$fact_version1" == "$need_version2" -o "$fact_version1" == "$need_version3" -o "$fact_version1" == "$need_version4" -o "$fact_version1" == "$need_version5" -o "$fact_version1" == "$need_version6" ];then
  	echo -e "$green_col     操作系统版本是$fact_version1,符合大版本的要求!$reset_col"
  else
  	echo -e "$red_col     操作系统版本是$fact_version,不符合$need_version要求!$reset_col"
  fi
}

main() {
  use_root
  set_hostname
  set_ssh
  set_sysctl
  set_dynmotd
  check_volume
  check_selinux
  check_timezone
  check_mtu
  check_LANG
  set_fonts
  check_ipnet
  check_network
  check_firewalld
  check_swap
  check_cpu
  check_mem
  check_passwd
  check_umask
  check_python
  check_openssl
  check_http
  check_datadisk
  check_root
  check_kernel
}
main

[root@YonXin-SIT-Master01 ~]# sh ~/init-centos7.sh

3.3 时间同步

这里以YonXin-SIT-Master01为例:

[root@YonXin-SIT-Master01 ~]# yum install chrony -y
[root@YonXin-SIT-Master01 ~]# vim /etc/chrony.conf
server ntp1.aliyun.com iburst
server ntp2.aliyun.com iburst
driftfile /var/lib/chrony/drift
makestep 1.0 3
rtcsync
allow 10.0.0.0/24
local stratum 10
logdir /var/log/chrony
[root@YonXin-SIT-Master01 ~]# systemctl enable chronyd && systemctl restart chronyd
[root@YonXin-SIT-Master01 ~]# systemctl list-unit-files | grep chronyd
[root@YonXin-SIT-Master01 ~]# timedatectl set-timezone Asia/Shanghai    //修改为中国时区
[root@YonXin-SIT-Master01 ~]# chronyc sources -v    //查看时间同步源
[root@YonXin-SIT-Master01 ~]# chronyc sourcestats -v    //查看时间同步源状态
[root@YonXin-SIT-Master01 ~]# vim /var/log/messages

4. 安装DNS服务

PS:使用nginx作为前端代理ingress时需要DNS来解析容器内网的域名服务!

(1) 规划在YonXin-SIT-Master01上安装DNS服务:

[root@YonXin-SIT-Master01 ~]# yum  install  bind  bind-utils -y
[root@YonXin-SIT-Master01 ~]# vim  /etc/named.conf    //修改主配置文件如下
acl slaves { 10.0.0.1; };
options {
        listen-on port 53 { 10.0.0.1; 127.0.0.1; };
        listen-on-v6 port 53 { any; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { any; };
        allow-transfer  { slaves; };
        forward only;
        forwarders { 114.114.114.114; 8.8.8.8; };
        recursion yes;
        dnssec-enable no;
        dnssec-validation no;

        /* Path to ISC DLV key */
        bindkeys-file "/etc/named.iscdlv.key";
        managed-keys-directory "/var/named/dynamic";
        pid-file "/run/named/named.pid";
        session-keyfile "/run/named/session.key";
};
logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};
zone "." IN {
        type hint;
        file "named.ca";
};
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
[root@YonXin-SIT-Master01 ~]# named-checkconf  /etc/named.conf    //检查配置文件是否有语法错误
[root@YonXin-SIT-Master01 ~]# systemctl enable named && systemctl restart named    //启动DNS服务

(2) 在/etc/named.rfc1912.zones配置文件中添加如下配置(用于定义根区域和自定义区域):

[root@YonXin-SIT-Master01 ~]# vim  /etc/named.rfc1912.zones
zone "hostname.com" IN {
        type master;
        file "hostname.com.zone";
        allow-update { any; };
};

zone "k8s-images.com" IN {
        type master;
        file "k8s-images.com.zone";
        allow-update { any; };
};

zone "k8s-ingress.com" IN {
        type master;
        file "k8s-ingress.com.zone";
        allow-update { any; };
};

zone "yonxin100.com" IN {
        type master;
        file "yonxin100.com.zone";
        allow-update { any; };
};

(3) 在/var/named/目录添加如下文件:

[root@YonXin-SIT-Master01 ~]# vim  /var/named/hostname.com.zone
$ORIGIN hostname.com.
$TTL 600 ;
@       IN SOA  dns.hostname.com. dnsadmin.hostname.com. (
                                        2022031201      ; serial
                                        10800   ; refresh
                                        900     ; retry
                                        604800  ; expire
                                        86400 ) ; minimum
        NS      dns.hostname.com.
$TTL 60 ;
dns                     A       10.0.0.1
YonXin-SIT-Master01     A       10.0.0.1
YonXin-SIT-Master02     A       10.0.0.2
YonXin-SIT-Node01       A       10.0.0.3
YonXin-SIT-Node02       A       10.0.0.4
[root@YonXin-SIT-Master01 ~]# vim /var/named/k8s-images.com.zone
$ORIGIN k8s-images.com.
$TTL 600 ;
@       IN SOA  dns.k8s-images.com. dnsadmin.k8s-images.com. (
                                        2022031201      ; serial
                                        10800   ; refresh
                                        900     ; retry
                                        604800  ; expire
                                        86400 ) ; minimum
        NS      dns.k8s-images.com.
$TTL 60 ;
dns     A       10.0.0.1
harbor  A       10.0.0.3
[root@YonXin-SIT-Master01 ~]# vim /var/named/k8s-ingress.com.zone
$ORIGIN k8s-ingress.com.
$TTL 600 ;
@       IN SOA  dns.k8s-ingress.com. dnsadmin.k8s-ingress.com. (
                                        2022031201      ; serial
                                        10800   ; refresh
                                        900     ; retry
                                        604800  ; expire
                                        86400 ) ; minimum
        NS      dns.k8s-ingress.com.
$TTL 60 ;
dns     A       10.0.0.1
*       A       10.0.0.1
*       A       10.0.0.2
[root@YonXin-SIT-Master01 ~]# vim /var/named/yonxin100.com.zone
$ORIGIN yonxin100.com.
$TTL 600 ;
@       IN SOA  dns.yonxin100.com. dnsadmin.yonxin100.com. (
                                        2022031201      ; serial
                                        10800   ; refresh
                                        900     ; retry
                                        604800  ; expire
                                        86400 ) ; minimum
        NS      dns.yonxin100.com.
$TTL 60 ;
dns     A       10.0.0.1
www     A       10.0.0.4
[root@YonXin-SIT-Master01 ~]# chmod -R 755 /var/named    //给新建文件加可读权限
[root@YonXin-SIT-Master01 ~]# rndc reload    //重新加载配置

(4) 所有服务器配置域名解析:

[root@master ~]# vim /etc/resolv.conf
# Generated by NetworkManager
search hostname.com
nameserver 10.0.0.1

5. 安装nginx作为所有业务入口

Nginx百度网盘下载链接:https://pan.baidu.com/s/1hZ8vMb8eFRQzb9VT1G7iYA 提取码:pjiu

[root@YonXin-SIT-Node02 ~]# tar zxf Yonxin-nginx-1.20.2-common-data.tar.gz
[root@YonXin-SIT-Node02 ~]# cd Yonxin-nginx-1.20.2-common-data && ./install_nginx.sh
[root@YonXin-SIT-Node02 ~]# cat /data/middleware/nginx/conf/nginx.conf    #优化的配置
user  root;
worker_processes  auto;
worker_rlimit_nofile  65535;
pid        /run/nginx.pid;


events {
    use epoll;
    worker_connections  20480;
    multi_accept on;
    accept_mutex on;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    #配置日志打印格式;
    log_format  main  '$remote_addr|$remote_user|[$time_local]|"$request"|'
                      '$status|$body_bytes_sent|$http_host|"$http_referer"|'
                      '"$http_user_agent"|$http_x_forwarded_for|$upstream_cache_status|'
                      '"$upstream_http_content_type"|$request_time|$upstream_response_time|$bytes_sent|$request_length|'
                      '"$upstream_addr"|$uuid|$span_id';

    map $time_iso8601 $logdate {
        '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
        default 'date-not-found';
    }

    access_log  logs/access_$logdate.log  main;
    error_log logs/error.log notice;
    open_log_file_cache max=10;
    #使用内核的FD文件传输功能,可以减少user mode和kernel mode的切换,从而提升服务器性能;
    sendfile        on;
    #当应用程序产生数据时,内核不会立马封装包,而是当数据量积累到一定量时才会封装,然后传输,防止网络阻塞;
    tcp_nopush     on;

    charset utf-8;
    #避免多增加一些域名转向到相同的upstream里面,影响nginx正常hash存储;
    server_names_hash_bucket_size 128;
    #请求头大小
    client_header_buffer_size 32k;
    #(请求行+请求头)的大小不能超过32K(4 * 8k);
    large_client_header_buffers 4 32k;

    #表示客户端请求服务器传输最大允许文件大小4G
    client_max_body_size 4096m;
    #分配给请求数据的Buffer大小
    client_body_buffer_size 512k;

    #HTTP长连接超时时间(秒),keepalive_timeout  0 表示关闭长连接;
    keepalive_timeout  65;
    #隐藏nginx版本信息
    server_tokens off;
    #当客户端请求头中带有下划线的字段将会被识别为有效字段;
    underscores_in_headers on;
    #设置头部哈希表的最大值,不能小于后端服务器设置的头部总数;
    proxy_headers_hash_max_size 51200;
    #设置头部哈希表大小;
    proxy_headers_hash_bucket_size 6400;
    #后端服务器连接的超时时间_发起握手等候响应超时时间(秒);
    proxy_connect_timeout 5;
    #后端服务器处理请求的时间
    proxy_read_timeout 7200;
    proxy_send_timeout 5000;
    proxy_buffer_size 16k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    proxy_temp_path /data/middleware/nginx/proxy_temp;
    proxy_cache_path /data/middleware/nginx/proxy_cache levels=1:2 keys_zone=content:20m inactive=1d max_size=100m;
    proxy_cache_path /data/middleware/nginx/proxy_cache_image levels=1:2 keys_zone=content_image:20m inactive=1d max_size=100m;
    proxy_cache_bypass $http_secret_header;
    proxy_ignore_client_abort on;
    #监控Nginx虚拟主机流量以及状态
    vhost_traffic_status_zone;
    vhost_traffic_status_filter_by_host on;
    #开启文件请求时进行gzip压缩传输;
    gzip  on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.0;
    #压缩等级;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript application/javascript text/css;
    #选项可让前端的缓存服务器缓存经过的gzip压缩的页面;
    gzip_vary on;

    # 指定lua模块路径,多个之间";"分隔,其中";;"表示默认搜索路径,默认到nginx的根目录下找
    lua_package_path "/data/middleware/nginx/lualib/?.lua;/data/middleware/nginx/lualib/lib/lua/?.lua;;";
    init_by_lua '
        require "resty.core"
        uuid4 = require "uuid4"
    ';

    #配置include管理多个配置文件;
    include /data/middleware/nginx/conf.d/*.conf;
}
[root@YonXin-SIT-Node02 ~]# cat /data/middleware/nginx/conf.d/upstream-server.conf    #配置ingress的代理
upstream ingress {
    server 10.0.0.1 max_fails=2 fail_timeout=3s weight=1;
    server 10.0.0.2 max_fails=2 fail_timeout=3s weight=1;
    check interval=3000 rise=2 fall=5 timeout=1000 type=tcp;
}
#upstream backend {
#    ip_hash;
#    server 10.32.140.177:80;
#    check fall=3 interval=1000 rise=2 timeout=2000 type=http default_down=true;
#    check_http_send "GET  /nccloud/healthcheck HTTP/1.1\r\nHOST:xxxx.com\r\n\r\n";
#    check_http_expect_alive http_2xx http_3xx;
#}

server {
    listen 80 default;
    proxy_http_version 1.1;
    if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})"){
      set $log_year $1;
      set $log_month $2;
      set $log_day $3;
    }
    set_by_lua $uuid '
          if ngx.var.http_X_traceId == nil then
              return string.sub(ngx.var.request_id,17,-1)
          else
              return ngx.var.http_X_traceId
          end
      ';
    set_by_lua $span_id '
          if ngx.var.http_X_spanId == nil then
              return ngx.var.uuid
          else
              return ngx.var.http_X_spanId
          end
      ';
    access_log logs/location_access_$log_year-$log_month-$log_day.log main;
    error_log  logs/location_error.log notice;
    error_page  404              /404.html;
    error_page 500 502 503 504   /50x.html;
    location = /50x.html {
      root html;
    }
    server_name www.yonxin100.com;
    listen 443 ssl;
    ssl_certificate "cert/server.crt";
    ssl_certificate_key "cert/server.key";

    location /status {
      #allow IP;          
      #deny all;
      check_status;
      access_log off;         
      #vhost_traffic_status_display;
      #vhost_traffic_status_display_format html;
    }

    location / {
      root   html;
      index  index.html index.htm;
    }

    location /nginx/ {
      proxy_pass http://ingress/;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header X-Forwarded-Host $http_host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host "test-nginx.k8s-ingress.com"; #对应ingress配置
    }

    location /tomcat/ {
      proxy_pass http://ingress/;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header X-Forwarded-Host $http_host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host "test-tomcat.k8s-ingress.com"; #对应ingress配置
    }
}

6. 安装docker和containerd

PS:所有服务都需要安装,Docker无法正常启动一般是selinux未设置disabled,docker IP跟主机IP冲突或者linux内核版本过低!

(1) 使用yum安装准备:

[root@server ~]# yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo  //下载安装仓库配置
[root@server ~]# yum clean all && yum makecache

(2) 加载ipvs内核模块:

[root@server ~]# yum install ipvsadm ipset sysstat conntrack libseccomp -y                    //启用ipvs内核模块
[root@server ~]# echo 'options ip_vs conn_tab_bits=20' > /etc/modprobe.d/ip_vs.conf    //调整ipvs哈希表大小
[root@server ~]# ipvsadm --set 10 10 10  && echo "ipvsadm --set 10 10 10" >> /etc/rc.d/rc.local  //设置开机启动
cat >  /etc/modules-load.d/ipvs.conf <<EOF
ip_vs
ip_vs_lc
ip_vs_wlc
ip_vs_rr
ip_vs_wrr
ip_vs_lblc
ip_vs_lblcr
ip_vs_dh
ip_vs_sh
ip_vs_fo
ip_vs_nq
ip_vs_sed
ip_vs_ftp
ip_vs_sh
nf_conntrack
ip_tables
ip_set
xt_set
ipt_set
ipt_rpfilter
ipt_REJECT
ipip
EOF
cat >  /etc/modules-load.d/containerd.conf <<EOF
overlay
br_netfilter
EOF
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

[root@server ~]# service systemd-modules-load restart && systemctl enable --now systemd-modules-load
[root@server ~]# sysctl --system && lsmod | grep -e ip_vs -e nf_conntrack -e overlay  //查询模块是否加载
[root@server ~]# ipvsadm -Ln          //查看LVS转发列表                                                                

(3) 安装服务

[root@server ~]# yum -y install docker-ce-20.10.9 docker-ce-cli-20.10.9 docker-compose containerd.io-1.6.6
[root@server ~]# mkdir -p /data/docker && mkdir -p /etc/docker && chmod 755 -R /etc/docker
[root@server ~]# vim /etc/docker/daemon.json     //修改 Docker Cgroup Driver 为 systemd
{
  "graph": "/data/docker",
  "insecure-registries": ["0.0.0.0/0","harbor.k8s-images.com","harbor.k8s-images.com:81"],
  "registry-mirrors": ["https://cjw7u3gx.mirror.aliyuncs.com","https://docker.mirrors.ustc.edu.cn"],
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {"max-size":"200m", "max-file":"5","labels": "somelabel","env": "os,customer"},
  "storage-driver": "overlay2",
  "bip": "172.17.0.1/16"
}
[root@server ~]# mkdir -p /etc/containerd && containerd config default | tee /etc/containerd/config.toml
[root@server ~]# vim /etc/containerd/config.toml
#1 systemd_cgroup = false 改为 systemd_cgroup = true
#2 sandbox_image = "k8s.gcr.io/pause:3.6" 改为:
sandbox_image = "registry.aliyuncs.com/google_containers/pause:3.6"
#3    [plugins."io.containerd.grpc.v1.cri".containerd.default_runtime]  改为:
        runtime_root = ""
        runtime_type = "io.containerd.runtime.v1.linux"
[root@server ~]#  systemctl daemon-reload && systemctl enable docker && systemctl restart docker  //开机启动
[root@server ~]#  systemctl enable containerd && systemctl status containerd && systemctl status docker
[root@server ~]#  ctr version && runc -version
[root@server ~]# docker info    //查看Docker环境(重点)

7. 安装Harbor服务

Harbor安装包百度网盘下载链接:https://pan.baidu.com/s/1pJaZoXzDq3qRDiW72mkAHg 提取码:prju

[root@YonXin-SIT-Node02 ~]# tar zxf Yonxin-harbor-v2.1.0-data.tar.gz
[root@YonXin-SIT-Node02 ~]# cd Yonxin-harbor-v2.1.0-data && ./install_harbor

8. 安装ETCD服务

8.1 安装cfssl工具

cfssl版本:1.6.1
(1) cfssl/cfssl-json/cfssl-certinfo下载地址:

https://github.com/cloudflare/cfssl/releases
  • cfssl: 用于签发证书,输出json格式文本;
  • cfssl-json: 将cfssl签发生成的证书(json格式)变成文件承载式文件;
  • cfssl-certinfo: 验证查看证书信息。

(2) cfssl工具的子命令包括:

  • genkey: 生成一个key(私钥)和CSR(证书签名请求)
  • certinfo: 输出给定证书的证书信息
  • gencert: 生成新的key(密钥)和签名证书,该命令的参数如下:
    • -initca:初始化一个新ca,生成根CA时需要。
    • -ca:指明ca的证书(ca.pem)
    • -ca-key:指明ca的私钥文件(ca-key.pem)
    • -config:指明证书请求csr的json文件(ca-config.json)
    • -profile:与-config中的profile对应,是指根据config中的profile段来生成证书的相关信息

8.2 生成etcd证书

(1) 创建生成CA证书签名请求(CSR)的JSON配置文件,文件路径及内容:

[root@YonXin-SIT-Master01 ~]# cat > /data/etcd/cert/ca-csr.json << EOF
{
    "CA":{"expiry":"876000h"},
    "CN": "kubernetes",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "L": "Beijing",
            "ST": "Beijing",
            "O": "k8s",
            "OU": "System"
        }
    ]
}
EOF

(2) 创建CA根证书策略文件

[root@YonXin-SIT-Master01 ~]# cat > /data/etcd/cert/ca-config.json << EOF
{
    "signing": {
        "default": {
            "expiry": "876000h"
        },
        "profiles": {
            "server": {
                "expiry": "876000h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth"
                ]
            },
            "client": {
                "expiry":"876000h",
                "usages": [
                    "signing",
                    "key enchiperment",
                    "client auth"
                ]
            },
            "kubernetes": {
                "expiry":"876000h",
                "usages": [
                    "signing",
                    "key enchiperment",
                    "server auth",
                    "client auth"
                ]
            },            
            "peer": {
                "expiry": "876000h",
                "usages": [
                    "signing",
                    "key enchiperment",
                    "server auth",
                    "client auth"
                ]
            }
        }
    }
}
EOF

(3) 创建etcd证书,客户端访问与节点互相访问使用同一套证书

[root@YonXin-SIT-Master01 ~]# cat > /data/etcd/cert/etcd-csr.json << EOF
{
    "CN": "k8s-etcd",
    "hosts": [
        "10.0.0.1",
        "10.0.0.2",
        "10.0.0.3",
        "127.0.0.1"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "k8s",
            "OU": "system"
        }
    ]
}
EOF

(4) 生成etcd证书和私钥

[root@YonXin-SIT-Master01 ~]# cd /data/etcd/cert/ && cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
[root@YonXin-SIT-Master01 ~]# cfssl gencert -ca="ca.pem" -ca-key="ca-key.pem" -config="ca-config.json" -profile="kubernetes" etcd-csr.json | cfssljson -bare etcd

(5) 查询证书有效期

[root@YonXin-SIT-Master01 ~]# openssl x509 -noout -text -in /data/etcd/cert/ca.pem | grep Not  //查询ca证书有效期
[root@YonXin-SIT-Master01 ~]# openssl x509 -noout -text -in /data/etcd/cert/etcd.pem | grep Not  //查询etcd证书有效期

8.3 安装etcd集群

(1) etcd版本:v3.5.4 ,安装包下载地址:

https://github.com/etcd-io/etcd/releases/tag/v3.5.4

(2) 二进制安装第一台etcd

[root@YonXin-SIT-Master01 ~]# tar -zxf etcd-v3.5.4-linux-amd64.tar.gz -C /data/
[root@YonXin-SIT-Master01 ~]# mv /data/etcd-v3.5.4-linux-amd64 /data/etcd 
[root@YonXin-SIT-Master01 ~]# mkdir -p /data/etcd/{cert,config,data,logs,service}
[root@YonXin-SIT-Master01 ~]# cp /data/etcd/etcdctl  /usr/bin/
[root@YonXin-SIT-Master01 ~]# vim /data/etcd/config/etcd.conf
#[Member]
ETCD_NAME="etcd01"
ETCD_DATA_DIR="/data/etcd/data"
ETCD_LISTEN_PEER_URLS="https://10.0.0.1:2380"
ETCD_LISTEN_CLIENT_URLS="https://10.0.0.1:2379,http://127.0.0.1:2379"
ETCD_QUOTA_BACKEND_BYTES="8000000000"
#[Clustering]
#ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://10.0.0.1:2380"
ETCD_ADVERTISE_CLIENT_URLS="https://10.0.0.1:2379"
ETCD_INITIAL_CLUSTER="etcd01=https://10.0.0.1:2380,etcd02=https://10.0.0.2:2380,etcd03=https://10.0.0.3:2380"
ETCD_INITIAL_CLUSTER_TOKEN="etcd-cluster"
ETCD_LOG_OUTPUT="stdout"
[root@YonXin-SIT-Master01 ~]# vim /data/etcd/service/etcd.service
[Unit]
Description=Etcd Server
After=network.target
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
User=root
WorkingDirectory=/data/etcd/
EnvironmentFile=/data/etcd/config/etcd.conf
ExecStart=/data/etcd/etcd \
--cert-file=/data/etcd/cert/etcd.pem \
--key-file=/data/etcd/cert/etcd-key.pem \
--trusted-ca-file=/data/etcd/cert/ca.pem \
--peer-cert-file=/data/etcd/cert/etcd.pem \
--peer-key-file=/data/etcd/cert/etcd-key.pem \
--peer-trusted-ca-file=/data/etcd/cert/ca.pem \
--initial-cluster-state=new \
--peer-client-cert-auth \
--client-cert-auth
Restart=on-failure
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
[root@YonXin-SIT-Master01 ~]# cp /data/etcd/service/etcd.service  /usr/lib/systemd/system/
[root@YonXin-SIT-Master01 ~]# systemctl daemon-reload && systemctl enable etcd && systemctl restart etcd
[root@YonXin-SIT-Master01 ~]# echo "#ETCDCTL Env" >> /etc/profile && echo "export ETCDCTL_API=3" >> /etc/profile

(3) 二进制安装其他etcd
复制第一台etcd的目录/data/etcd 到其他2台服务器的/data 目录下,修改/data/etcd/config/etcd.conf配置文件的IP地址和etcd名称,删除/data/etcd/data/目录下的文件,然后执行:

[root@YonXin-SIT-Master02 ~]# cp /data/etcd/service/etcd.service  /usr/lib/systemd/system/
[root@YonXin-SIT-Master02 ~]# systemctl daemon-reload && systemctl enable etcd && systemctl restart etcd
[root@YonXin-SIT-Master02 ~]# echo "#ETCDCTL Env" >> /etc/profile && echo "export ETCDCTL_API=3" >> /etc/profile

(4) 检查etcd集群状态

[root@YonXin-SIT-Master01 ~]# etcdctl --endpoints="https://10.0.0.1:2379,https://10.0.0.2:2379,https://10.0.0.3:2379" --cacert=/data/etcd/cert/ca.pem --cert=/data/etcd/cert/etcd.pem --key=/data/etcd/cert/etcd-key.pem --write-out=table member list   #查看集群成员   

在这里插入图片描述

[root@YonXin-SIT-Master01 ~]# etcdctl --endpoints="https://10.0.0.1:2379,https://10.0.0.2:2379,https://10.0.0.3:2379" --cacert=/data/etcd/cert/ca.pem --cert=/data/etcd/cert/etcd.pem --key=/data/etcd/cert/etcd-key.pem --write-out=table endpoint status  #查看集群状态                                                                                                                         

在这里插入图片描述

9. 安装第一台k8s-master服务

9.1 配置4层反向代理

[root@YonXin-SIT-Master01 ~]# yum install -y keepalived  haproxy    //拉取并配置Keepalived和haproxy
[root@YonXin-SIT-Master01 ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
   router_id K8S-HAPROXY
   script_user root
   enable_script_security
}
vrrp_script check_haproxy {
    script "/etc/keepalived/check_haproxy.sh"
    interval 2
    weight -40
}
vrrp_instance VI_HAPROXY {
    state BACKUP
    interface bond0
    virtual_router_id 218
    priority 120
    advert_int 2
    authentication {
        auth_type PASS
        auth_pass 2121
    }
    virtual_ipaddress {
        10.0.0.8
    }
    track_script {
        check_haproxy
    }
}
[root@YonXin-SIT-Master01 ~]# journalctl -f -u keepalived    //查看实时日志打印
[root@YonXin-SIT-Master01 ~]# vim /etc/keepalived/check_haproxy.sh
#!/bin/bash
flag=`systemctl status haproxy |grep -cE "running"`
if [ ${flag} -eq 1 ];then
  exit 0
else
  exit 1
fi
[root@YonXin-SIT-Master01 ~]# chmod 755  /etc/keepalived/check_haproxy.sh     //可执行权限
[root@YonXin-SIT-Master01 ~]# vim /etc/haproxy/haproxy.cfg
global
  log 127.0.0.1 local2 info
  chroot      /var/lib/haproxy
  pidfile     /var/run/haproxy.pid
  maxconn 4096
  nbproc      8
  daemon
  stats bind-process 1
  stats socket /var/lib/haproxy/stats
defaults
  mode                     http
  log                     global
  option                  dontlognull
  option http-server-close
  option                  redispatch
  option                  forwardfor
  retries                 3
  timeout http-request    10s
  timeout queue           1m
  timeout connect         10s
  timeout client          1m
  timeout server          1m
  timeout http-keep-alive 10s
  timeout check           10s
  option forceclose
  maxconn                 3000
frontend  main *:5443
    mode tcp
    option tcplog
    default_backend     k8s_apiserver
backend k8s_apiserver
    mode tcp
    option tcplog
    balance     roundrobin  # 默认的负载均衡的方式,轮询方式
    server k8s-master01 10.0.0.1:6443 check inter 2000 fall 2 rise 2 weight 1
    server k8s-master02 10.0.0.2:6443 check inter 2000 fall 2 rise 2 weight 1
[root@YonXin-SIT-Master01 ~]# systemctl enable haproxy && systemctl restart haproxy && systemctl status haproxy
[root@YonXin-SIT-Master01 ~]# systemctl enable keepalived && systemctl restart keepalived

9.2 签发所有证书

安装包下载地址:https://github.com/kubernetes/kubernetes/tree/master/CHANGELOG
(1) 下载二进制包并解压

[root@YonXin-SIT-Master01 ~]# tar -zxf kubernetes-server-linux-amd64.tar.gz -C /data/
[root@YonXin-SIT-Master01 ~]# mv /data/kubernetes/server/bin  /data/kubernetes/
[root@YonXin-SIT-Master01 ~]# rm -rf /data/kubernetes/{kubernetes-src.tar.gz,LICENSES,addons,server,bin/{*.tar,*_tag}}
[root@YonXin-SIT-Master01 ~]# mkdir -p /data/kubernetes/{cfssl,pki,config,data,logs,service,yaml}
[root@YonXin-SIT-Master01 ~]# cp /data/kubernetes/bin/kubectl /usr/bin/

(2) 创建生成CA证书签名请求(CSR)的JSON配置文件,文件路径及内容:

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/pki/ca-csr.json << EOF
{
    "CA":{"expiry":"876000h"},
    "CN": "kubernetes",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "L": "Beijing",
            "ST": "Beijing",
            "O": "k8s",
            "OU": "System"
        }
    ]
}
EOF

(2) 创建CA根证书策略文件

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/pki/ca-config.json << EOF
{
    "signing": {
        "default": {
            "expiry": "876000h"
        },
        "profiles": {
            "server": {
                "expiry": "876000h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth"
                ]
            },
            "client": {
                "expiry":"876000h",
                "usages": [
                    "signing",
                    "key enchiperment",
                    "client auth"
                ]
            },
            "kubernetes": {
                "expiry":"876000h",
                "usages": [
                    "signing",
                    "key enchiperment",
                    "server auth",
                    "client auth"
                ]
            },            
            "peer": {
                "expiry": "876000h",
                "usages": [
                    "signing",
                    "key enchiperment",
                    "server auth",
                    "client auth"
                ]
            }
        }
    }
}
EOF

(3) 创建kube-apiserver的json文件

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/pki/kube-apiserver-csr.json << EOF
{
    "CN": "kubernetes",
    "hosts": [
      "10.0.0.1",
      "10.0.0.2",
      "10.0.0.3",
      "10.0.0.8",
      "10.96.0.1",
      "127.0.0.1",
      "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

(4) 创建kube-controller-manager的json文件

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/pki/kube-controller-manager-csr.json << EOF
{
  "CN": "system:kube-controller-manager",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing", 
      "ST": "BeiJing",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

(5) 创建kube-scheduler的json文件

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/pki/kube-scheduler-csr.json << EOF
{
  "CN": "system:kube-scheduler",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing",
      "ST": "BeiJing",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

(6) 创建kubectl的json文件

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/pki/kubectl-csr.json <<EOF
{
  "CN": "admin",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "L": "BeiJing",
      "ST": "BeiJing",
      "O": "system:masters",
      "OU": "System"
    }
  ]
}
EOF

(7) 创建kube-proxy的json文件

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/pki/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

(8) 创建所有证书文件

[root@YonXin-SIT-Master01 ~]# cd /data/kubernetes/pki && cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
[root@YonXin-SIT-Master01 ~]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-apiserver-csr.json | cfssljson -bare kube-apiserver
[root@YonXin-SIT-Master01 ~]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-controller-manager-csr.json | cfssljson -bare kube-controller-manager
[root@YonXin-SIT-Master01 ~]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-scheduler-csr.json | cfssljson -bare kube-scheduler
[root@YonXin-SIT-Master01 ~]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kubectl-csr.json | cfssljson -bare kubectl
[root@YonXin-SIT-Master01 ~]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-proxy-csr.json | cfssljson -bare kube-proxy

(9) 查询证书文件有效期

[root@YonXin-SIT-Master01 ~]# openssl x509 -noout -text -in /data/kubernetes/pki/ca.pem | grep Not     //查询ca证书有效期
[root@YonXin-SIT-Master01 ~]# openssl x509 -noout -text -in /data/kubernetes/pki/kube-apiserver.pem | grep Not

9.3 生成token.csv文件

[root@YonXin-SIT-Master01 ~]# head -c 16 /dev/urandom | od -An -t x | tr -d ' '
e6c807c0033ea7cfcda16abad126751c
[root@YonXin-SIT-Master01 ~]# echo 'e6c807c0033ea7cfcda16abad126751c,kubelet-bootstrap,10001,"system:node-bootstrapper"' >  /data/kubernetes/config/token.csv

9.4 创建kube-apiserver启动配置和脚本

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/config/kube-apiserver.conf << EOF
KUBE_APISERVER_OPTS="--logtostderr=false \\
--v=2 \\
--etcd-servers=https://10.0.0.1:2379,https://10.0.0.2:2379,https://10.0.0.3:2379 \\
--bind-address=10.0.0.1 \\
--secure-port=6443 \\
--advertise-address=10.0.0.1 \\
--allow-privileged=true \\
--service-cluster-ip-range=10.96.0.0/16 \\
--enable-admission-plugins=NodeRestriction \\
--authorization-mode=RBAC,Node \\
--enable-bootstrap-token-auth=true \\
--token-auth-file=/data/kubernetes/config/token.csv \\
--service-node-port-range=30000-60000 \\
--kubelet-client-certificate=/data/kubernetes/pki/kube-apiserver.pem \\
--kubelet-client-key=/data/kubernetes/pki/kube-apiserver-key.pem \\
--tls-cert-file=/data/kubernetes/pki/kube-apiserver.pem  \\
--tls-private-key-file=/data/kubernetes/pki/kube-apiserver-key.pem \\
--client-ca-file=/data/kubernetes/pki/ca.pem \\
--service-account-key-file=/data/kubernetes/pki/ca-key.pem \\
--service-account-issuer=https://kubernetes.default.svc.cluster.local \\
--service-account-signing-key-file=/data/kubernetes/pki/ca-key.pem \\
--etcd-cafile=/data/etcd/cert/ca.pem \\
--etcd-certfile=/data/etcd/cert/etcd.pem \\
--etcd-keyfile=/data/etcd/cert/etcd-key.pem \\
--requestheader-client-ca-file=/data/kubernetes/pki/ca.pem \\
--proxy-client-cert-file=/data/kubernetes/pki/kube-apiserver.pem \\
--proxy-client-key-file=/data/kubernetes/pki/kube-apiserver-key.pem \\
--requestheader-allowed-names=kubernetes \\
--requestheader-extra-headers-prefix=X-Remote-Extra- \\
--requestheader-group-headers=X-Remote-Group \\
--requestheader-username-headers=X-Remote-User \\
--enable-aggregator-routing=true \\
--audit-log-maxage=30 \\
--audit-log-maxbackup=3 \\
--audit-log-maxsize=100 \\
--audit-log-path=/data/kubernetes/logs/audit.log"
EOF
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/service/kube-apiserver.service << EOF
[Unit]
Description=Kubernetes API Server
Documentation=https://github.com/kubernetes/kubernetes

[Service]
EnvironmentFile=/data/kubernetes/config/kube-apiserver.conf
ExecStart=/data/kubernetes/bin/kube-apiserver \$KUBE_APISERVER_OPTS
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
[root@YonXin-SIT-Master01 ~]# cp /data/kubernetes/service/kube-apiserver.service /usr/lib/systemd/system/
[root@YonXin-SIT-Master01 ~]# systemctl enable kube-apiserver && systemctl restart kube-apiserver

9.5 创建kube-controller-manager启动配置和脚本

[root@YonXin-SIT-Master01 ~]# KUBE_CONFIG="/data/kubernetes/config/kube-controller-manager.kubeconfig" 
KUBE_APISERVER="https://10.0.0.8:5443" 
kubectl config set-cluster kubernetes \
  --certificate-authority=/data/kubernetes/pki/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials kube-controller-manager \
  --client-certificate=/data/kubernetes/pki/kube-controller-manager.pem \
  --client-key=/data/kubernetes/pki/kube-controller-manager-key.pem \
  --embed-certs=true \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \
  --cluster=kubernetes \
  --user=kube-controller-manager \
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/config/kube-controller-manager.conf << EOF
KUBE_CONTROLLER_MANAGER_OPTS="--logtostderr=false \\
--v=2 \\
--leader-elect=true \\
--kubeconfig=/data/kubernetes/config/kube-controller-manager.kubeconfig \\
--bind-address=127.0.0.1 \\
--allocate-node-cidrs=true \\
--cluster-cidr=10.244.0.0/16 \\
--service-cluster-ip-range=10.96.0.0/16 \\
--cluster-signing-cert-file=/data/kubernetes/pki/ca.pem \\
--cluster-signing-key-file=/data/kubernetes/pki/ca-key.pem  \\
--root-ca-file=/data/kubernetes/pki/ca.pem \\
--service-account-private-key-file=/data/kubernetes/pki/ca-key.pem \\
--cluster-signing-duration=876000h0m0s"
EOF
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/service/kube-controller-manager.service << EOF
[Unit]
Description=Kubernetes Controller Manager
Documentation=https://github.com/kubernetes/kubernetes

[Service]
EnvironmentFile=/data/kubernetes/config/kube-controller-manager.conf
ExecStart=/data/kubernetes/bin/kube-controller-manager \$KUBE_CONTROLLER_MANAGER_OPTS
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
[root@YonXin-SIT-Master01 ~]# cp /data/kubernetes/service/kube-controller-manager.service /usr/lib/systemd/system/
[root@YonXin-SIT-Master01 ~]# systemctl enable kube-controller-manager && systemctl restart kube-controller-manager

9.6 创建kube-scheduler启动配置和脚本

[root@YonXin-SIT-Master01 ~]# KUBE_CONFIG="/data/kubernetes/config/kube-scheduler.kubeconfig"
KUBE_APISERVER="https://10.0.0.8:5443"
kubectl config set-cluster kubernetes \
  --certificate-authority=/data/kubernetes/pki/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials kube-scheduler \
  --client-certificate=/data/kubernetes/pki/kube-scheduler.pem \
  --client-key=/data/kubernetes/pki/kube-scheduler-key.pem \
  --embed-certs=true \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \
  --cluster=kubernetes \
  --user=kube-scheduler \
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/config/kube-scheduler.conf << EOF
KUBE_SCHEDULER_OPTS="--logtostderr=false \\
--v=2 \\
--leader-elect \\
--kubeconfig=/data/kubernetes/config/kube-scheduler.kubeconfig \\
--bind-address=127.0.0.1"
EOF
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/service/kube-scheduler.service << EOF
[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/kubernetes/kubernetes

[Service]
EnvironmentFile=/data/kubernetes/config/kube-scheduler.conf
ExecStart=/data/kubernetes/bin/kube-scheduler \$KUBE_SCHEDULER_OPTS
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
[root@YonXin-SIT-Master01 ~]# cp /data/kubernetes/service/kube-scheduler.service /usr/lib/systemd/system/
[root@YonXin-SIT-Master01 ~]# systemctl enable kube-scheduler && systemctl restart kube-scheduler

9.7 创建kubectl连接配置文件

[root@YonXin-SIT-Master01 ~]# KUBE_CONFIG="/data/kubernetes/config/kubectl.kubeconfig"
KUBE_APISERVER="https://10.0.0.8:5443"
kubectl config set-cluster kubernetes \
  --certificate-authority=/data/kubernetes/pki/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials cluster-admin \
  --client-certificate=/data/kubernetes/pki/kubectl.pem \
  --client-key=/data/kubernetes/pki/kubectl-key.pem \
  --embed-certs=true \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \
  --cluster=kubernetes \
  --user=cluster-admin \
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}
[root@YonXin-SIT-Master01 ~]# mkdir -p $HOME/.kube && sudo cp -i /data/kubernetes/config/kubectl.kubeconfig  $HOME/.kube/config
[root@YonXin-SIT-Master01 ~]# sudo chown $(id -u):$(id -g) $HOME/.kube/config                         //生成kubectl(重要)

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

[root@YonXin-SIT-Master01 ~]# kubectl create clusterrolebinding kubelet-bootstrap --clusterrole=system:node-bootstrapper --user=kubelet-bootstrap

9.9 创建kubelet启动配置和脚本

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/config/kubelet.conf << EOF
KUBELET_OPTS="--logtostderr=false \\
--v=2 \\
--hostname-override=YonXin-SIT-Master01 \\
--cluster-domain=cluster.local \\
--kubeconfig=/data/kubernetes/config/kubelet.kubeconfig \\
--bootstrap-kubeconfig=/data/kubernetes/config/kubelet-bootstrap.kubeconfig \\
--config=/data/kubernetes/config/kubelet-config.yml \\
--cert-dir=/data/kubernetes/pki \\
--container-runtime=remote  \\
--runtime-request-timeout=3m  \\
--container-runtime-endpoint=unix:///run/containerd/containerd.sock  \\
--cgroup-driver=systemd \\
--feature-gates=IPv6DualStack=true"
EOF
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/config/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.96.0.10
clusterDomain: cluster.local 
failSwapOn: false
authentication:
  anonymous:
    enabled: false
  webhook:
    cacheTTL: 2m0s
    enabled: true
  x509:
    clientCAFile: /data/kubernetes/pki/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: 500
EOF
[root@YonXin-SIT-Master01 ~]# KUBE_CONFIG="/data/kubernetes/config/kubelet-bootstrap.kubeconfig"
KUBE_APISERVER="https://10.0.0.8:5443" # apiserver IP:PORT
kubectl config set-cluster kubernetes \
  --certificate-authority=/data/kubernetes/pki/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials "kubelet-bootstrap" \
  --token=$(awk -F "," '{print $1}' /data/kubernetes/config/token.csv) \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \
  --cluster=kubernetes \
  --user="kubelet-bootstrap" \
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/service/kubelet.service << EOF
[Unit]
Description=Kubernetes Kubelet
After=docker.service

[Service]
EnvironmentFile=/data/kubernetes/config/kubelet.conf
ExecStart=/data/kubernetes/bin/kubelet \$KUBELET_OPTS
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF
[root@YonXin-SIT-Master01 ~]# cp /data/kubernetes/service/kubelet.service  /usr/lib/systemd/system/
[root@YonXin-SIT-Master01 ~]# systemctl enable kubelet && systemctl restart kubelet && systemctl status kubelet

9.10 创建kube-proxy启动配置和脚本

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/config/kube-proxy.conf << EOF
KUBE_PROXY_OPTS="--logtostderr=false \\
--v=2 \\
--config=/data/kubernetes/config/kube-proxy-config.yml"
EOF
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/config/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: /data/kubernetes/config/kube-proxy.kubeconfig
hostnameOverride: YonXin-SIT-Master01
clusterCIDR: 10.244.0.0/16
mode: ipvs
ipvs:
  scheduler: "rr"
iptables:
  masqueradeAll: true
EOF
[root@YonXin-SIT-Master01 ~]# KUBE_CONFIG="/data/kubernetes/config/kube-proxy.kubeconfig"
KUBE_APISERVER="https://10.0.0.8:5443"
kubectl config set-cluster kubernetes \
  --certificate-authority=/data/kubernetes/pki/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-credentials kube-proxy \
  --client-certificate=/data/kubernetes/pki/kube-proxy.pem \
  --client-key=/data/kubernetes/pki/kube-proxy-key.pem \
  --embed-certs=true \
  --kubeconfig=${KUBE_CONFIG}
kubectl config set-context default \
  --cluster=kubernetes \
  --user=kube-proxy \
  --kubeconfig=${KUBE_CONFIG}
kubectl config use-context default --kubeconfig=${KUBE_CONFIG}
[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/service/kube-proxy.service << EOF
[Unit]
Description=Kubernetes Proxy
After=network.target

[Service]
EnvironmentFile=/data/kubernetes/config/kube-proxy.conf
ExecStart=/data/kubernetes/bin/kube-proxy \$KUBE_PROXY_OPTS
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF
[root@YonXin-SIT-Master01 ~]# cp /data/kubernetes/service/kube-proxy.service  /usr/lib/systemd/system/
[root@YonXin-SIT-Master01 ~]# systemctl enable kube-proxy && systemctl restart kube-proxy

9.11 批准kubelete证书申请并加入集群

[root@YonXin-SIT-Master01 ~]# kubectl get csr                 //查看kubelet证书请求(重要)                      
[root@YonXin-SIT-Master01 ~]# kubectl certificate approve     node-csr-XXXXXXXX           //批准kubelet证书申请(重要)
[root@YonXin-SIT-Master01 ~]# kubectl get cs && kubectl get sa -A && kubectl get ns -A && kubectl get role -A //查看资源
[root@YonXin-SIT-Master01 ~]# kubectl label node [nodename] node-role.kubernetes.io/master=                 //给master打标签
[root@YonXin-SIT-Master01 ~]# kubectl label node [nodename] node-role.kubernetes.io/ingress=                 //给master打标签

9.12 配置kubectl命令补全功能

[root@YonXin-SIT-Master01 ~]# yum -y install  bash-completion
chmod +x /usr/share/bash-completion/bash_completion
/usr/share/bash-completion/bash_completion
source /usr/share/bash-completion/bash_completion
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> /etc/bashrc

9.13 授权apiserver访问kubelet

[root@YonXin-SIT-Master01 ~]# cat > /data/kubernetes/yaml/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@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/apiserver-to-kubelet-rbac.yaml

9.14 配置calico功能

calico.yaml百度网盘下载链接:https://pan.baidu.com/s/1c5CaBpm5C-7xHuNQ9W7bqA 提取码:tpkt

[root@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/calico.yaml

9.15 配置coredns功能

[root@YonXin-SIT-Master01 ~]# vim /data/kubernetes/yaml/coredns.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: coredns
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: system:coredns
rules:
- apiGroups:
  - ""
  resources:
  - endpoints
  - services
  - pods
  - namespaces
  verbs:
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: system:coredns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:coredns
subjects:
- kind: ServiceAccount
  name: coredns
  namespace: kube-system
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
data:
  Corefile: |
    .:53 {
        errors
        health {
          lameduck 5s
        }
        ready
        kubernetes cluster.local in-addr.arpa ip6.arpa {
          fallthrough in-addr.arpa ip6.arpa
        }
        prometheus :9153
        forward . /etc/resolv.conf {
          max_concurrent 1000
        }
        cache 30
        loop
        reload
        loadbalance
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coredns
  namespace: kube-system
  labels:
    k8s-app: kube-dns
    kubernetes.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: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
  replicas: 2
  selector:
    matchLabels:
      k8s-app: kube-dns
  template:
    metadata:
      labels:
        k8s-app: kube-dns
    spec:
      priorityClassName: system-cluster-critical
      serviceAccountName: coredns
      tolerations:
        - key: "CriticalAddonsOnly"
          operator: "Exists"
      nodeSelector:
        kubernetes.io/os: linux
      affinity:
         podAntiAffinity:
           preferredDuringSchedulingIgnoredDuringExecution:
           - weight: 100
             podAffinityTerm:
               labelSelector:
                 matchExpressions:
                   - key: k8s-app
                     operator: In
                     values: ["kube-dns"]
               topologyKey: kubernetes.io/hostname
      containers:
      - name: coredns
        image: registry.cn-beijing.aliyuncs.com/dotbalo/coredns:1.7.0
        imagePullPolicy: IfNotPresent
        resources:
          limits:
            memory: 170Mi
          requests:
            cpu: 100m
            memory: 70Mi
        args: [ "-conf", "/etc/coredns/Corefile" ]
        volumeMounts:
        - name: config-volume
          mountPath: /etc/coredns
          readOnly: true
        ports:
        - containerPort: 53
          name: dns
          protocol: UDP
        - containerPort: 53
          name: dns-tcp
          protocol: TCP
        - containerPort: 9153
          name: metrics
          protocol: TCP
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            add:
            - NET_BIND_SERVICE
            drop:
            - all
          readOnlyRootFilesystem: true
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 60
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
        readinessProbe:
          httpGet:
            path: /ready
            port: 8181
            scheme: HTTP
      dnsPolicy: Default
      volumes:
        - name: config-volume
          configMap:
            name: coredns
            items:
            - key: Corefile
              path: Corefile
---
apiVersion: v1
kind: Service
metadata:
  name: kube-dns
  namespace: kube-system
  annotations:
    prometheus.io/port: "9153"
    prometheus.io/scrape: "true"
  labels:
    k8s-app: kube-dns
    kubernetes.io/cluster-service: "true"
    kubernetes.io/name: "CoreDNS"
spec:
  selector:
    k8s-app: kube-dns
  clusterIP: 10.96.0.10
  ports:
  - name: dns
    port: 53
    protocol: UDP
  - name: dns-tcp
    port: 53
    protocol: TCP
  - name: metrics
    port: 9153
    protocol: TCP
[root@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/coredns.yaml

9.16 配置dashboard功能

[root@YonXin-SIT-Master01 ~]# vim /data/kubernetes/yaml/dashboard.yaml
# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: Namespace
metadata:
  name: kubernetes-dashboard

---

apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kubernetes-dashboard

---

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

---

apiVersion: v1
kind: Secret
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard-certs
  namespace: kubernetes-dashboard
type: Opaque

---

apiVersion: v1
kind: Secret
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard-csrf
  namespace: kubernetes-dashboard
type: Opaque
data:
  csrf: ""

---

apiVersion: v1
kind: Secret
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard-key-holder
  namespace: kubernetes-dashboard
type: Opaque

---

kind: ConfigMap
apiVersion: v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard-settings
  namespace: kubernetes-dashboard

---

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kubernetes-dashboard
rules:
  # Allow Dashboard to get, update and delete Dashboard exclusive secrets.
  - apiGroups: [""]
    resources: ["secrets"]
    resourceNames: ["kubernetes-dashboard-key-holder", "kubernetes-dashboard-certs", "kubernetes-dashboard-csrf"]
    verbs: ["get", "update", "delete"]
    # Allow Dashboard to get and update 'kubernetes-dashboard-settings' config map.
  - apiGroups: [""]
    resources: ["configmaps"]
    resourceNames: ["kubernetes-dashboard-settings"]
    verbs: ["get", "update"]
    # Allow Dashboard to get metrics.
  - 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
  name: kubernetes-dashboard
rules:
  # Allow Metrics Scraper to get metrics from the Metrics server
  - 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
  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
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:
      securityContext:
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: kubernetes-dashboard
          image: kubernetesui/dashboard:v2.5.1
          imagePullPolicy: Always
          ports:
            - containerPort: 8443
              protocol: TCP
          args:
            - --auto-generate-certificates
            - --namespace=kubernetes-dashboard
            # Uncomment the following line to manually specify Kubernetes API server Host
            # If not specified, Dashboard will attempt to auto discover the API server and connect
            # to it. Uncomment only if the default does not work.
            # - --apiserver-host=http://my-address:port
          volumeMounts:
            - name: kubernetes-dashboard-certs
              mountPath: /certs
              # Create on-disk volume to store exec logs
            - 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
      # Comment the following tolerations if Dashboard must not be deployed on master
      tolerations:
        - 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.7
          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
      # Comment the following tolerations if Dashboard must not be deployed on master
      tolerations:
        - key: node-role.kubernetes.io/master
          effect: NoSchedule
      volumes:
        - name: tmp-volume
          emptyDir: {}
[root@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/dashboard.yaml
[root@YonXin-SIT-Master01 ~]# vim /data/kubernetes/yaml/dashboard-user.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kubernetes-dashboard
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kubernetes-dashboard
[root@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/dashboard-user.yaml
[root@YonXin-SIT-Master01 ~]# kubectl -n kubernetes-dashboard create token admin-user

9.17 配置nginx-ingress-controller功能

vim /data/kubernetes/yaml/nginx-ingress-controller.yaml

apiVersion: v1
kind: Namespace
metadata:
  labels:
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  name: ingress-nginx
---
apiVersion: v1
automountServiceAccountToken: true
kind: ServiceAccount
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx
  namespace: ingress-nginx
---
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx
  namespace: ingress-nginx
rules:
- apiGroups:
  - ""
  resources:
  - namespaces
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - configmaps
  - pods
  - secrets
  - endpoints
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - services
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses/status
  verbs:
  - update
- apiGroups:
  - networking.k8s.io
  resources:
  - ingressclasses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resourceNames:
  - ingress-controller-leader
  resources:
  - configmaps
  verbs:
  - get
  - update
- apiGroups:
  - ""
  resources:
  - configmaps
  verbs:
  - create
- apiGroups:
  - ""
  resources:
  - events
  verbs:
  - create
  - patch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission
  namespace: ingress-nginx
rules:
- apiGroups:
  - ""
  resources:
  - secrets
  verbs:
  - get
  - create
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx
rules:
- apiGroups:
  - ""
  resources:
  - configmaps
  - endpoints
  - nodes
  - pods
  - secrets
  - namespaces
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - get
- apiGroups:
  - ""
  resources:
  - services
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - events
  verbs:
  - create
  - patch
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses/status
  verbs:
  - update
- apiGroups:
  - networking.k8s.io
  resources:
  - ingressclasses
  verbs:
  - get
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission
rules:
- apiGroups:
  - admissionregistration.k8s.io
  resources:
  - validatingwebhookconfigurations
  verbs:
  - get
  - update
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx
  namespace: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: ingress-nginx
subjects:
- kind: ServiceAccount
  name: ingress-nginx
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission
  namespace: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: ingress-nginx-admission
subjects:
- kind: ServiceAccount
  name: ingress-nginx-admission
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: ingress-nginx
subjects:
- kind: ServiceAccount
  name: ingress-nginx
  namespace: ingress-nginx
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: ingress-nginx-admission
subjects:
- kind: ServiceAccount
  name: ingress-nginx-admission
  namespace: ingress-nginx
---
apiVersion: v1
data:
  allow-snippet-annotations: "true"
kind: ConfigMap
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-controller
  namespace: ingress-nginx
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  ports:
  - appProtocol: http
    name: http
    port: 80
    protocol: TCP
    targetPort: http
  - appProtocol: https
    name: https
    port: 443
    protocol: TCP
    targetPort: https
  selector:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  type: ClusterIP
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-controller-admission
  namespace: ingress-nginx
spec:
  ports:
  - appProtocol: https
    name: https-webhook
    port: 443
    targetPort: webhook
  selector:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  type: ClusterIP
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  minReadySeconds: 0
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app.kubernetes.io/component: controller
      app.kubernetes.io/instance: ingress-nginx
      app.kubernetes.io/name: ingress-nginx
  template:
    metadata:
      labels:
        app.kubernetes.io/component: controller
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/name: ingress-nginx
    spec:
      hostNetwork: true
      containers:
      - args:
        - /nginx-ingress-controller
#        - --publish-service=$(POD_NAMESPACE)/ingress-nginx-controller
        - --election-id=ingress-controller-leader
        - --controller-class=k8s.io/ingress-nginx
        - --ingress-class=nginx
        - --configmap=$(POD_NAMESPACE)/ingress-nginx-controller
        - --validating-webhook=:8443
        - --validating-webhook-certificate=/usr/local/certificates/cert
        - --validating-webhook-key=/usr/local/certificates/key
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: LD_PRELOAD
          value: /usr/local/lib/libmimalloc.so
        image: registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-ingress-controller:v1.0.0
        imagePullPolicy: IfNotPresent
        lifecycle:
          preStop:
            exec:
              command:
              - /wait-shutdown
        livenessProbe:
          failureThreshold: 5
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        name: controller
        ports:
        - containerPort: 80
          name: http
          protocol: TCP
        - containerPort: 443
          name: https
          protocol: TCP
        - containerPort: 8443
          name: webhook
          protocol: TCP
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        resources:
          requests:
            cpu: 100m
            memory: 90Mi
        securityContext:
          allowPrivilegeEscalation: true
          capabilities:
            add:
            - NET_BIND_SERVICE
            drop:
            - ALL
          runAsUser: 101
        volumeMounts:
        - mountPath: /usr/local/certificates/
          name: webhook-cert
          readOnly: true
      dnsPolicy: ClusterFirst
      nodeSelector:
        kubernetes.io/os: linux
        node-role.kubernetes.io/ingress: ""
      serviceAccountName: ingress-nginx
      terminationGracePeriodSeconds: 300
      volumes:
      - name: webhook-cert
        secret:
          secretName: ingress-nginx-admission
---
apiVersion: batch/v1
kind: Job
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission-create
  namespace: ingress-nginx
spec:
  template:
    metadata:
      labels:
        app.kubernetes.io/component: admission-webhook
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/part-of: ingress-nginx
        app.kubernetes.io/version: 1.2.0
      name: ingress-nginx-admission-create
    spec:
      containers:
      - args:
        - create
        - --host=ingress-nginx-controller-admission,ingress-nginx-controller-admission.$(POD_NAMESPACE).svc
        - --namespace=$(POD_NAMESPACE)
        - --secret-name=ingress-nginx-admission
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        image: registry.cn-hangzhou.aliyuncs.com/google_containers/kube-webhook-certgen:v1.0
        imagePullPolicy: IfNotPresent
        name: create
        securityContext:
          allowPrivilegeEscalation: false
      nodeSelector:
        kubernetes.io/os: linux
      restartPolicy: OnFailure
      securityContext:
        fsGroup: 2000
        runAsNonRoot: true
        runAsUser: 2000
      serviceAccountName: ingress-nginx-admission
---
apiVersion: batch/v1
kind: Job
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission-patch
  namespace: ingress-nginx
spec:
  template:
    metadata:
      labels:
        app.kubernetes.io/component: admission-webhook
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/part-of: ingress-nginx
        app.kubernetes.io/version: 1.2.0
      name: ingress-nginx-admission-patch
    spec:
      containers:
      - args:
        - patch
        - --webhook-name=ingress-nginx-admission
        - --namespace=$(POD_NAMESPACE)
        - --patch-mutating=false
        - --secret-name=ingress-nginx-admission
        - --patch-failure-policy=Fail
        env:
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        image: registry.cn-hangzhou.aliyuncs.com/google_containers/kube-webhook-certgen:v1.0
        imagePullPolicy: IfNotPresent
        name: patch
        securityContext:
          allowPrivilegeEscalation: false
      nodeSelector:
        kubernetes.io/os: linux
      restartPolicy: OnFailure
      securityContext:
        fsGroup: 2000
        runAsNonRoot: true
        runAsUser: 2000
      serviceAccountName: ingress-nginx-admission
---
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: nginx
spec:
  controller: k8s.io/ingress-nginx
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  labels:
    app.kubernetes.io/component: admission-webhook
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
    app.kubernetes.io/version: 1.2.0
  name: ingress-nginx-admission
webhooks:
- admissionReviewVersions:
  - v1
  clientConfig:
    service:
      name: ingress-nginx-controller-admission
      namespace: ingress-nginx
      path: /networking/v1/ingresses
  failurePolicy: Fail
  matchPolicy: Equivalent
  name: validate.nginx.ingress.kubernetes.io
  rules:
  - apiGroups:
    - networking.k8s.io
    apiVersions:
    - v1
    operations:
    - CREATE
    - UPDATE
    resources:
    - ingresses
  sideEffects: None
[root@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/nginx-ingress-controller.yaml
[root@YonXin-SIT-Master01 ~]# vim /data/kubernetes/yaml/test-nginx.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx-pod
  template:
    metadata:
      labels:
        app: nginx-pod
    spec:
      containers:
      - name: nginx
        image: nginx:1.17.1
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  namespace: default
spec:
  type: ClusterIP
  ports:
    - port: 80
      name: nginx
  selector:
    app: nginx-pod
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  namespace: default
spec:
  ingressClassName: nginx  #必须存在,否则ingress状态下Address字段无法显示NodeIP!
  rules:
  - host: "test-nginx.k8s-ingress.com"
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: nginx-service
            port:
              number: 80
---
[root@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/test-nginx.yaml
[root@YonXin-SIT-Master01 ~]# vim /data/kubernetes/yaml/test-tomcat.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcat-deployment
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tomcat-pod
  template:
    metadata:
      labels:
        app: tomcat-pod
    spec:
      containers:
      - name: tomcat
        image: tomcat:8.5-jre10-slim
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: tomcat-service
  namespace: default
spec:
  type: NodePort
  ports:
    - port: 8080
      name: tomcat
  selector:
    app: tomcat-pod
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: tomcat-ingress
  namespace: default
spec:
  ingressClassName: nginx  #必须存在,否则ingress状态下Address字段无法显示NodeIP!
  rules:
  - host: "test-tomcat.k8s-ingress.com"
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: tomcat-service
            port:
              number: 8080
---
[root@YonXin-SIT-Master01 ~]# kubectl apply -f /data/kubernetes/yaml/test-tomcat.yaml

(1) 在本地电脑上配置hosts解析www.yonxin100.com域名IP为前端nginx主机的IP
C:\Windows\System32\drivers\etc\hosts
10.0.0.4 www.yonxin100.com

(2) 访问nginx代理ingress的nginx域名服务http://www.yonxin100.com/nginx/
在这里插入图片描述
(3) 访问nginx代理ingress的tomcat域名服务http://www.yonxin100.com/tomcat/
在这里插入图片描述

10. 安装其他k8s-master服务

部署Master0X 节点:将Master01所有K8s文件拷贝,删除如下文件,修改涉及配置启动所有服务即可~

[root@YonXin-SIT-Master02 ~]# rm -f /data/kubernetes/config/kubelet.kubeconfig && rm -f /data/kubernetes/pki/kubelet*
[root@YonXin-SIT-Master02 ~]# kubectl get csr                                                                          //查看kubelet证书请求(重要)
[root@YonXin-SIT-Master02 ~]# kubectl certificate approve     node-csr-XXXXXXXX           //批准kubelet证书申请(重要)

11. 安装新的k8s-node服务

部署新Node节点:将Master01所有K8s文件拷贝,删除如下文件,修改kubelet/kube-proxy配置启动服务~

[root@YonXin-SIT-node01 ~]# rm -f /data/kubernetes/config/kubelet.kubeconfig && rm -f /data/kubernetes/pki/kubelet* 
[root@YonXin-SIT-node01 ~]# kubectl get csr                                                                          //查看kubelet证书请求(重要)
[root@YonXin-SIT-node01 ~]# kubectl certificate approve     node-csr-XXXXXXXX           //批准kubelet证书申请(重要)
[root@YonXin-SIT-node01 ~]# kubectl label node [nodename] node-role.kubernetes.io/node=                   //给node打标签

12. 日常运维服务

12.1 如何把受损的etcd重新添加到集群

1.删除受损节点的成员信息
[root@YonXin-SIT-Master01 ~]# etcdctl --endpoints="https://10.0.0.1:2379" --cacert=/data/etcd/cert/ca.pem --cert=/data/etcd/cert/etcd.pem --key=/data/etcd/cert/etcd-key.pem member remove fde9dd315b6d0b2
2.在受损节点上删除--data-dir存储的数据
[root@YonXin-SIT-Master02 ~]# rm -rf /data/etcd/data/*
3.在受损节点上重新加入集群
[root@YonXin-SIT-Master02 ~]# etcdctl member add etcd2 --peer-urls="https://10.0.0.2:2380" --endpoints="https://10.0.0.1:2379" --cacert=/data/etcd/cert/ca.pem --cert=/data/etcd/cert/etcd.pem --key=/data/etcd/cert/etcd-key.pem
4.修改受损节点etcd启动参数
将etcd.service的--initial-cluster-state启动参数,改为--initial-cluster-state=existing
5.重启受损节点服务
[root@YonXin-SIT-Master02 ~]# service etcd restart

12.2 如何监控K8S集群系统

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值