常见的K8S安装部署方式:

  • Minikube 单节点微型K8S (仅供学习、预览使用)
  • 二进制安装部署(生产首选,新手推荐)
  • 使用kubeadmin进行部署, K8S的部署工具,跑在K8S里(相对简单,熟手推荐)

    二进制安装

    这里的部署文档基于阿里云服务器 文中有一些附件形式的软件包可以直接下载 由于上附件需要更多的空间 如果有需要注册语雀的朋友 可以点击我的邀请链接注册(会送我一点空间)

image.png

安装前准备

相关目录 /opt 二进制服务安装路径 /opt/src 二进制包放置路径

环境准备

所有机器都需要执行

  1. ~]# uname -a (内核版本最低需要3.10)
  2. Linux alice40 3.10.0-957.21.3.el7.x86_64 #1 SMP Tue Jun 18 16:35:19 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
  3. ~]# systemctl stop firewalld
  4. ~]# systemctl disable firewalld
  5. ~]# setenforce 0
  6. ~]# sed -ir '/^SELINUX=/s/=.+/=disabled/' /etc/selinux/config
  7. ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
  8. ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
  9. ~]# yum install -y wget net-tools telnet tree nmap sysstat lrzsz dos2unix bind-utils vim less
  10. ~]# 都需要配置定时任务
  11. ~]# crontab -l
  12. #ntp
  13. 00 * * * * /usr/sbin/ntpdate ntp6.aliyun.com

bind安装

hdss7-11 安装bind

 ~]# yum install -y bind

主配置文件
注意语法(分号空格)这里的IP是内网IP

 ~]# vim /etc/named.conf  # 确保以下配置正确
    listen-on port 53 { 10.4.7.11; }; # 监听端口53 下面一行本来有ipv6地址 需要删除
    directory     "/var/named";
    allow-query     { any; }; #允许内机器都可以查
  forwarders      { 10.4.7.254; }; # 上级dns 虚拟机这里填的是网关地址,阿里云机器可以填223.5.5.5
  recursion yes; # 采用递归方法查询IP
  dnssec-enable no;
  dnssec-validation no;
 ~]# named-checkconf # 检查配置  没有信息即为正确
 ~]#

在 hdss7-11.host.com 配置区域文件

# 增加两个zone配置,od.com为业务域,host.com.zone为主机域
 ~]# vim /etc/named.rfc1912.zones  
zone "host.com" IN {
        type  master;
        file  "host.com.zone";
        allow-update { 10.4.7.11; };
};

zone "od.com" IN {
        type  master;
        file  "od.com.zone";
        allow-update { 10.4.7.11; };
};

在 hdss7-11.host.com 配置主机域文件

# line6中时间需要修改 格式为xxxx xx xx01(年月日01)每次修改配置文件都需要前滚一个序列号
 ~]# vim /var/named/host.com.zone
$ORIGIN host.com.
$TTL 600    ; 10 minutes # 过期时间十分钟 这里的分号是注释
@       IN SOA    dns.host.com. dnsadmin.host.com. (
                2020010501 ; serial
                10800      ; refresh (3 hours) # soa参数
                900        ; retry (15 minutes)
                604800     ; expire (1 week)
                86400      ; minimum (1 day)
                )
            NS   dns.host.com.
$TTL 60    ; 1 minute
dns                A    10.4.7.11
HDSS7-11           A    10.4.7.11
HDSS7-12           A    10.4.7.12
HDSS7-21           A    10.4.7.21
HDSS7-22           A    10.4.7.22
HDSS7-200          A    10.4.7.200

在 hdss7-11.host.com 配置业务域文件

 ~]# vim /var/named/od.com.zone
$ORIGIN od.com.
$TTL 600    ; 10 minutes
@           IN SOA    dns.od.com. dnsadmin.od.com. (
                2020010501 ; serial
                10800      ; refresh (3 hours)
                900        ; retry (15 minutes)
                604800     ; expire (1 week)
                86400      ; minimum (1 day)
                )
                NS   dns.od.com.
$TTL 60    ; 1 minute
dns                A    10.4.7.11

在 hdss7-11.host.com 启动bind服务,并测试

[root@hdss7-11 ~]# named-checkconf  # 检查配置文件
[root@hdss7-11 ~]# systemctl start named ; systemctl enable named
[root@hdss7-11 ~]# dig -t A hdss7-11.host.com  @10.4.7.11 +shor #检查是否可以解析到
10.4.7.11

修改主机DNS

  • 修改所有主机的dns服务器地址
    [root@alice001 resume]# cat /etc/sysconfig/network-scripts/ifcfg-eth0 
    DEVICE=eth0
    BOOTPROTO=dhcp
    ONBOOT=yes
    DNS1=172.23.187.175
    [root@alice001 resume]#
    [root@hdss7-11 ~]# systemctl restart network
    [root@hdss7-11 ~]# cat /etc/resolv.conf
    # Generated by NetworkManager
    search host.com #添加后解析主机A记录 可以不加域名 例如 dig -t A hdss7-11  @10.4.7.11 +short
    nameserver 172.23.187.175
    

根证书准备

  • 在 hdss7-200 下载工具
    [root@hdss7-200 ~]# wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 -O /usr/local/bin/cfssl
    [root@hdss7-200 ~]# wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64 -O /usr/local/bin/cfssl-json
    [root@hdss7-200 ~]# wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64 -O /usr/local/bin/cfssl-certinfo
    [root@hdss7-200 ~]# chmod u+x /usr/local/bin/cfssl*
    

在 hdss7-200 签发根证书

 ~]# mkdir /opt/certs/ ; cd /opt/certs/
 certs]# vim /opt/certs/ca-csr.json
{
    "CN": "OldboyEdu",
    "hosts": [
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ],
    "ca": {
        "expiry": "175200h"  # 过期时间(20年)
    }
}
 certs]# cfssl gencert -initca ca-csr.json | cfssl-json -bare ca
2020/01/05 10:42:07 [INFO] generating a new CA key and certificate from CSR
2020/01/05 10:42:07 [INFO] generate received request
2020/01/05 10:42:07 [INFO] received CSR
2020/01/05 10:42:07 [INFO] generating key: rsa-2048
2020/01/05 10:42:08 [INFO] encoded CSR
2020/01/05 10:42:08 [INFO] signed certificate with serial number 451005524427475354617025362003367427117323539780
 certs]# ls -l ca*
-rw-r--r-- 1 root root  993 Jan  5 10:42 ca.csr
-rw-r--r-- 1 root root  328 Jan  5 10:39 ca-csr.json
-rw------- 1 root root 1675 Jan  5 10:42 ca-key.pem
-rw-r--r-- 1 root root 1346 Jan  5 10:42 ca.pem

CN: Common Name ,浏览器使用该字段验证网站是否合法, 一般写的是域名。非常重要。浏览器使 用该字段验证网站是否合法C: Country,国家ST:State,州,省L: Locality ,地区,城市O: Organization Name ,组织名称,公司名称OU: Organization Unit Name ,组织单位名称,公司部门

docker环境准备

需要安装docker的机器:hdss7-21 hdss7-22 hdss7-200,以hdss7-21为例

 bip需要改为 172.xx.xx.1/24 这里的xx.xx是主机内网IP的后两段
 ~]# wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
 ~]# yum install -y docker-ce
 ~]# mkdir /etc/docker/
 ~]# vim /etc/docker/daemon.json
{
  "graph": "/data/docker",
  "storage-driver": "overlay2",
  "insecure-registries": ["registry.access.redhat.com","quay.io","harbor.od.com"],
  "registry-mirrors": ["https://registry.docker-cn.com"],
  "bip": "172.7.21.1/24",
  "exec-opts": ["native.cgroupdriver=systemd"],
  "live-restore": true
}
 ~]# mkdir /data/docker
 ~]# systemctl start docker ; systemctl enable docker
 ~]# docker version # 检查版本

配置详情解释请参考: 戳我
如果需要安装指定版本的docker

查看软件版本yum list docker-ce.x86_64 --showduplicates | sort -r
安装对应版本软件yum install -y docker-ce-18.09.9 docker-ce-cli-18.09.9 containerd.io

一条命令安装docker

curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

harbor安装

官方地址:https://goharbor.io/
下载地址:https://github.com/goharbor/harbor/releases
注意 不要选择1.7.5以下版本 有漏洞
下载的时候下载harbor-offline-installer-vx.x.x.tgz版本(离线安装版本)
harbor-offline-installer-v1.8.0.tgz
harbor-offline-installer-v1.8.5.tgz

安装harbor

 ~]# cd /opt/src
 src]# wget https://github.com/goharbor/harbor/releases/download/v1.9.4/harbor-offline-installer-v1.9.4.tgz
 src]# mv harbor /opt/harbor-v1.9.4
 src]# ln -s /opt/harbor-v1.9.4 /opt/harbor
 src]# ll /opt/
total 0
lrwxrwxrwx 1 root root 26 Jan  5 11:13 harbor -> /opt/harbor-v1.9.4
# 实验环境仅修改以下配置项,生产环境还得修改密码
 src]# vim /opt/harbor/harbor.yml
hostname: harbor.od.com
http:
  port: 180
data_volume: /data/harbor
location: /data/harbor/logs
 src]# yum install -y docker-compose
 src]# cd /opt/harbor/
 harbor]# ./install.sh 
......
✔ ----Harbor has been installed and started successfully.----
 harbor]# docker-compose ps 
      Name                     Command               State             Ports          
--------------------------------------------------------------------------------------
harbor-core         /harbor/harbor_core              Up                               
harbor-db           /docker-entrypoint.sh            Up      5432/tcp                 
harbor-jobservice   /harbor/harbor_jobservice  ...   Up                               
harbor-log          /bin/sh -c /usr/local/bin/ ...   Up      127.0.0.1:1514->10514/tcp
harbor-portal       nginx -g daemon off;             Up      8080/tcp                 
nginx               nginx -g daemon off;             Up      0.0.0.0:180->8080/tcp    
redis               redis-server /etc/redis.conf     Up      6379/tcp                 
registry            /entrypoint.sh /etc/regist ...   Up      5000/tcp                 
registryctl         /harbor/start.sh                 Up
  • 设置harbor开机启动

    [root@hdss7-200 harbor]# vim /etc/rc.d/rc.local  # 增加以下内容
    # start harbor
    cd /opt/harbor
    /usr/docker-compose stop
    /usr/docker-compose start
    

    hdss7-200 安装nginx

  • 安装Nginx反向代理harbor

这里如果用的是阿里云 记得在安全组放行80端口

# 当前机器中Nginx功能较少,使用yum安装即可。如有多个harbor考虑源码编译且配置健康检查
# nginx配置此处忽略,仅仅使用最简单的配置。
 harbor]# vim /etc/nginx/conf.d/harbor.conf
 harbor]# cat /etc/nginx/conf.d/harbor.conf
server {
    listen       80;
    server_name  harbor.od.com;
    # 避免出现上传失败的情况
    client_max_body_size 1000m;

    location / {
        proxy_pass http://127.0.0.1:180;
    }
} harbor]# systemctl start nginx ; systemctl enable nginx
  • hdss7-11 配置DNS解析

    ~]# vim /var/named/od.com.zone  # 序列号需要滚动一个
    $ORIGIN od.com.
    $TTL 600    ; 10 minutes
    @           IN SOA    dns.od.com. dnsadmin.od.com. (
                  2020010502 ; serial
                  10800      ; refresh (3 hours)
                  900        ; retry (15 minutes)
                  604800     ; expire (1 week)
                  86400      ; minimum (1 day)
                  )
                  NS   dns.od.com.
    $TTL 60    ; 1 minute
    dns                A    10.4.7.11
    harbor             A    10.4.7.200
    ~]# systemctl restart named.service  # reload 无法使得配置生效
    ~]# host harbor.od.com
    harbor.od.com has address 10.4.7.200
    

    image.png

  • 新建项目: public

image.png

  • 测试harbor

    ~]# docker pull nginx:1.7.9
    ~]# docker tag nginx:1.7.9  harbor.od.com/public/nginx:v1.7.9
    ~]# docker login -u admin harbor.od.com
    ~]# docker push harbor.od.com/public/nginx:v1.7.9
    ~]# docker logout
    

    image.png

    主控节点安装

    etcd安装

    etcd 的leader选举机制,要求至少为3台或以上的奇数台。本次安装涉及:hdss7-12,hdss7-21,hdss7-22

    签发etcd证书

    证书签发服务器 hdss7-200:

  • 创建ca的json配置: /opt/certs/ca-config.json

    • server 表示服务端连接客户端时携带的证书,用于客户端验证服务端身份
    • client 表示客户端连接服务端时携带的证书,用于服务端验证客户端身份
    • peer 表示相互之间连接时使用的证书,如etcd节点之间验证

"expiry": "175200h" 证书有效期 十年 如果这里是一年的话 到期后集群会立宕掉

{
    "signing": {
        "default": {
            "expiry": "175200h"
        },
        "profiles": {
            "server": {
                "expiry": "175200h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth"
                ]
            },
            "client": {
                "expiry": "175200h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "client auth"
                ]
            },
            "peer": {
                "expiry": "175200h",
                "usages": [
                    "signing",
                    "key encipherment",
                    "server auth",
                    "client auth"
                ]
            }
        }
    }
}
  • 创建etcd证书配置:/opt/certs/etcd-peer-csr.json

重点在hosts上,将所有可能的etcd服务器添加到host列表,不能使用网段,新增etcd服务器需要重新签发证书

{
    "CN": "k8s-etcd",
    "hosts": [
        "10.4.7.11",
        "10.4.7.12",
        "10.4.7.21",
        "10.4.7.22"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ]
}
  • 签发证书

    [root@hdss7-200 ~]# cd /opt/certs/
    [root@hdss7-200 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=peer etcd-peer-csr.json |cfssl-json -bare etcd-peer
    [root@hdss7-200 certs]# ll etcd-peer*
    -rw-r--r-- 1 root root 1062 Jan  5 17:01 etcd-peer.csr
    -rw-r--r-- 1 root root  363 Jan  5 16:59 etcd-peer-csr.json
    -rw------- 1 root root 1675 Jan  5 17:01 etcd-peer-key.pem
    -rw-r--r-- 1 root root 1428 Jan  5 17:01 etcd-peer.pem
    

    安装etcd

    etcd地址:https://github.com/etcd-io/etcd/
    实验使用版本: etcd-v3.1.20-linux-amd64.tar.gz
    etcd-v3.1.20-linux-amd64.tar.gz
    本次安装涉及:hdss7-12,hdss7-21,hdss7-22

  • 下载etcd

    [root@hdss7-12 ~]# useradd -s /sbin/nologin -M etcd
    [root@hdss7-12 ~]# cd /opt/src/
    [root@hdss7-12 src]# wget https://github.com/etcd-io/etcd/releases/download/v3.1.20/etcd-v3.1.20-linux-amd64.tar.gz
    [root@hdss7-12 src]# tar -xf etcd-v3.1.20-linux-amd64.tar.gz 
    [root@hdss7-12 src]# mv etcd-v3.1.20-linux-amd64 /opt/etcd-v3.1.20
    [root@hdss7-12 src]# ln -s /opt/etcd-v3.1.20 /opt/etcd
    [root@hdss7-12 src]# ll /opt/etcd
    lrwxrwxrwx 1 root root 25 Jan  5 17:56 /opt/etcd -> /opt/etcd-v3.1.20
    [root@hdss7-12 src]# mkdir -p /opt/etcd/certs /data/etcd /data/logs/etcd-server
    
  • 下发证书到各个etcd上

    ~]# cd /opt/certs/
    certs]# for i in 12 21 22;do scp ca.pem etcd-peer.pem etcd-peer-key.pem hdss7-${i}:/opt/etcd/certs/ ;done
    
[root@hdss7-12 src]# md5sum /opt/etcd/certs/*
8778d0c3411891af61a287e49a70c89a  /opt/etcd/certs/ca.pem
7918783c2f6bf69e96edf03e67d04983  /opt/etcd/certs/etcd-peer-key.pem
d4d849751a834c7727d42324fdedf92d  /opt/etcd/certs/etcd-peer.pem
  • 创建启动脚本(部分参数每台机器不同) ```bash ~]# vim /opt/etcd/etcd-server-startup.sh

    !/bin/sh

    listen-peer-urls etcd节点之间通信端口

    listen-client-urls 客户端与etcd通信端口

    quota-backend-bytes 配额大小

    需要修改的参数:name,listen-peer-urls,listen-client-urls,initial-advertise-peer-urls

WORK_DIR=$(dirname $(readlink -f $0)) [ $? -eq 0 ] && cd $WORK_DIR || exit

/opt/etcd/etcd —name etcd-server-7-12 \ —data-dir /data/etcd/etcd-server \ —listen-peer-urls https://10.4.7.12:2380 \ —listen-client-urls https://10.4.7.12:2379,http://127.0.0.1:2379 \ —quota-backend-bytes 8000000000 \ —initial-advertise-peer-urls https://10.4.7.12:2380 \ —advertise-client-urls https://10.4.7.12:2379,http://127.0.0.1:2379 \ —initial-cluster etcd-server-7-12=https://10.4.7.12:2380,etcd-server-7-21=https://10.4.7.21:2380,etcd-server-7-22=https://10.4.7.22:2380 \ —ca-file ./certs/ca.pem \ —cert-file ./certs/etcd-peer.pem \ —key-file ./certs/etcd-peer-key.pem \ —client-cert-auth \ —trusted-ca-file ./certs/ca.pem \ —peer-ca-file ./certs/ca.pem \ —peer-cert-file ./certs/etcd-peer.pem \ —peer-key-file ./certs/etcd-peer-key.pem \ —peer-client-cert-auth \ —peer-trusted-ca-file ./certs/ca.pem \ —log-output stdout



~]# chmod u+x /opt/etcd/etcd-server-startup.sh ~]# chown -R etcd.etcd /opt/etcd/ /data/etcd /data/logs/etcd-server

<a name="UGdjQ"></a>
#### 启动etcd
因为这些进程都是要启动为后台进程,要么手动启动,要么采用后台进程管理工具,实验中使用后台管理工具

~]# yum install -y supervisor ~]# systemctl start supervisord ; systemctl enable supervisord ~]# vim /etc/supervisord.d/etcd-server.ini [program:etcd-server-7-12] command=/opt/etcd/etcd-server-startup.sh ; the program (relative uses PATH, can take args) numprocs=1 ; number of processes copies to start (def 1) directory=/opt/etcd ; directory to cwd to before exec (def no cwd) autostart=true ; start at supervisord start (default: true) autorestart=true ; retstart at unexpected quit (default: true) startsecs=30 ; number of secs prog must stay running (def. 1) startretries=3 ; max # of serial start failures (default 3) exitcodes=0,2 ; ‘expected’ exit codes for process (default 0,2) stopsignal=QUIT ; signal used to kill process (default TERM) stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10) user=etcd ; setuid to this UNIX account to run the program redirect_stderr=true ; redirect proc stderr to stdout (default false) stdout_logfile=/data/logs/etcd-server/etcd.stdout.log ; stdout log path, NONE for none; default AUTO stdout_logfile_maxbytes=64MB ; max # logfile bytes b4 rotation (default 50MB) stdout_logfile_backups=5 ; # of stdout logfile backups (default 10) stdout_capture_maxbytes=1MB ; number of bytes in ‘capturemode’ (default 0) stdout_events_enabled=false ; emit events on stdout writes (default false) ~]# supervisorctl update etcd-server-7-12: added process group


- etcd 进程状态查看

~]# supervisorctl status # supervisorctl 状态 etcd-server-7-12 RUNNING pid 22375, uptime 0:00:39

~]# netstat -lntp|grep etcd tcp 0 0 10.4.7.12:2379 0.0.0.0: LISTEN 22379/etcd
tcp 0 0 127.0.0.1:2379 0.0.0.0:
LISTEN 22379/etcd
tcp 0 0 10.4.7.12:2380 0.0.0.0:* LISTEN 22379/etcd

~]# /opt/etcd/etcdctl member list # 随着etcd重启,leader会变化 988139385f78284: name=etcd-server-7-22 peerURLs=https://10.4.7.22:2380 clientURLs=http://127.0.0.1:2379,https://10.4.7.22:2379 isLeader=false 5a0ef2a004fc4349: name=etcd-server-7-21 peerURLs=https://10.4.7.21:2380 clientURLs=http://127.0.0.1:2379,https://10.4.7.21:2379 isLeader=true f4a0cb0a765574a8: name=etcd-server-7-12 peerURLs=https://10.4.7.12:2380 clientURLs=http://127.0.0.1:2379,https://10.4.7.12:2379 isLeader=false

~]# /opt/etcd/etcdctl cluster-health member 988139385f78284 is healthy: got healthy result from http://127.0.0.1:2379 member 5a0ef2a004fc4349 is healthy: got healthy result from http://127.0.0.1:2379 member f4a0cb0a765574a8 is healthy: got healthy result from http://127.0.0.1:2379 cluster is healthy


- etcd 启停方式

~]# supervisorctl start etcd-server-7-12 ~]# supervisorctl stop etcd-server-7-12 ~]# supervisorctl restart etcd-server-7-12 ~]# supervisorctl status etcd-server-7-12

<a name="zic0e"></a>
### apiserver 安装
<a name="G9D3U"></a>
#### 下载kubernetes服务端
aipserver 涉及的服务器:hdss7-21,hdss7-22<br />下载 kubernetes 二进制版本包需要科学上网工具

- 进入kubernetes的github页面: [https://github.com/kubernetes/kubernetes](https://github.com/kubernetes/kubernetes)
- 进入tags页签: [https://github.com/kubernetes/kubernetes/tags](https://github.com/kubernetes/kubernetes/tags)
- 选择要下载的版本: [https://github.com/kubernetes/kubernetes/releases/tag/v1.15.2](https://github.com/kubernetes/kubernetes/releases/tag/v1.15.2)
- 点击 CHANGELOG-${version}.md  进入说明页面: [https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG-1.15.md#downloads-for-v1152](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG-1.15.md#downloads-for-v1152)
- 下载Server Binaries: [https://dl.k8s.io/v1.15.2/kubernetes-server-linux-amd64.tar.gz](https://dl.k8s.io/v1.15.2/kubernetes-server-linux-amd64.tar.gz)

[kubernetes-server-linux-amd64.tar.gz](https://www.yuque.com/attachments/yuque/0/2021/gz/2392831/1612088268719-cf070c15-2a63-49e8-88af-2e35749fef93.gz?_lake_card=%7B%22uid%22%3A%221612088017224-0%22%2C%22src%22%3A%22https%3A%2F%2Fwww.yuque.com%2Fattachments%2Fyuque%2F0%2F2021%2Fgz%2F2392831%2F1612088268719-cf070c15-2a63-49e8-88af-2e35749fef93.gz%22%2C%22name%22%3A%22kubernetes-server-linux-amd64.tar.gz%22%2C%22size%22%3A443770238%2C%22type%22%3A%22application%2Fgzip%22%2C%22ext%22%3A%22gzip%22%2C%22progress%22%3A%7B%22percent%22%3A99%7D%2C%22status%22%3A%22done%22%2C%22percent%22%3A0%2C%22id%22%3A%22KJFz2%22%2C%22card%22%3A%22file%22%7D)

~]# cd /opt/src src]# wget https://dl.k8s.io/v1.15.2/kubernetes-server-linux-amd64.tar.gz

src]# tar -xf kubernetes-server-linux-amd64.tar.gz src]# mv kubernetes /opt/kubernetes-v1.15.2 src]# ln -s /opt/kubernetes-v1.15.2 /opt/kubernetes src]# ll /opt/kubernetes lrwxrwxrwx 1 root root 31 Jan 6 12:59 /opt/kubernetes -> /opt/kubernetes-v1.15.2

src]# cd /opt/kubernetes kubernetes]# rm -f kubernetes-src.tar.gz 源代码文件 kubernetes]# cd server/bin/ bin]# rm -f .tar _tag # .tar _tag 镜像文件 bin]# ll total 884636 -rwxr-xr-x 1 root root 43534816 Aug 5 18:01 apiextensions-apiserver -rwxr-xr-x 1 root root 100548640 Aug 5 18:01 cloud-controller-manager -rwxr-xr-x 1 root root 200648416 Aug 5 18:01 hyperkube -rwxr-xr-x 1 root root 40182208 Aug 5 18:01 kubeadm -rwxr-xr-x 1 root root 164501920 Aug 5 18:01 kube-apiserver -rwxr-xr-x 1 root root 116397088 Aug 5 18:01 kube-controller-manager -rwxr-xr-x 1 root root 42985504 Aug 5 18:01 kubectl -rwxr-xr-x 1 root root 119616640 Aug 5 18:01 kubelet -rwxr-xr-x 1 root root 36987488 Aug 5 18:01 kube-proxy -rwxr-xr-x 1 root root 38786144 Aug 5 18:01 kube-scheduler -rwxr-xr-x 1 root root 1648224 Aug 5 18:01 mounter

<a name="ChFxb"></a>
#### 签发证书
签发证书 涉及的服务器:hdss7-200

- 签发client证书(apiserver和etcd通信证书)

[root@hdss7-200 ~]# cd /opt/certs/ [root@hdss7-200 certs]# vim /opt/certs/client-csr.json { “CN”: “k8s-node”, “hosts”: [ ], “key”: { “algo”: “rsa”, “size”: 2048 }, “names”: [ { “C”: “CN”, “ST”: “beijing”, “L”: “beijing”, “O”: “od”, “OU”: “ops” } ] } certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=client client-csr.json |cfssl-json -bare client 2020/01/06 13:42:47 [INFO] generate received request 2020/01/06 13:42:47 [INFO] received CSR 2020/01/06 13:42:47 [INFO] generating key: rsa-2048 2020/01/06 13:42:47 [INFO] encoded CSR 2020/01/06 13:42:47 [INFO] signed certificate with serial number 268276380983442021656020268926931973684313260543 2020/01/06 13:42:47 [WARNING] This certificate lacks a “hosts” field. This makes it unsuitable for websites. For more information see the Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org); specifically, section 10.2.3 (“Information Requirements”). certs]# ls client* -l -rw-r—r— 1 root root 993 Jan 6 13:42 client.csr -rw-r—r— 1 root root 280 Jan 6 13:42 client-csr.json -rw———- 1 root root 1679 Jan 6 13:42 client-key.pem -rw-r—r— 1 root root 1363 Jan 6 13:42 client.pem


- 签发server证书(apiserver和其它k8s组件通信使用)

hosts中将所有可能作为apiserver的ip添加进去,VIP 10.4.7.10 也要加入

[root@hdss7-200 certs]# vim /opt/certs/apiserver-csr.json { “CN”: “k8s-apiserver”, “hosts”: [ “127.0.0.1”, “192.168.0.1”, “kubernetes.default”, “kubernetes.default.svc”, “kubernetes.default.svc.cluster”, “kubernetes.default.svc.cluster.local”, “10.4.7.10”, “10.4.7.21”, “10.4.7.22”, “10.4.7.23” ], “key”: { “algo”: “rsa”, “size”: 2048 }, “names”: [ { “C”: “CN”, “ST”: “beijing”, “L”: “beijing”, “O”: “od”, “OU”: “ops” } ] } [root@hdss7-200 certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=server apiserver-csr.json |cfssl-json -bare apiserver 2020/01/06 13:46:56 [INFO] generate received request 2020/01/06 13:46:56 [INFO] received CSR 2020/01/06 13:46:56 [INFO] generating key: rsa-2048 2020/01/06 13:46:56 [INFO] encoded CSR 2020/01/06 13:46:56 [INFO] signed certificate with serial number 573076691386375893093727554861295529219004473872 2020/01/06 13:46:56 [WARNING] This certificate lacks a “hosts” field. This makes it unsuitable for websites. For more information see the Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org); specifically, section 10.2.3 (“Information Requirements”). [root@hdss7-200 certs]# ls apiserver* -l -rw-r—r— 1 root root 1249 Jan 6 13:46 apiserver.csr -rw-r—r— 1 root root 566 Jan 6 13:45 apiserver-csr.json -rw———- 1 root root 1675 Jan 6 13:46 apiserver-key.pem -rw-r—r— 1 root root 1598 Jan 6 13:46 apiserver.pem


- 证书下发

certs]# for i in 21 22;do echo hdss7-$i;ssh hdss7-$i “mkdir /opt/kubernetes/server/bin/certs”;scp apiserver-key.pem apiserver.pem ca-key.pem ca.pem client-key.pem client.pem hdss7-$i:/opt/kubernetes/server/bin/certs/;done

<a name="ya6eY"></a>
#### 配置apiserver日志审计
aipserver 涉及的服务器:hdss7-21,hdss7-22

bin]# mkdir /opt/kubernetes/conf bin]# vim /opt/kubernetes/conf/audit.yaml # 打开文件后,设置 :set paste,避免自动缩进 apiVersion: audit.k8s.io/v1beta1 # This is required. kind: Policy

Don’t generate audit events for all requests in RequestReceived stage.

omitStages:

  • “RequestReceived” rules:

    Log pod changes at RequestResponse level

  • level: RequestResponse resources:
    • group: “”

      Resource “pods” doesn’t match requests to any subresource of pods,

      which is consistent with the RBAC policy.

      resources: [“pods”]

      Log “pods/log”, “pods/status” at Metadata level

  • level: Metadata resources:

    • group: “” resources: [“pods/log”, “pods/status”]

    Don’t log requests to a configmap called “controller-leader”

  • level: None resources:

    • group: “” resources: [“configmaps”] resourceNames: [“controller-leader”]

    Don’t log watch requests by the “system:kube-proxy” on endpoints or services

  • level: None users: [“system:kube-proxy”] verbs: [“watch”] resources:

    • group: “” # core API group resources: [“endpoints”, “services”]

    Don’t log authenticated requests to certain non-resource URL paths.

  • level: None userGroups: [“system:authenticated”] nonResourceURLs:

    • “/api*” # Wildcard matching.
    • “/version”

    Log the request body of configmap changes in kube-system.

  • level: Request resources:

    • group: “” # core API group resources: [“configmaps”]

      This rule only applies to resources in the “kube-system” namespace.

      The empty string “” can be used to select non-namespaced resources.

      namespaces: [“kube-system”]

    Log configmap and secret changes in all other namespaces at the Metadata level.

  • level: Metadata resources:

    • group: “” # core API group resources: [“secrets”, “configmaps”]

    Log all other resources in core and extensions at the Request level.

  • level: Request resources:

    • group: “” # core API group
    • group: “extensions” # Version of group should NOT be included.

    A catch-all rule to log all other requests at the Metadata level.

  • level: Metadata

    Long-running requests like watches that fall under this rule will not

    generate an audit event in RequestReceived.

    omitStages:
    • “RequestReceived” ```

      配置启动脚本

      aipserver 涉及的服务器:hdss7-21,hdss7-22
  • 创建启动脚本
 这里需要修改 --etcd-servers https://10.4.7.12:2379,https://10.4.7.21:2379,https://10.4.7.22:2379 分别三台etcd的地址
 bin]# vim /opt/kubernetes/server/bin/kube-apiserver-startup.sh
#!/bin/bash

WORK_DIR=$(dirname $(readlink -f $0))
[ $? -eq 0 ] && cd $WORK_DIR || exit

/opt/kubernetes/server/bin/kube-apiserver \
    --apiserver-count 2 \
    --audit-log-path /data/logs/kubernetes/kube-apiserver/audit-log \
    --audit-policy-file ../../conf/audit.yaml \
    --authorization-mode RBAC \
    --client-ca-file ./certs/ca.pem \
    --requestheader-client-ca-file ./certs/ca.pem \
    --enable-admission-plugins NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota \
    --etcd-cafile ./certs/ca.pem \
    --etcd-certfile ./certs/client.pem \
    --etcd-keyfile ./certs/client-key.pem \
    --etcd-servers https://10.4.7.12:2379,https://10.4.7.21:2379,https://10.4.7.22:2379 \
    --service-account-key-file ./certs/ca-key.pem \
    --service-cluster-ip-range 192.168.0.0/16 \
    --service-node-port-range 3000-29999 \
    --target-ram-mb=1024 \
    --kubelet-client-certificate ./certs/client.pem \
    --kubelet-client-key ./certs/client-key.pem \
    --log-dir  /data/logs/kubernetes/kube-apiserver \
    --tls-cert-file ./certs/apiserver.pem \
    --tls-private-key-file ./certs/apiserver-key.pem \
    --v 2
  • 配置supervisor启动配置

    bin]# vim /etc/supervisord.d/kube-apiserver.ini
    [program:kube-apiserver-7-21]
    command=/opt/kubernetes/server/bin/kube-apiserver-startup.sh
    numprocs=1
    directory=/opt/kubernetes/server/bin
    autostart=true
    autorestart=true
    startsecs=30
    startretries=3
    exitcodes=0,2
    stopsignal=QUIT
    stopwaitsecs=10
    user=root
    redirect_stderr=true
    stdout_logfile=/data/logs/kubernetes/kube-apiserver/apiserver.stdout.log
    stdout_logfile_maxbytes=64MB
    stdout_logfile_backups=5
    stdout_capture_maxbytes=1MB
    stdout_events_enabled=false
    bin]# mkdir -p /data/logs/kubernetes/kube-apiserver/
    bin]# supervisorctl update
    bin]# supervisorctl status
    etcd-server-7-21                 RUNNING   pid 23637, uptime 22:26:08
    kube-apiserver-7-21              RUNNING   pid 32591, uptime 0:05:37
    
  • 启停apiserver

    ~]# supervisorctl start kube-apiserver-7-21
    ~]# supervisorctl stop kube-apiserver-7-21
    ~]# supervisorctl restart kube-apiserver-7-21
    ~]# supervisorctl status kube-apiserver-7-21
    
  • 查看进程

    bin]# netstat -lntp|grep api
    tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      32595/kube-apiserve 
    tcp6       0      0 :::6443                 :::*                    LISTEN      32595/kube-apiserve 
    bin]# ps uax|grep kube-apiserver|grep -v grep
    root      32591  0.0  0.0 115296  1476 ?        S    20:17   0:00 /bin/bash /opt/kubernetes/server/bin/kube-apiserver-startup.sh
    root      32595  3.0  2.3 402720 184892 ?       Sl   20:17   0:16 /opt/kubernetes/server/bin/kube-apiserver --apiserver-count 2 --audit-log-path /data/logs/kubernetes/kube-apiserver/audit-log --audit-policy-file ../../conf/audit.yaml --authorization-mode RBAC --client-ca-file ./certs/ca.pem --requestheader-client-ca-file ./certs/ca.pem --enable-admission-plugins NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota --etcd-cafile ./certs/ca.pem --etcd-certfile ./certs/client.pem --etcd-keyfile ./certs/client-key.pem --etcd-servers https://10.4.7.12:2379,https://10.4.7.21:2379,https://10.4.7.22:2379 --service-account-key-file ./certs/ca-key.pem --service-cluster-ip-range 192.168.0.0/16 --service-node-port-range 3000-29999 --target-ram-mb=1024 --kubelet-client-certificate ./certs/client.pem --kubelet-client-key ./certs/client-key.pem --log-dir /data/logs/kubernetes/kube-apiserver --tls-cert-file ./certs/apiserver.pem --tls-private-key-file ./certs/apiserver-key.pem --v 2
    

    配置apiserver L4代理

    nginx配置

    这里只做了一台机器 所以没有做keepalived

    ~]# yum install -y nginx
    ~]# vim /etc/nginx/nginx.conf  
    # 末尾加上以下内容,stream 只能加在 main 中
    # 此处只是简单配置下nginx,实际生产中,建议进行更合理的配置
    stream {
      log_format proxy '$time_local|$remote_addr|$upstream_addr|$protocol|$status|'
                       '$session_time|$upstream_connect_time|$bytes_sent|$bytes_received|'
                       '$upstream_bytes_sent|$upstream_bytes_received' ;
    
      upstream kube-apiserver {
          server 10.4.7.21:6443     max_fails=3 fail_timeout=30s;
          server 10.4.7.22:6443     max_fails=3 fail_timeout=30s;
      }
      server {
          listen 7443;
          proxy_connect_timeout 2s;
          proxy_timeout 900s;
          proxy_pass kube-apiserver;
          access_log /var/log/nginx/proxy.log proxy;
      }
    }
    ~]# systemctl start nginx; systemctl enable nginx
    ~]# curl 127.0.0.1:7443  # 测试几次
    Client sent an HTTP request to an HTTPS server.
    ~]# cat /var/log/nginx/proxy.log 
    06/Jan/2020:21:00:27 +0800|127.0.0.1|10.4.7.21:6443|TCP|200|0.001|0.000|76|78|78|76
    06/Jan/2020:21:05:03 +0800|127.0.0.1|10.4.7.22:6443|TCP|200|0.020|0.019|76|78|78|76
    06/Jan/2020:21:05:04 +0800|127.0.0.1|10.4.7.21:6443|TCP|200|0.001|0.001|76|78|78|76
    

    controller-manager 安装

    controller-manager 涉及的服务器:hdss7-21,hdss7-22
    controller-manager 设置为只调用当前机器的 apiserver,走127.0.0.1网卡,因此不配制SSL证书

    配置启动脚本

  • 创建启动脚本

 ~]# vim /opt/kubernetes/server/bin/kube-controller-manager-startup.sh
#!/bin/sh
WORK_DIR=$(dirname $(readlink -f $0))
[ $? -eq 0 ] && cd $WORK_DIR || exit

/opt/kubernetes/server/bin/kube-controller-manager \
    --cluster-cidr 172.7.0.0/16 \
    --leader-elect true \
    --log-dir /data/logs/kubernetes/kube-controller-manager \
    --master http://127.0.0.1:8080 \
    --service-account-private-key-file ./certs/ca-key.pem \
    --service-cluster-ip-range 192.168.0.0/16 \
    --root-ca-file ./certs/ca.pem \
    --v 2
 ~]# chmod u+x /opt/kubernetes/server/bin/kube-controller-manager-startup.sh
  • 配置supervisor启动配置
    ~]# vim /etc/supervisord.d/kube-controller-manager.ini
    [program:kube-controller-manager-7-21]
    command=/opt/kubernetes/server/bin/kube-controller-manager-startup.sh             ; the program (relative uses PATH, can take args)
    numprocs=1                                                                        ; number of processes copies to start (def 1)
    directory=/opt/kubernetes/server/bin                                              ; directory to cwd to before exec (def no cwd)
    autostart=true                                                                    ; start at supervisord start (default: true)
    autorestart=true                                                                  ; retstart at unexpected quit (default: true)
    startsecs=30                                                                      ; number of secs prog must stay running (def. 1)
    startretries=3                                                                    ; max # of serial start failures (default 3)
    exitcodes=0,2                                                                     ; 'expected' exit codes for process (default 0,2)
    stopsignal=QUIT                                                                   ; signal used to kill process (default TERM)
    stopwaitsecs=10                                                                   ; max num secs to wait b4 SIGKILL (default 10)
    user=root                                                                         ; setuid to this UNIX account to run the program
    redirect_stderr=true                                                              ; redirect proc stderr to stdout (default false)
    stdout_logfile=/data/logs/kubernetes/kube-controller-manager/controller.stdout.log  ; stderr log path, NONE for none; default AUTO
    stdout_logfile_maxbytes=64MB                                                      ; max # logfile bytes b4 rotation (default 50MB)
    stdout_logfile_backups=4                                                          ; # of stdout logfile backups (default 10)
    stdout_capture_maxbytes=1MB                                                       ; number of bytes in 'capturemode' (default 0)
    stdout_events_enabled=false                                                       ; emit events on stdout writes (default false)
    
 ~]# supervisorctl update
kube-controller-manager-7-21: stopped
kube-controller-manager-7-21: updated process group
 ~]# supervisorctl status
etcd-server-7-21                 RUNNING   pid 23637, uptime 1 day, 0:16:54
kube-apiserver-7-21              RUNNING   pid 32591, uptime 1:56:23
kube-controller-manager-7-21     RUNNING   pid 33357, uptime 0:00:38

kube-scheduler安装

kube-scheduler 涉及的服务器:hdss7-21,hdss7-22
kube-scheduler 设置为只调用当前机器的 apiserver,走127.0.0.1网卡,因此不配制SSL证书

  • 创建启动脚本 ``` ~]# vim /opt/kubernetes/server/bin/kube-scheduler-startup.sh

    !/bin/sh

    WORK_DIR=$(dirname $(readlink -f $0)) [ $? -eq 0 ] && cd $WORK_DIR || exit

/opt/kubernetes/server/bin/kube-scheduler \ —leader-elect \ —log-dir /data/logs/kubernetes/kube-scheduler \ —master http://127.0.0.1:8080 \ —v 2 ~]# chmod u+x /opt/kubernetes/server/bin/kube-scheduler-startup.sh ~]# mkdir -p /data/logs/kubernetes/kube-scheduler


- 配置supervisor启动配置

~]# vim /etc/supervisord.d/kube-scheduler.ini [program:kube-scheduler-7-21] command=/opt/kubernetes/server/bin/kube-scheduler-startup.sh
numprocs=1
directory=/opt/kubernetes/server/bin
autostart=true
autorestart=true
startsecs=30
startretries=3
exitcodes=0,2
stopsignal=QUIT
stopwaitsecs=10
user=root
redirect_stderr=true
stdout_logfile=/data/logs/kubernetes/kube-scheduler/scheduler.stdout.log stdout_logfile_maxbytes=64MB
stdout_logfile_backups=4
stdout_capture_maxbytes=1MB
stdout_events_enabled=false



~]# supervisorctl update kube-scheduler-7-21: stopped kube-scheduler-7-21: updated process group ~]# supervisorctl status etcd-server-7-21 RUNNING pid 23637, uptime 1 day, 0:26:53 kube-apiserver-7-21 RUNNING pid 32591, uptime 2:06:22 kube-controller-manager-7-21 RUNNING pid 33357, uptime 0:10:37 kube-scheduler-7-21 RUNNING pid 33450, uptime 0:01:18

<a name="qh755"></a>
### 检查主控节点状态

~]# ln -s /opt/kubernetes/server/bin/kubectl /usr/local/bin/ ~]# kubectl get cs NAME STATUS MESSAGE ERROR scheduler Healthy ok
controller-manager Healthy ok
etcd-1 Healthy {“health”: “true”}
etcd-0 Healthy {“health”: “true”}
etcd-2 Healthy {“health”: “true”}

如果这里你只展示一个etcd节点 那就是apiserver那里配置错了  填了同一个etcd的地址  别问我怎么知道的 ![image.png](https://cdn.nlark.com/yuque/0/2021/png/2392831/1612086271239-92a93485-f75a-4d01-af14-9dfdae97a0d9.png#align=left&display=inline&height=37&margin=%5Bobject%20Object%5D&name=image.png&originHeight=37&originWidth=123&size=12023&status=done&style=none&width=123)
<a name="6Tk5j"></a>
## 运算节点部署
<a name="tc2I0"></a>
### kubelet 部署
<a name="840GX"></a>
#### 签发证书
证书签发在 hdss7-200 操作

~]# cd /opt/certs/ certs]# vim kubelet-csr.json # 将所有可能的kubelet机器IP添加到hosts中 { “CN”: “k8s-kubelet”, “hosts”: [ “127.0.0.1”, “10.4.7.10”, “10.4.7.21”, “10.4.7.22”, “10.4.7.23”, “10.4.7.24”, “10.4.7.25”, “10.4.7.26”, “10.4.7.27”, “10.4.7.28” ], “key”: { “algo”: “rsa”, “size”: 2048 }, “names”: [ { “C”: “CN”, “ST”: “beijing”, “L”: “beijing”, “O”: “od”, “OU”: “ops” } ] } certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=server kubelet-csr.json | cfssl-json -bare kubelet 2020/01/06 23:10:56 [INFO] generate received request 2020/01/06 23:10:56 [INFO] received CSR 2020/01/06 23:10:56 [INFO] generating key: rsa-2048 2020/01/06 23:10:56 [INFO] encoded CSR 2020/01/06 23:10:56 [INFO] signed certificate with serial number 61221942784856969738771370531559555767101820379 2020/01/06 23:10:56 [WARNING] This certificate lacks a “hosts” field. This makes it unsuitable for websites. For more information see the Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org); specifically, section 10.2.3 (“Information Requirements”). certs]# ls kubelet* -l -rw-r—r— 1 root root 1115 Jan 6 23:10 kubelet.csr -rw-r—r— 1 root root 452 Jan 6 23:10 kubelet-csr.json -rw———- 1 root root 1675 Jan 6 23:10 kubelet-key.pem -rw-r—r— 1 root root 1468 Jan 6 23:10 kubelet.pem

certs]# scp kubelet.pem kubelet-key.pem hdss7-21:/opt/kubernetes/server/bin/certs/ certs]# scp kubelet.pem kubelet-key.pem hdss7-22:/opt/kubernetes/server/bin/certs/

<a name="03RJ2"></a>
#### 创建kubelet配置
kubelet配置在 hdss7-21 hdss7-22 操作

- set-cluster  # 创建需要连接的集群信息,可以创建多个k8s集群信息

~]# kubectl config set-cluster myk8s \ —certificate-authority=/opt/kubernetes/server/bin/certs/ca.pem \ —embed-certs=true \ —server=https://172.23.187.175:7443 \ —kubeconfig=/opt/kubernetes/conf/kubelet.kubeconfig


- set-credentials  # 创建用户账号,即用户登陆使用的客户端私有和证书,可以创建多个证书

~]# kubectl kubectl config set-credentials k8s-node \ —client-certificate=/opt/kubernetes/server/bin/certs/client.pem \ —client-key=/opt/kubernetes/server/bin/certs/client-key.pem \ —embed-certs=true \ —kubeconfig=/opt/kubernetes/conf/kubelet.kubeconfig


- set-context  # 设置context,即确定账号和集群对应关系

[root@hdss7-21 ~]# kubectl config set-context myk8s-context \ —cluster=myk8s \ —user=k8s-node \ —kubeconfig=/opt/kubernetes/conf/kubelet.kubeconfig


- use-context  # 设置当前使用哪个context

~]# kubectl config use-context myk8s-context —kubeconfig=/opt/kubernetes/conf/kubelet.kubeconfig


把此配置文件传给另一台就不用做以上四步

scp /opt/kubernetes/conf/kubelet.kubeconfig hdss7-22:/opt/kubernetes/conf/

<a name="q5NaY"></a>
#### 授权k8s-node用户
**此步骤只需要在一台master节点执行**<br />授权 k8s-node 用户绑定集群角色 system:node ,让 k8s-node 成为具备运算节点的权限。

~]# vim k8s-node.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: k8s-node roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: system:node subjects:

  • apiGroup: rbac.authorization.k8s.io kind: User name: k8s-node ~]# kubectl create -f k8s-node.yaml clusterrolebinding.rbac.authorization.k8s.io/k8s-node created ~]# kubectl get clusterrolebinding k8s-node NAME AGE k8s-node 36s
    <a name="RChx7"></a>
    #### 装备pause镜像
    将pause镜像放入到harbor私有仓库中,仅在 hdss7-200 操作:
    
    ~]# docker image pull kubernetes/pause ~]# docker image tag kubernetes/pause:latest harbor.od.com/public/pause:latest ~]# docker login -u admin harbor.od.com ~]# docker image push harbor.od.com/public/pause:latest
    <a name="DkJ3g"></a>
    #### 创建启动脚本
    在node节点创建脚本并启动kubelet,涉及服务器: hdss7-21  hdss7-22
    
    ~]# vim /opt/kubernetes/server/bin/kubelet-startup.sh

    !/bin/sh

WORK_DIR=$(dirname $(readlink -f $0)) [ $? -eq 0 ] && cd $WORK_DIR || exit

/opt/kubernetes/server/bin/kubelet \ —anonymous-auth=false \ —cgroup-driver systemd \ —cluster-dns 192.168.0.2 \ —cluster-domain cluster.local \ —runtime-cgroups=/systemd/system.slice \ —kubelet-cgroups=/systemd/system.slice \ —fail-swap-on=”false” \ —client-ca-file ./certs/ca.pem \ —tls-cert-file ./certs/kubelet.pem \ —tls-private-key-file ./certs/kubelet-key.pem \ —hostname-override hdss7-21.host.com \ —image-gc-high-threshold 20 \ —image-gc-low-threshold 10 \ —kubeconfig ../../conf/kubelet.kubeconfig \ —log-dir /data/logs/kubernetes/kube-kubelet \ —pod-infra-container-image harbor.od.com/public/pause:latest \ —root-dir /data/kubelet ~]# chmod u+x /opt/kubernetes/server/bin/kubelet-startup.sh ~]# mkdir -p /data/logs/kubernetes/kube-kubelet /data/kubelet

~]# vim /etc/supervisord.d/kube-kubelet.ini [program:kube-kubelet-7-21] command=/opt/kubernetes/server/bin/kubelet-startup.sh numprocs=1 directory=/opt/kubernetes/server/bin autostart=true autorestart=true startsecs=30 startretries=3 exitcodes=0,2 stopsignal=QUIT stopwaitsecs=10 user=root redirect_stderr=true stdout_logfile=/data/logs/kubernetes/kube-kubelet/kubelet.stdout.log stdout_logfile_maxbytes=64MB stdout_logfile_backups=5 stdout_capture_maxbytes=1MB stdout_events_enabled=false



~]# supervisorctl update ~]# supervisorctl status etcd-server-7-21 RUNNING pid 23637, uptime 1 day, 14:56:25 kube-apiserver-7-21 RUNNING pid 32591, uptime 16:35:54 kube-controller-manager-7-21 RUNNING pid 33357, uptime 14:40:09 kube-kubelet-7-21 RUNNING pid 37232, uptime 0:01:08 kube-scheduler-7-21 RUNNING pid 33450, uptime 14:30:50 ~]# kubectl get node NAME STATUS ROLES AGE VERSION hdss7-21.host.com Ready 3m13s v1.15.2 hdss7-22.host.com Ready 3m13s v1.15.2

<a name="uzNPY"></a>
#### 修改节点角色
使用 kubectl get nodes 获取的Node节点角色为空,可以按照以下方式修改

~]# kubectl get node NAME STATUS ROLES AGE VERSION hdss7-21.host.com Ready 3m13s v1.15.2 hdss7-22.host.com Ready 3m13s v1.15.2 ~]# kubectl label node hdss7-21.host.com node-role.kubernetes.io/node= node/hdss7-21.host.com labeled ~]# kubectl label node hdss7-21.host.com node-role.kubernetes.io/master= node/hdss7-21.host.com labeled ~]# kubectl label node hdss7-22.host.com node-role.kubernetes.io/master= node/hdss7-22.host.com labeled ~]# kubectl label node hdss7-22.host.com node-role.kubernetes.io/node= node/hdss7-22.host.com labeled ~]# kubectl get node NAME STATUS ROLES AGE VERSION hdss7-21.host.com Ready master,node 7m44s v1.15.2 hdss7-22.host.com Ready master,node 7m44s v1.15.2

<a name="F0OWJ"></a>
### kube-proxy部署
<a name="oUoud"></a>
#### 签发证书
证书签发在 hdss7-200 操作

[root@hdss7-200 ~]# cd /opt/certs/ [root@hdss7-200 certs]# vim kube-proxy-csr.json # CN 其实是k8s中的角色 { “CN”: “system:kube-proxy”, “key”: { “algo”: “rsa”, “size”: 2048 }, “names”: [ { “C”: “CN”, “ST”: “beijing”, “L”: “beijing”, “O”: “od”, “OU”: “ops” } ] } certs]# cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=client kube-proxy-csr.json |cfssl-json -bare kube-proxy-client 2020/01/07 21:45:53 [INFO] generate received request 2020/01/07 21:45:53 [INFO] received CSR 2020/01/07 21:45:53 [INFO] generating key: rsa-2048 2020/01/07 21:45:53 [INFO] encoded CSR 2020/01/07 21:45:53 [INFO] signed certificate with serial number 620191685968917036075463174423999296907693104226 2020/01/07 21:45:53 [WARNING] This certificate lacks a “hosts” field. This makes it unsuitable for websites. For more information see the Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org); certs]# ls kube-proxy-c* -l # 因为kube-proxy使用的用户是kube-proxy,不能使用client证书,必须要重新签发自己的证书 -rw-r—r— 1 root root 1005 Jan 7 21:45 kube-proxy-client.csr -rw———- 1 root root 1675 Jan 7 21:45 kube-proxy-client-key.pem -rw-r—r— 1 root root 1375 Jan 7 21:45 kube-proxy-client.pem -rw-r—r— 1 root root 267 Jan 7 21:45 kube-proxy-csr.json

certs]# scp kube-proxy-client-key.pem kube-proxy-client.pem hdss7-21:/opt/kubernetes/server/bin/certs/ 100% 1375 870.6KB/s 00:00
certs]# scp kube-proxy-client-key.pem kube-proxy-client.pem hdss7-22:/opt/kubernetes/server/bin/certs/

<a name="LDq8L"></a>
#### 创建kube-proxy配置
在所有node节点创建,涉及服务器:hdss7-21 ,hdss7-22

这里—server=https://10.4.7.10:7443 需要修改位反代的ip地址 ~]# kubectl config set-cluster myk8s \ —certificate-authority=/opt/kubernetes/server/bin/certs/ca.pem \ —embed-certs=true \ —server=https://172.23.187.175:7443 \ —kubeconfig=/opt/kubernetes/conf/kube-proxy.kubeconfig

~]# kubectl config set-credentials kube-proxy \ —client-certificate=/opt/kubernetes/server/bin/certs/kube-proxy-client.pem \ —client-key=/opt/kubernetes/server/bin/certs/kube-proxy-client-key.pem \ —embed-certs=true \ —kubeconfig=/opt/kubernetes/conf/kube-proxy.kubeconfig

~]# kubectl config set-context myk8s-context \ —cluster=myk8s \ —user=kube-proxy \ —kubeconfig=/opt/kubernetes/conf/kube-proxy.kubeconfig

~]# kubectl config use-context myk8s-context —kubeconfig=/opt/kubernetes/conf/kube-proxy.kubeconfig

把生成配置文件传到另一台机器 那边就可以不用做以上四步

conf]# scp kube-proxy.kubeconfig hdss7-22:/opt/kubernetes/conf/

<a name="ZnQJk"></a>
#### 加载ipvs模块
kube-proxy 共有3种流量调度模式,分别是 namespace,iptables,ipvs,其中ipvs性能最好。

[root@hdss7-21 ~]# for i in $(ls /usr/lib/modules/$(uname -r)/kernel/net/netfilter/ipvs|grep -o “^[^.]*”);do echo $i; /sbin/modinfo -F filename $i >/dev/null 2>&1 && /sbin/modprobe $i;done [root@hdss7-21 ~]# lsmod | grep ip_vs # 查看ipvs模块

<a name="oTBhP"></a>
#### 创建启动脚本

—hostname-override 需要修改为主机名

~]# vim /opt/kubernetes/server/bin/kube-proxy-startup.sh

!/bin/sh

WORK_DIR=$(dirname $(readlink -f $0)) [ $? -eq 0 ] && cd $WORK_DIR || exit

/opt/kubernetes/server/bin/kube-proxy \ —cluster-cidr 172.7.0.0/16 \ —hostname-override hdss7-21.host.com \ —proxy-mode=ipvs \ —ipvs-scheduler=nq \ —kubeconfig ../../conf/kube-proxy.kubeconfig ~]# chmod u+x /opt/kubernetes-v1.15.2/server/bin/kube-proxy-startup.sh ~]# mkdir -p /data/logs/kubernetes/kube-proxy

~]# vim /etc/supervisord.d/kube-proxy.ini [program:kube-proxy-7-21] command=/opt/kubernetes/server/bin/kube-proxy-startup.sh
numprocs=1
directory=/opt/kubernetes/server/bin
autostart=true
autorestart=true
startsecs=30
startretries=3
exitcodes=0,2
stopsignal=QUIT
stopwaitsecs=10
user=root
redirect_stderr=true
stdout_logfile=/data/logs/kubernetes/kube-proxy/proxy.stdout.log stdout_logfile_maxbytes=64MB
stdout_logfile_backups=5
stdout_capture_maxbytes=1MB
stdout_events_enabled=false

~]# supervisorctl update

<a name="GtBRc"></a>
#### 验证集群

~]# supervisorctl status etcd-server-7-21 RUNNING pid 23637, uptime 2 days, 0:27:18 kube-apiserver-7-21 RUNNING pid 32591, uptime 1 day, 2:06:47 kube-controller-manager-7-21 RUNNING pid 33357, uptime 1 day, 0:11:02 kube-kubelet-7-21 RUNNING pid 37232, uptime 9:32:01 kube-proxy-7-21 RUNNING pid 47088, uptime 0:06:19 kube-scheduler-7-21 RUNNING pid 33450, uptime 1 day, 0:01:43

~]# yum install -y ipvsadm ~]# ipvsadm -Ln IP Virtual Server version 1.2.1 (size=4096) Prot LocalAddress:Port Scheduler Flags -> RemoteAddress:Port Forward Weight ActiveConn InActConn TCP 192.168.0.1:443 nq -> 10.4.7.21:6443 Masq 1 0 0
-> 10.4.7.22:6443 Masq 1 0 0 ~]# kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 192.168.0.1 443/TCP 16h

创建yaml文件
```shell
 ~]# cat nginx-ds.yaml 
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata: 
    name: nginx-ds
spec:
    template:
      metadata:
        labels:
          app: nginx-ds
      spec:
        containers:
        - name: my-nginx
          image: harbor.od.com/public/nginx:v1.7.9
          ports: 
          - containerPort: 80

创建资源

 ~]# kubectl create -f  nginx-ds.yaml
daemonset.extensions/nginx-ds created
 ~]# kubectl get pods
NAME             READY   STATUS              RESTARTS   AGE
nginx-ds-5lz6s   0/1     ContainerCreating   0          4s
nginx-ds-cx2bg   0/1     ContainerCreating   0          4s
 ~]# kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-ds-5lz6s   1/1     Running   0          9m14s
nginx-ds-cx2bg   1/1     Running   0          9m14s
 ~]# kubectl get pods -owide
NAME             READY   STATUS    RESTARTS   AGE   IP              NODE                NOMINATED NODE   READINESS GATES
nginx-ds-5lz6s   1/1     Running   0          22m   172.187.173.2   alice002.host.com   <none>           <none>
nginx-ds-cx2bg   1/1     Running   0          22m   172.187.174.2   alice003.host.com   <none>           <none>

这里集群里只有一台登陆了harbor 没搞懂为什么另一台也可以pull到镜像


报错排查

更多报错请查看https://www.yuque.com/grep/k8serror

bind报错network unreachable resolving ‘./DNSKEY/IN’: 2001:dc3::35#53

[root@alice38 named]# systemctl status named
● named.service - Berkeley Internet Name Domain (DNS)
   Loaded: loaded (/usr/lib/systemd/system/named.service; disabled; vendor preset: disabled)
   Active: active (running) since Sat 2021-01-16 19:08:34 CST; 6s ago
  Process: 6008 ExecStop=/bin/sh -c /usr/sbin/rndc stop > /dev/null 2>&1 || /bin/kill -TERM $MAINPID (code=exited, status=0/SUCCESS)
  Process: 6023 ExecStart=/usr/sbin/named -u named -c ${NAMEDCONF} $OPTIONS (code=exited, status=0/SUCCESS)
  Process: 6020 ExecStartPre=/bin/bash -c if [ ! "$DISABLE_ZONE_CHECKING" == "yes" ]; then /usr/sbin/named-checkconf -z "$NAMEDCONF"; else echo "Checking of zone files is disabled"; fi (code=exited, status=0/SUCCESS)
 Main PID: 6026 (named)
    Tasks: 4
   Memory: 52.1M
   CGroup: /system.slice/named.service
           └─6026 /usr/sbin/named -u named -c /etc/named.conf

Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:dc3::35#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:500:9f::42#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:7fd::1#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:500:1::53#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:500:2::c#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:7fe::53#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:503:ba3e::2:30#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:500:2f::f#53
Jan 16 19:08:36 alice38 named[6026]: network unreachable resolving './DNSKEY/IN': 2001:500:2d::d#53
Jan 16 19:08:40 alice38 named[6026]: managed-keys-zone: Key 20326 for zone . acceptance timer complete: key now trusted

解决办法

vi /etc/sysconfig/named

增加一行OPTIONS=”-4”

[root@alice38 named]# cat  /etc/sysconfig/named
# BIND named process options
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# OPTIONS="whatever"     --  These additional options will be passed to named
#                            at startup. Don't add -t here, enable proper
#                            -chroot.service unit file.
#                            Use of parameter -c is not supported here. Extend
#                            systemd named*.service instead. For more
#                            information please read the following KB article:
#                            https://access.redhat.com/articles/2986001
#
# DISABLE_ZONE_CHECKING  --  By default, service file calls named-checkzone
#                            utility for every zone to ensure all zones are
#                            valid before named starts. If you set this option
#                            to 'yes' then service file doesn't perform those
#                            checks.
OPTIONS="-4"

重启

[root@alice38 named]# systemctl restart named
[root@alice38 named]# systemctl status named
● named.service - Berkeley Internet Name Domain (DNS)
   Loaded: loaded (/usr/lib/systemd/system/named.service; disabled; vendor preset: disabled)
   Active: active (running) since Sat 2021-01-16 19:16:53 CST; 1s ago
  Process: 6742 ExecStop=/bin/sh -c /usr/sbin/rndc stop > /dev/null 2>&1 || /bin/kill -TERM $MAINPID (code=exited, status=0/SUCCESS)
  Process: 6756 ExecStart=/usr/sbin/named -u named -c ${NAMEDCONF} $OPTIONS (code=exited, status=0/SUCCESS)
  Process: 6753 ExecStartPre=/bin/bash -c if [ ! "$DISABLE_ZONE_CHECKING" == "yes" ]; then /usr/sbin/named-checkconf -z "$NAMEDCONF"; else echo "Checking of zone files is disabled"; fi (code=exited, status=0/SUCCESS)
 Main PID: 6759 (named)
    Tasks: 4
   Memory: 51.7M
   CGroup: /system.slice/named.service
           └─6759 /usr/sbin/named -u named -c /etc/named.conf -4

Jan 16 19:16:53 alice38 named[6759]: zone 0.in-addr.arpa/IN: loaded serial 0
Jan 16 19:16:53 alice38 named[6759]: zone localhost.localdomain/IN: loaded serial 0
Jan 16 19:16:53 alice38 named[6759]: zone 1.0.0.127.in-addr.arpa/IN: loaded serial 0
Jan 16 19:16:53 alice38 named[6759]: zone localhost/IN: loaded serial 0
Jan 16 19:16:53 alice38 named[6759]: zone od.com/IN: loaded serial 2020011601
Jan 16 19:16:53 alice38 named[6759]: zone host.com/IN: loaded serial 2020011601
Jan 16 19:16:53 alice38 named[6759]: zone 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa/IN: loaded serial 0
Jan 16 19:16:53 alice38 named[6759]: all zones loaded
Jan 16 19:16:53 alice38 systemd[1]: Started Berkeley Internet Name Domain (DNS).

重启之后就好了

harbor/docker login登陆不上

报错: Error response from daemon: Get http://harbor.od.com/v2/: Get http://harbor.od.com:180/service/token?account=admin&client_id=docker&offline_token=true&service=harbor-registry: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
K8S中Harbor使用Nginx反向代理无法获取image - liucx - 博客园 (2021_1_30 下午12_17_37).html
解决办法:
https://www.cnblogs.com/liucx/p/12981023.html