1、基础环境

1.安装epel-release

$ yum install epel-release -y

2.保证系统内核版本为3.10.x以上

$ uname -a
Linux k8s-node01 3.10.0-693.el7.x86_64

3.关闭防火墙和selinux

$ systemctl stop firewalld && systemctl disable firewalld
$ sed -i.bak 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
$ setenforce 0

4.时间同步

$ echo '#time sync by lidao at 2017-03-08' >>/var/spool/cron/root
$ echo '*/5 * * * * /usr/sbin/ntpdate pool.ntp.org >/dev/null 2>&1' >>/var/spool/cron/root
$ crontab -l

5.内核优化

$ cat >>/etc/sysctl.conf<<EOF
net.ipv4.tcp_fin_timeout = 2
net.ipv4.ip_forward = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.ip_local_port_range = 4000    65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_orphans = 16384
EOF

$ sysctl -p

6.安装必要工具

$ yum install wget net-tools telnet tree nmap sysstat lrzsz dos2unix bind-utils -y

2、部署DNS

bind9服务来实现DNS,在ingress中实现七层代理,在实验环境中就得绑定hosts方式实现访问,而且容器也没办法绑定hosts,这里通过DNS来实现。

1.安装bind9软件(hdss7-11)

$ yum install bind -y

2.主配置文件

$ vim /etc/named.conf
listen-on port 53 { 10.4.7.11; }; # dns监听地址
allow-query     { any; };         # 允许所有主机访问dns服务
forwarders      { 10.4.7.2; };    # 指定上级dns
recursion yes;                    # dns采用递归算法查询(另一种是迭代)
dnssec-enable no;									# 节约资源将其关闭
dnssec-validation no;						  # 节约资源将其关闭

配置文件语法校验

# 没有报错说明语法没问题
$ named-checkconf

2.区域配置文件

$ 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; };
};

3.配置区域数据文件

  • /var/named/host.com.zone
$ORIGIN host.com.
$TTL 600	; 10 minutes
@       IN SOA	dns.host.com. dnsadmin.host.com. (
				2019011001 ; serial
				10800      ; refresh (3 hours)
				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
  • /var/named/od.com.zone
$ORIGIN od.com.
$TTL 600	; 10 minutes
@   		IN SOA	dns.od.com. dnsadmin.od.com. (
				2019011001 ; 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

4.启动dns服务

$ systemctl start named && systemctl enable named

5.验证是否可解析

$ dig -t A hdss7-21.host.com @10.4.7.11 +short
10.4.7.21
$ dig -t A hdss7-200.host.com @10.4.7.11 +short
10.4.7.200

6.DNS客户端配置

所有节点

  • 修改网卡dns方式
# 修改网卡配置文件DNS1
$ vim /etc/sysconfig/network-scripts/ifcfg-eth0
DNS1=10.4.7.11

$ systemctl restart network

# 测试ping
$ ping baidu.com
PING baidu.com (39.156.69.79) 56(84) bytes of data.
64 bytes from 39.156.69.79 (39.156.69.79): icmp_seq=1 ttl=128 time=47.0 ms
64 bytes from 39.156.69.79 (39.156.69.79): icmp_seq=2 ttl=128 time=48.3 ms

$ ping hdss7-21.host.com
PING HDSS7-21.host.com (10.4.7.21) 56(84) bytes of data.
64 bytes from 10.4.7.21 (10.4.7.21): icmp_seq=1 ttl=64 time=0.821 ms
64 bytes from 10.4.7.21 (10.4.7.21): icmp_seq=2 ttl=64 time=0.598 ms
  • 添加search(短域名)
$ vim /etc/resolv.conf
# Generated by NetworkManager
search host.com
nameserver 10.4.7.2

# Ping短域名
$ ping hdss7-200
PING HDSS7-200.host.com (10.4.7.200) 56(84) bytes of data.
64 bytes from 10.4.7.200 (10.4.7.200): icmp_seq=1 ttl=64 time=1.18 ms
64 bytes from 10.4.7.200 (10.4.7.200): icmp_seq=2 ttl=64 time=0.456 ms

3、准备自签证书

运维主机hdss7-200.host.com上:

1.安装CFSSL

$ wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 -O /usr/bin/cfssl
$ wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64 -O /usr/bin/cfssl-json
$ wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64 -O /usr/bin/cfssl-certinfo
$ chmod +x /usr/bin/cfssl*
  • 关于cfssl工具:
    • cfssl:证书签发的主要工具
    • cfssl-json:将cfssl生成的整数(json格式)变为文件承载式证书
    • cfssl-certinfo:验证证书的信息

2.创建生成CA证书签名请求(csr)的json配置文件

$ vim /opt/certs/ca-csr.json
{
    "CN": "Sky",
    "hosts": [
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ],
    "ca": {
        "expiry": "175200h"
    }
}

3.生成CA证书和私钥

$ cfssl gencert -initca ca-csr.json | cfssl-json -bare ca
2020/01/10 13:58:49 [INFO] generating a new CA key and certificate from CSR
2020/01/10 13:58:49 [INFO] generate received request
2020/01/10 13:58:49 [INFO] received CSR
2020/01/10 13:58:49 [INFO] generating key: rsa-2048
2020/01/10 13:58:49 [INFO] encoded CSR
2020/01/10 13:58:49 [INFO] signed certificate with serial number 214125439771303219718649555160058070055859759808

$ ll
total 16
-rw-r--r-- 1 root root  328 Jan 10 13:53 ca-csr.json # 请求文件
-rw------- 1 root root 1675 Jan 10 13:58 ca-key.pem  # 私钥
-rw-r--r-- 1 root root  993 Jan 10 13:58 ca.csr
-rw-r--r-- 1 root root 1346 Jan 10 13:58 ca.pem      # 证书

4、部署Docker环境

hdss7-200.host.com,hdss7-21.host.com,hdss7-22.host.com上:

1.一键安装Docker-ce

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

2.配置文件

$ mkdir /etc/docker/
$ mkdir -p /data/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://q2gr04ke.mirror.aliyuncs.com"],
  "bip": "172.7.21.1/24",
  "exec-opts": ["native.cgroupdriver=systemd"],
  "live-restore": true
}

3.启动docker

$ systemctl restart docker.service && systemctl enable docker.service

5、私有仓库Harbor部署

hdss7-200.host.com上:

1.下载软件二进制包并解压

https://github.com/goharbor/harbor

$ tar xf harbor-offline-installer-v1.8.1.tgz -C /opt/
$ mv /opt/harbor/ /opt/harbor-v1.8.1
$ ln -s /opt/harbor-v1.8.1/ /opt/harbor

2.配置文件

$ vim /opt/harbor/harbor.yml
hostname: harbor.od.com
http:
  port: 180
data_volume: /data/harbor
location: /data/harbor/logs

创建相应目录

$ mkdir -p /data/harbor/logs

3.安装docker-compose

$ yum install docker-compose -y

4.启动harbor

$ sh /opt/harbor/install.sh
$ docker-compose ps

5.基于Nginx实现代理访问Harbor

$ yum install nginx -y

$ vim /etc/nginx/conf.d/harbor.od.com.conf
server {
    listen       80;
    server_name  harbor.od.com;

    client_max_body_size 1000m;

    location / {
        proxy_pass http://127.0.0.1:180;
    }
}

启动nginx

$ nginx -t
$ systemctl start nginx && systemctl enable nginx

6.hdss7-11上添加dns A记录

$ vi /var/named/od.com.zone
harbor             A    10.4.7.200

重启dns并测试

$ systemctl restart named
$ dig -t A harbor.od.com +short
10.4.7.200

7.浏览器访问:harbor.od.com

8.harbor上新建一个名:public 公开项目
Kubernetes 完整二进制部署(精品)-LMLPHP

9.从docker.io拉取nginx镜像

$ docker pull nginx:1.7.9
# 等价于
$ docker pull docker.io/library/nginx:1.7.9

将从公网下载的nginx打上刚才创建的harbor仓库下public项目的tag

# 找到nginx image id将其打上new tag
$ docker tag 84581e99d807 harbor.od.com/public/nginx:v1.7.9

# 需先登录harbor
$ docker login harbor.od.com
Username: admin
Password:

# 然后在推送镜像到私有仓库
$ docker push harbor.od.com/public/nginx:v1.7.9

6、部署Master节点

6.1、部署Etcd集群

集群规划

注意:这里部署文档以hdss7-12.host.com主机为例,另外两台主机安装部署方法类似

1.创建基于根证书的config配置文件

运维主机hdss7-200上

$ vim /opt/certs/ca-config.json
{
    "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"
                ]
            }
        }
    }
}

2.创建生成etcd自签证书签名请求(csr)的json配置文件

运维主机hdss7-200上

$ vim /opt/certs/etcd-peer-csr.json
{
    "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"
        }
    ]
}

3.生成etcd证书和私钥

运维主机hdss7-200上

$ cd /opt/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
2020/01/10 15:05:30 [INFO] generate received request
2020/01/10 15:05:30 [INFO] received CSR
2020/01/10 15:05:30 [INFO] generating key: rsa-2048
2020/01/10 15:05:30 [INFO] encoded CSR
2020/01/10 15:05:30 [INFO] signed certificate with serial number 257419759502713087580344599035913411225571544160
2020/01/10 15:05:30 [WARNING] This certificate lacks a "hosts" field. This makes it unsuitable for
websites. For more information see the Baseline Requirements for the Issuance and Management
of Publicly-Trusted Certificates, v.1.1.6, from the CA/Browser Forum (https://cabforum.org);
specifically, section 10.2.3 ("Information Requirements").

检查生成的证书、私钥

$ ll etcd-peer*
-rw-r--r-- 1 root root  364 Jan 10 15:03 etcd-peer-csr.json
-rw------- 1 root root 1675 Jan 10 15:05 etcd-peer-key.pem
-rw-r--r-- 1 root root 1062 Jan 10 15:05 etcd-peer.csr
-rw-r--r-- 1 root root 1428 Jan 10 15:05 etcd-peer.pem

4.创建etcd用户

hdss7-12.host.com上:

$ useradd -s /sbin/nologin -M etcd

5.下载软件、解压,做软连接

hdss7-12.host.com上:

etcd下载地址

$ tar xf etcd-v3.1.20-linux-amd64.tar.gz  -C /opt/
$ mv /opt/etcd-v3.1.20-linux-amd64/ /opt/etcd-v3.1.20
$ ln -s /opt/etcd-v3.1.20/ /opt/etcd

6.创建目录,拷贝证书、私钥

hdss7-12.host.com上:

  • 创建目录
$ mkdir -p /opt/etcd/certs /data/etcd /data/logs/etcd-server
  • 拷贝证书

将运维主机上生成的ca.pemetcd-peer-key.pemetcd-peer.pem拷贝到/opt/etcd/certs目录中,注意私钥文件权限600

$ ll -l
total 12
-rw-r--r-- 1 root root 1346 Jan 27 12:04 ca.pem
-rw------- 1 root root 1675 Jan 27 12:03 etcd-peer-key.pem
-rw-r--r-- 1 root root 1432 Jan 27 12:03 etcd-peer.pem
  • 修改权限
$ chown -R etcd.etcd /opt/etcd-v3.1.20 /data/etcd/ /data/logs/etcd-server/

7.创建etcd服务启动脚本

hdss7-12.host.com上:

$ vim /opt/etcd/etcd-server-startup.sh
#!/bin/sh
./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 +x /opt/etcd/etcd-server-startup.sh

8.创建etcd-server的启动配置

hdss7-12.host.com上:

安装supervisor(优势:自动拉起挂掉的程序)

$ yum install supervisor -y
$ systemctl start supervisord && systemctl enable supervisord

将etcd启动脚本交给supervisor管理

$ 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=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)
killasgroup=true
stopasgroup=true

9.启动etcd

hdss7-12.host.com上:

$ supervisorctl update
etcd-server-7-12: added process group

检查是否启动

$ supervisorctl status
etcd-server-7-12                 RUNNING   pid 5029, uptime 0:02:11
$ netstat -lntup | grep "etcd"
tcp        0      0 10.4.7.12:2379          0.0.0.0:*               LISTEN      5030/./etcd
tcp        0      0 127.0.0.1:2379          0.0.0.0:*               LISTEN      5030/./etcd
tcp        0      0 10.4.7.12:2380          0.0.0.0:*               LISTEN      5030/./etcd

10.检查集群状态(必须在三节点起来后)

$ /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

检查集群角色

$ ./etcdctl member list
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=false
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=true

6.2、部署kube-apiserver集群

集群规划

注意:这里10.4.7.1110.4.7.12使用nginx做4层负载均衡,用keepalived跑一个VIP:10.4.7.10,代理两个kube-apiserver,实现高可用

这类部署文档以hdss7-21.host.com主机为例,另外一台运算节点部署方法类似

下载软件,解压,做软连接

hdss7-21.host.com上:

kubernetes官方Github地址

kuberneetes下载地址

$ tar xf /opt/src/kubernetes-server-linux-amd64-v1.15.2.tar.gz  -C /opt/
$ mv /opt/kubernetes/ /opt/kubernetes-v1.15.2
$ ln -s /opt/kubernetes-v1.15.2/ /opt/kubernetes

6.2.1、创建cliient证书

运维主机hdss7-200上

1创建生成证书签名请求(csr)的json配置文件

$ 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"
        }
    ]
}

2.生成client证书和私钥

$ cd /opt/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/10 16:16:35 [INFO] generate received request
2020/01/10 16:16:35 [INFO] received CSR
2020/01/10 16:16:35 [INFO] generating key: rsa-2048
\2020/01/10 16:16:36 [INFO] encoded CSR
2020/01/10 16:16:36 [INFO] signed certificate with serial number 294650890732881478597150479545220844543007627512
2020/01/10 16:16:36 [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").

3.检查生成的证书、私钥

$ ll client*
-rw-r--r-- 1 root root  280 Jan 10 16:15 client-csr.json
-rw------- 1 root root 1679 Jan 10 16:16 client-key.pem
-rw-r--r-- 1 root root  993 Jan 10 16:16 client.csr
-rw-r--r-- 1 root root 1363 Jan 10 16:16 client.pem

6.2.2、签发kube-apiserver证书

运维主机hdss7-200上

1.创建生成证书签名请求(csr)的json配置文件

$ 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"
        }
    ]
}

注意:

  • hosts 字段指定授权使用该证书的 IP 或域名列表,这里列出了 VIP 、apiserver节点 IP、kubernetes 服务 IP 和域名;
  • 域名最后字符不能是 . (如不能为kubernetes.default.svc.cluster.local. ),否则解析时失败,提示: x509:cannot parse dnsName "kubernetes.default.svc.cluster.local." ;
  • 如果使用非 cluster.local 域名,如 opsnull.com ,则需要修改域名列表中的最后两个域名为: kubernetes.default.svc.opsnull 、 kubernetes.default.svc.opsnull.com
  • kubernetes 服务 IP 是 apiserver 自动创建的,一般是 --service-cluster-ip-range 参数指定的网段的第一个IP,后续可以通过如下命令获取:
$ kubectl get svc kubernetes
NAME          TYPE       CLUSTER-IP     EXTERNAL-IP    PORT(S)   AGE
kubernetes   ClusterIP   192.168.0.1     <none>         443/TCP   4d

2.生成api-server证书和私钥

$ cd /opt/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/10 16:21:06 [INFO] generate received request
2020/01/10 16:21:06 [INFO] received CSR
2020/01/10 16:21:06 [INFO] generating key: rsa-2048
2020/01/10 16:21:07 [INFO] encoded CSR
2020/01/10 16:21:07 [INFO] signed certificate with serial number 533398970701884951320970228765072309875544569205
2020/01/10 16:21:07 [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").

3.检查生成的证书、私钥

$ ll apiserver*
-rw-r--r-- 1 root root  566 Jan 10 16:19 apiserver-csr.json
-rw------- 1 root root 1679 Jan 10 16:21 apiserver-key.pem
-rw-r--r-- 1 root root 1249 Jan 10 16:21 apiserver.csr
-rw-r--r-- 1 root root 1598 Jan 10 16:21 apiserver.pem

6.2.3、kube-apiserver配置

hdss7-21上

1.创建目录存放证书和私钥以及配置文件

$ mkdir /opt/kubernetes/server/bin/cert /opt/kubernetes/server/bin/conf

2.拷贝证书、私钥,注意私钥文件属性600

$ ll # 三套证书
total 24
-rw------- 1 root root 1679 Jan 10 16:32 apiserver-key.pem
-rw-r--r-- 1 root root 1598 Jan 10 16:32 apiserver.pem
-rw------- 1 root root 1675 Jan 10 16:32 ca-key.pem
-rw-r--r-- 1 root root 1346 Jan 10 16:32 ca.pem
-rw------- 1 root root 1679 Jan 10 16:32 client-key.pem
-rw-r--r-- 1 root root 1363 Jan 10 16:32 client.pem

3.创建api-server审计策略文件

$ vi /opt/kubernetes/server/bin/conf/audit.yaml
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"

4.创建启动脚本

$ vim /opt/kubernetes/server/bin/kube-apiserver.sh
#!/bin/bash
./kube-apiserver \
  --apiserver-count 2 \
  --insecure-port 8080 \
  --secure-port 6443 \
  --audit-log-path /data/logs/kubernetes/kube-apiserver/audit-log \
  --audit-policy-file ./conf/audit.yaml \
  --authorization-mode RBAC \
  --client-ca-file ./cert/ca.pem \
  --requestheader-client-ca-file ./cert/ca.pem \
  --enable-admission-plugins NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota \
  --etcd-cafile ./cert/ca.pem \
  --etcd-certfile ./cert/client.pem \
  --etcd-keyfile ./cert/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 ./cert/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 ./cert/client.pem \
  --kubelet-client-key ./cert/client-key.pem \
  --log-dir  /data/logs/kubernetes/kube-apiserver \
  --tls-cert-file ./cert/apiserver.pem \
  --tls-private-key-file ./cert/apiserver-key.pem \
  --v 2

配置参数说明

给脚本添加执行权限

$ chmod +x /opt/kubernetes/server/bin/kube-apiserver.sh

5.创建api-server的启动配置

$ vi /etc/supervisord.d/kube-apiserver.ini
[program:kube-apiserver-7-21]
command=/opt/kubernetes/server/bin/kube-apiserver.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-apiserver/apiserver.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)
killasgroup=true
stopasgroup=true

6.创建日志目录

$ mkdir -p /data/logs/kubernetes/kube-apiserver

7.启动并检查

$ supervisorctl update
$ supervisorctl status
etcd-server-7-22                 RUNNING   pid 4013, uptime 1:12:36
kube-apiserver-7-22              RUNNING   pid 4596, uptime 0:00:31

8.查看api-server端口

$ netstat -lntup | egrep "8080|6443"
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      20375/./kube-apiser
tcp6       0      0 :::6443                 :::*                    LISTEN      20375/./kube-apiser

6.3、L4反向代理

hdss7-11hdss7-12上基于nginx实现L4反向代理调度到后端的kubernetes api-server:
Kubernetes 完整二进制部署(精品)-LMLPHP

所有Node节点的k8s组件:kubelet,kube-proxy会去访问https://10.4.7.10:7443这个地址,并携带证书

6.3.1、部署Nginx

1.安装nginx

$ yum install nginx -y

2.nginx配置文件

$ vim /etc/nginx/nginx.conf # 黏贴到http标签外
stream {
    # kubernetes api-server ip地址以及https端口
    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;
    }
    # 监听7443端口,将其接收的流量转发至指定proxy_pass
    server {
        listen 7443;
        proxy_connect_timeout 2s;
        proxy_timeout 900s;
        proxy_pass kube-apiserver;
    }
}

3.启动nginx

$ systemctl start nginx && systemctl enable nginx

6.3.2、部署keepalived

1.安装keepalived

$ yum install keepalived -y

2.监听脚本

$ vi /etc/keepalived/check_port.sh
#!/bin/bash
# keepalived 监控端口脚本
# 使用方法:
# 在keepalived的配置文件中
# vrrp_script check_port {#创建一个vrrp_script脚本,检查配置
#     script "/etc/keepalived/check_port.sh 6379" #配置监听的端口
#     interval 2 #检查脚本的频率,单位(秒)
# }
CHK_PORT=$1
if [ -n "$CHK_PORT" ];then
        PORT_PROCESS=`ss -lnt|grep $CHK_PORT|wc -l`
        if [ $PORT_PROCESS -eq 0 ];then
                echo "Port $CHK_PORT Is Not Used,End."
                exit 1
        fi
else
        echo "Check Port Cant Be Empty!"
fi

添加可执行权限

$ chmod +x /etc/keepalived/check_port.sh

3.keepalived主配置文件

$ vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id 10.4.7.11
}

vrrp_script chk_nginx {
    # 调用脚本检测nginx监听的7443端口是否存在
    script "/etc/keepalived/check_port.sh 7443"
    interval 2
    weight -20
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 251
    priority 100
    advert_int 1
    # 当前主机IP
    mcast_src_ip 10.4.7.11
    nopreempt

		# 高可用认证
    authentication {
        auth_type PASS
        auth_pass 11111111
    }
    track_script {
         chk_nginx
    }
    # 虚拟IP
    virtual_ipaddress {
        10.4.7.10
    }
}

4.keepalived备配置文件

$ vi /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
	router_id 10.4.7.12
}
vrrp_script chk_nginx {
	script "/etc/keepalived/check_port.sh 7443"
	interval 2
	weight -20
}
vrrp_instance VI_1 {
	state BACKUP
	interface eth0
	virtual_router_id 251
	mcast_src_ip 10.4.7.12
	priority 90
	advert_int 1
	authentication {
		auth_type PASS
		auth_pass 11111111
	}
	track_script {
		chk_nginx
	}
	virtual_ipaddress {
		10.4.7.10
	}
}

5.启动

$ systemctl start keepalived.service && systemctl enable keepalived.service

6.4、部署controller-manager

hdss7-21.host.comhdss7-22.host.com都部署了api-server,并且暴露了127.0.0.1:8080端口,也就是只能当前机器访问,那么controller-manager也是部署到当前机器,那就可以通过非安全端口8080直接访问到本机的api-server,即访问快捷/速度快又不需要证书认证。

集群规划

1.创建启动脚本

$ vim /opt/kubernetes/server/bin/kube-controller-manager.sh
#!/bin/sh
./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 ./cert/ca-key.pem \
  --service-cluster-ip-range 192.168.0.0/16 \
  --root-ca-file ./cert/ca.pem \
  --v 2

配置参数说明

2.调整文件权限,创建日志存放目录

$ chmod +x /opt/kubernetes/server/bin/kube-controller-manager.sh
$ mkdir -p /data/logs/kubernetes/kube-controller-manager

3.创建controller-manager的启动配置

$ vi /etc/supervisord.d/kube-conntroller-manager.ini
[program:kube-controller-manager-7-21]
command=/opt/kubernetes/server/bin/kube-controller-manager.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)
killasgroup=true
stopasgroup=true

4.启动并检查

$ supervisorctl update
$ supervisorctl status
etcd-server-7-21                 RUNNING   pid 4148, uptime 2:07:47
kube-apiserver-7-21              RUNNING   pid 4544, uptime 1:02:36
kube-controller-manager-7-21     RUNNING   pid 4690, uptime 0:00:32

6.5、部署kube-scheduler

hdss7-21.host.comhdss7-22.host.com都部署了api-server,并且暴露了127.0.0.1:8080端口,也就是只能当前机器访问,那么kube-scheduler也是部署到当前机器,那就可以通过非安全端口8080直接访问到本机的api-server,即访问快捷/速度快又不需要证书认证。

集群规划

1.创建启动脚本

$ vim /opt/kubernetes/server/bin/kube-scheduler.sh
#!/bin/sh
./kube-scheduler \
  --leader-elect  \
  --log-dir /data/logs/kubernetes/kube-scheduler \
  --master http://127.0.0.1:8080 \
  --v 2

2.调整文件权限,创建目录

$ chmod +x /opt/kubernetes/server/bin/kube-scheduler.sh
$ mkdir -p /data/logs/kubernetes/kube-scheduler

3.创建controller-manager的启动配置

$ vi /etc/supervisord.d/kube-scheduler.ini
[program:kube-scheduler-7-21]
command=/opt/kubernetes/server/bin/kube-scheduler.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-scheduler/scheduler.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)
killasgroup=true
stopasgroup=true

4.启动并检查

$ supervisorctl update
$ supervisorctl status
etcd-server-7-21                 RUNNING   pid 4148, uptime 2:11:12
kube-apiserver-7-21              RUNNING   pid 4544, uptime 1:06:01
kube-controller-manager-7-21     RUNNING   pid 4690, uptime 0:03:57
kube-scheduler-7-21              RUNNING   pid 4727, uptime 0:00:32

5.检查集群健康状态

$ ln -s /opt/kubernetes/server/bin/kubectl /usr/bin/kubectl
$ kubectl get cs
NAME                 STATUS    MESSAGE              ERROR
controller-manager   Healthy   ok
scheduler            Healthy   ok
etcd-2               Healthy   {"health": "true"}
etcd-0               Healthy   {"health": "true"}
etcd-1               Healthy   {"health": "true"}

7、部署Node节点服务

7.1、部署Kubelet

集群规划

7.1.1、签发kubelet证书

运维主机hdss7-200.host.com上:

1.创建生成证书签名请求(csr)的json配置文件

$ vim /opt/certs/kubelet-csr.json
{
    "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"
        }
    ]
}

2.生成证书和私钥

$ cd /opt/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/10 20:15:39 [INFO] generate received request
2020/01/10 20:15:39 [INFO] received CSR
2020/01/10 20:15:39 [INFO] generating key: rsa-2048
2020/01/10 20:15:40 [INFO] encoded CSR
2020/01/10 20:15:40 [INFO] signed certificate with serial number 526251135664766815056179206511844993208257685250
2020/01/10 20:15:40 [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").

3.检查证书和私钥

$ ll kubelet*
-rw-r--r-- 1 root root  452 Jan 10 20:15 kubelet-csr.json
-rw------- 1 root root 1675 Jan 10 20:15 kubelet-key.pem
-rw-r--r-- 1 root root 1115 Jan 10 20:15 kubelet.csr
-rw-r--r-- 1 root root 1468 Jan 10 20:15 kubelet.pem

7.1.2、kubelet配置

hdss7-21.host.com上:

1.拷贝证书到各运算节点,并创建配置(证书、私钥,注意私钥文件权限600)

$  ll /opt/kubernetes/server/bin/cert/
total 32
-rw------- 1 root root 1679 Jan 10 16:32 apiserver-key.pem
-rw-r--r-- 1 root root 1598 Jan 10 16:32 apiserver.pem
-rw------- 1 root root 1675 Jan 10 16:32 ca-key.pem
-rw-r--r-- 1 root root 1346 Jan 10 16:32 ca.pem
-rw------- 1 root root 1679 Jan 10 16:32 client-key.pem
-rw-r--r-- 1 root root 1363 Jan 10 16:32 client.pem
-rw------- 1 root root 1675 Jan 10 20:20 kubelet-key.pem
-rw-r--r-- 1 root root 1468 Jan 10 20:20 kubelet.pem

2.创建kubelet配置文件

# 进入指定目录
$ cd /opt/kubernetes/server/bin/conf/

# 指定根证书和api-server的vip
$ kubectl config set-cluster myk8s \
  --certificate-authority=/opt/kubernetes/server/bin/cert/ca.pem \
  --embed-certs=true \
  --server=https://10.4.7.10:7443 \
  --kubeconfig=kubelet.kubeconfig

# 拿客户端密钥和api-server通信
$ kubectl config set-credentials k8s-node \
  --client-certificate=/opt/kubernetes/server/bin/cert/client.pem \
  --client-key=/opt/kubernetes/server/bin/cert/client-key.pem \
  --embed-certs=true \
  --kubeconfig=kubelet.kubeconfig

# 以k8s-node用户去访问api-server(该用户需要授权)
$ kubectl config set-context myk8s-context \
  --cluster=myk8s \
  --user=k8s-node \
  --kubeconfig=kubelet.kubeconfig

$ kubectl config use-context myk8s-context --kubeconfig=kubelet.kubeconfig
  • 关于kubeconfig文件
    • 这是一个k8s用户的配置文件
    • 它里面含有证书信息
    • 证书过期或更换,需要同步替换该文件

3.创建授权资源配置文件k8s-node.yaml

$ vim /opt/kubernetes/server/bin/conf/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
  • User account是为人设计的,而service account则是为Pod中的进程调用Kubernetes API而设计;
  • User account是跨namespace的,而service account则是仅局限它所在的namespace

4.使用kubctl创建

$ kubectl create -f /opt/kubernetes/server/bin/conf/k8s-node.yaml

7.1.3、准备pause基础镜像

pause镜像是k8s里必不可少的以pod方式运行业务容器时的一个基础容器。

运维主机hdss7-200.host.com上:

1.下载

$ docker pull kubernetes/pause

2.提交至私有仓库(harbor)中

$ docker tag f9d5de079539 harbor.od.com/public/pause:latest
$ docker push harbor.od.com/public/pause:latest

7.1.4、创建kubelet启动脚本

hdss7-21.host.com上:

1.启动脚本

$ vim /opt/kubernetes/server/bin/kubelet.sh
#!/bin/sh
./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 ./cert/ca.pem \
  --tls-cert-file ./cert/kubelet.pem \
  --tls-private-key-file ./cert/kubelet-key.pem \
  --hostname-override hdss7-22.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

参数配置解析

创建目录

$ mkdir -p /data/logs/kubernetes/kube-kubelet /data/kubelet

给脚本添加+x权限

$ chmod +x /opt/kubernetes/server/bin/kubelet.sh

2.创建kubelet的启动配置

$ vi /etc/supervisord.d/kube-kubelet.ini
[program:kube-kubelet-7-21]
command=/opt/kubernetes/server/bin/kubelet.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-kubelet/kubelet.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)
killasgroup=true
stopasgroup=true

3.启动并检查

$ supervisorctl update
$ supervisorctl status
etcd-server-7-21                 RUNNING   pid 4148, uptime 5:20:56
kube-apiserver-7-21              RUNNING   pid 4544, uptime 4:15:45
kube-controller-manager-7-21     RUNNING   pid 4690, uptime 3:13:41
kube-kubelet-7-21                RUNNING   pid 5099, uptime 0:01:33
kube-scheduler-7-21              RUNNING   pid 4727, uptime 3:10:16

4.查看节点

# 给节点打上标签
$ kubectl label node hdss7-22.host.com node-role.kubernetes.io/node=
$ kubectl label node hdss7-22.host.com node-role.kubernetes.io/master=

$ kubectl get nodes
NAME                STATUS   ROLES         AGE     VERSION
hdss7-21.host.com   Ready    master,node   9m56s   v1.15.2
hdss7-22.host.com   Ready    master,node   4m5s    v1.15.2

7.2、部署kube-proxy

集群规划

7.2.1、签发kube-proxy证书

运维主机hdss-200.host.com上:

1.创建生成证书签名请求(csr)的json配置文件

$ vim /opt/certs/kube-proxy-csr.json
{
    "CN": "system:kube-proxy",
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "beijing",
            "L": "beijing",
            "O": "od",
            "OU": "ops"
        }
    ]
}

2.生成证书和私钥

$ cd /opt/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/10 21:12:40 [INFO] generate received request
2020/01/10 21:12:40 [INFO] received CSR
2020/01/10 21:12:40 [INFO] generating key: rsa-2048
2020/01/10 21:12:41 [INFO] encoded CSR
2020/01/10 21:12:41 [INFO] signed certificate with serial number 377857644553048066195455948935822375401500792612
2020/01/10 21:12:41 [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").

3.检查证书和私钥

$ ll  kube-proxy*
-rw------- 1 root root 1675 Jan 10 21:12 kube-proxy-client-key.pem
-rw-r--r-- 1 root root 1005 Jan 10 21:12 kube-proxy-client.csr
-rw-r--r-- 1 root root 1375 Jan 10 21:12 kube-proxy-client.pem
-rw-r--r-- 1 root root  267 Jan 10 21:12 kube-proxy-csr.json

7.2.2、Kube-proxy配置

hdss7-21.host.com上:

1.拷贝证书到各运算节点,并创建配置(证书、私钥,注意私钥文件权限600)

$ ll
total 40
-rw------- 1 root root 1679 Jan 10 16:32 apiserver-key.pem
-rw-r--r-- 1 root root 1598 Jan 10 16:32 apiserver.pem
-rw------- 1 root root 1675 Jan 10 16:32 ca-key.pem
-rw-r--r-- 1 root root 1346 Jan 10 16:32 ca.pem
-rw------- 1 root root 1679 Jan 10 16:32 client-key.pem
-rw-r--r-- 1 root root 1363 Jan 10 16:32 client.pem
-rw------- 1 root root 1675 Jan 10 21:16 kube-proxy-client-key.pem
-rw-r--r-- 1 root root 1375 Jan 10 21:16 kube-proxy-client.pem
-rw------- 1 root root 1675 Jan 10 20:20 kubelet-key.pem
-rw-r--r-- 1 root root 1468 Jan 10 20:20 kubelet.pem

2.创建kube-proxy配置

# 进入指定目录
$ cd /opt/kubernetes/server/bin/conf/

$ kubectl config set-cluster myk8s \
  --certificate-authority=/opt/kubernetes/server/bin/cert/ca.pem \
  --embed-certs=true \
  --server=https://10.4.7.10:7443 \
  --kubeconfig=kube-proxy.kubeconfig

$ kubectl config set-credentials kube-proxy \
  --client-certificate=/opt/kubernetes/server/bin/cert/kube-proxy-client.pem \
  --client-key=/opt/kubernetes/server/bin/cert/kube-proxy-client-key.pem \
  --embed-certs=true \
  --kubeconfig=kube-proxy.kubeconfig

$ kubectl config set-context myk8s-context \
  --cluster=myk8s \
  --user=kube-proxy \
  --kubeconfig=kube-proxy.kubeconfig

$ kubectl config use-context myk8s-context --kubeconfig=kube-proxy.kubeconfig

7.2.3、创建kube-proxy启动脚本

hdss7-21.host.com上:

1.加载ipvs模块

$ vi /root/ipvs.sh
#!/bin/bash
ipvs_mods_dir="/usr/lib/modules/$(uname -r)/kernel/net/netfilter/ipvs"
for i in $(ls $ipvs_mods_dir|grep -o "^[^.]*")
do
  /sbin/modinfo -F filename $i &>/dev/null
  if [ $? -eq 0 ];then
    /sbin/modprobe $i
  fi
done

添加+x权限

$ chmod +x /root/ipvs.sh

执行脚本并检查ip_vs模块是否加载

$ sh /root/ipvs.sh
$ lsmod  | grep  ip_vs

2.创建启动脚本

$ vim /opt/kubernetes/server/bin/kube-proxy.sh
#!/bin/sh
./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

创建日志存放目录

$ mkdir -p /data/logs/kubernetes/kube-proxy

给脚本添加+x权限

$ chmod +x /opt/kubernetes/server/bin/kube-proxy.sh

2.创建kubelet的启动配置

$ vi /etc/supervisord.d/kube-proxy.ini
[program:kube-proxy-7-21]
command=/opt/kubernetes/server/bin/kube-proxy.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-proxy/proxy.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)
killasgroup=true
stopasgroup=true

启动并检查

$ supervisorctl update
$ supervisorctl status
etcd-server-7-21                 RUNNING   pid 4148, uptime 5:59:11
kube-apiserver-7-21              RUNNING   pid 4544, uptime 4:54:00
kube-controller-manager-7-21     RUNNING   pid 4690, uptime 3:51:56
kube-kubelet-7-21                RUNNING   pid 5099, uptime 0:39:48
kube-proxy-7-21                  RUNNING   pid 14452, uptime 0:00:45
kube-scheduler-7-21              RUNNING   pid 4727, uptime 3:48:31

3.安装ipvs管理工具

$ yum install ipvsadm -y

4.检查ipvs是否成功

$ 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

8、验证集群

1.在任意一个运算节点, 创建一个资源清单

这里我们选hdss7-21.host.com主机

$ vi /root/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 /root/nginx-ds.yaml
daemonset.extensions/nginx-ds created

查看pod状态

$ kubctl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-ds-gl9mg   1/1     Running   0          20s
nginx-ds-mlptx   1/1     Running   0          20s

2.查看集群状态

$ kubectl get cs
NAME                 STATUS    MESSAGE              ERROR
controller-manager   Healthy   ok
scheduler            Healthy   ok
etcd-1               Healthy   {"health": "true"}
etcd-0               Healthy   {"health": "true"}
etcd-2               Healthy   {"health": "true"}

$ kubectl get node
NAME                STATUS   ROLES         AGE   VERSION
hdss7-21.host.com   Ready    master,node   48m   v1.15.2
hdss7-22.host.com   Ready    master,node   42m   v1.15.2
04-17 08:54