Kubernetes简介

Kubernetes简介

2020-03-01
opensource
kubernetes

环境准备

https://labs.play-with-k8s.com/

添加管理节点:+ ADD NEW INSTANCE

You can bootstrap a cluster as follows:

 1. Initializes cluster master node:

 kubeadm init --apiserver-advertise-address $(hostname -i)


 2. Initialize cluster networking:

 kubectl apply -n kube-system -f \
    "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 |tr -d '\n')"
Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 192.168.0.18:6443 --token fq6j4j.j7fwcjgd9nxb0uyv \
    --discovery-token-ca-cert-hash sha256:ea8303472a0ee1c3d13c31ea3defa4e4d129ba8548491c794901f8639c573f80

添加数据节点:+ ADD NEW INSTANCE

kubeadm join 192.168.0.18:6443 --token fq6j4j.j7fwcjgd9nxb0uyv \
    --discovery-token-ca-cert-hash sha256:ea8303472a0ee1c3d13c31ea3defa4e4d129ba8548491c794901f8639c573f80

添加数据节点:+ ADD NEW INSTANCE

kubeadm join 192.168.0.18:6443 --token fq6j4j.j7fwcjgd9nxb0uyv \
    --discovery-token-ca-cert-hash sha256:ea8303472a0ee1c3d13c31ea3defa4e4d129ba8548491c794901f8639c573f80

系统架构

alt

Kubernetes以集群为单位提供容器化管理平台

[node1 ~]$ kubectl get nodes
NAME    STATUS   ROLES    AGE     VERSION
node1   Ready    master   4m37s   v1.14.9
node2   Ready    <none>   90s     v1.14.9
node3   Ready    <none>   40s     v1.14.9

同一个节点既可以做为Master也可以做为Workder

集群包含两种角色的节点集合,Master和Worker

  • Master做为集群的控制面,负责管理整个容器化平台并对外提供服务。
  • Worker节点做为集群的计算面,负责集群资源的实际运行载体。
[node1 ~]$ kubectl get pods --all-namespaces
NAMESPACE     NAME                            READY   STATUS    RESTARTS   AGE
kube-system   coredns-6dcc67dcbc-gv77k        1/1     Running   0          5m32s
kube-system   coredns-6dcc67dcbc-k5926        1/1     Running   0          5m32s
kube-system   etcd-node1                      1/1     Running   0          4m30s
kube-system   kube-apiserver-node1            1/1     Running   0          4m48s
kube-system   kube-controller-manager-node1   1/1     Running   0          4m37s
kube-system   kube-proxy-h2vtz                1/1     Running   0          2m45s
kube-system   kube-proxy-j59hl                1/1     Running   0          5m32s
kube-system   kube-proxy-tsq8v                1/1     Running   0          115s
kube-system   kube-scheduler-node1            1/1     Running   0          4m51s
kube-system   weave-net-8l2bq                 2/2     Running   0          5m6s
kube-system   weave-net-d6299                 2/2     Running   1          115s
kube-system   weave-net-hmw2k                 2/2     Running   0          2m45s

Master节点主要运行组件:

  • kube-apiserver,消息总线,负责集群消息通信中心,对外提供REST API服务。
  • kube-controller-manager,系统核心,负责管理集群各种资源。
  • kube-scheduler,调度器,负责POD资源调度策略。
  • etcd,存储中心,负责存储集群各种资源状态信息。

Worker节点主要运行组件:

  • kube-proxy,负责节点网络管理。
  • Kubelet,节点代理,负责节点上任务调度。
  • Container Runtime,容器运行时,支持Docker、rkt等

Addons:

  • coredns,集群DNS服务器,负责各种服务地址解析。
  • weave-net,容器网络插件,支持weave、flannel、canal等

组件说明

alt

Kubernetes通过对集群内各种资源的调度管理实现应用在集群内的运行管理。

  • Pod,Kubernetes集群最小调度单元,包含单个或多个容器。
  • Label,通过给资源打标签Label方式实现资源的分类。
  • Label Selector,通过选择Label方式实现对资源的分组。
  • Deployment,管理应用的实例,实现应用的快速伸缩。
  • Service,将应用以服务的方式在集群内提供功能。
  • Ingress,将集群内的服务暴露到集群外提供功能。
  • ConfigMap,管理应用的普通配置信息。
  • Secret,管理应用的敏感配置信息。
  • PVC,对应用提供外部存储连接。
  • PV,提供存储实体。

Kubectl

Kubectl是Kubernetes集群的命令行管理工具。

语法

kubectl [command] [TYPE] [NAME] [flags]
  • command,对目标资源的操作动作,包括增删改查,例如create, get, describe, delete,其他apply涵盖create和udpate功能。
  • TYPE,目标资源的类型,主要类型及其缩写如下:
    * all
    * clusterrolebindings
    * clusterroles
    * clusters (valid only for federation apiservers)
    * componentstatuses (aka 'cs')
    * configmaps (aka 'cm')
    * cronjobs
    * daemonsets (aka 'ds')
    * deployments (aka 'deploy')
    * endpoints (aka 'ep')
    * events (aka 'ev')
    * ingresses (aka 'ing')
    * jobs
    * namespaces (aka 'ns')
    * nodes (aka 'no')
    * persistentvolumeclaims (aka 'pvc')
    * persistentvolumes (aka 'pv')
    * pods (aka 'po')
    * rolebindings
    * roles
    * secrets
    * serviceaccounts (aka 'sa')
    * services (aka 'svc')
    * statefulsets
    * storageclasses
  • NAME,资源实例名称
  • flags,特殊标识,提供扩展功能。

常用操作

Operation
    Syntax
    Description
annotate
    kubectl annotate (-f FILENAME \| TYPE NAME \| TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]
    Add or update the annotations of one or more resources.
apply
    kubectl apply -f FILENAME [flags]
    Apply a configuration change to a resource from a file or stdin.
create
    kubectl create -f FILENAME [flags]
    Create one or more resources from a file or stdin.
delete
    kubectl delete (-f FILENAME \| TYPE [NAME \| /NAME \| -l label \| --all]) [flags]
    Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources.
describe
    kubectl describe (-f FILENAME \| TYPE [NAME_PREFIX \| /NAME \| -l label]) [flags]
    Display the detailed state of one or more resources.
edit
    kubectl edit (-f FILENAME \| TYPE NAME \| TYPE/NAME) [flags]
    Edit and update the definition of one or more resources on the server by using the default editor.
exec
    kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]
    Execute a command against a container in a pod,
explain
    kubectl explain [--include-extended-apis=true] [--recursive=false] [flags]
    Get documentation of various resources. For instance pods, nodes, services, etc.
get
    kubectl get (-f FILENAME \| TYPE [NAME \| /NAME \| -l label]) [--watch] [--sort-by=FIELD] [[-o \| --output]=OUTPUT_FORMAT] [flags]
    List one or more resources.
logs
    kubectl logs POD [-c CONTAINER] [--follow] [flags]
    Print the logs for a container in a pod.
replace
    kubectl replace -f FILENAME
    Replace a resource from a file or stdin.
run
    kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [flags]
    Run a specified image on the cluster.

输出样式

Kubectl默认已文本方法返回,可以通过指定flag改变输出样式

kubectl [command] [TYPE] [NAME] -o=<output_format>

output_format支持以下选项:

Output format
    Description
-o=custom-columns=<spec>
    Print a table using a comma separated list of custom columns.
-o=custom-columns-file=<filename>
    Print a table using the custom columns template in the <filename> file.
-o=json
    Output a JSON formatted API object.
-o=jsonpath=<template>
    Print the fields defined in a jsonpath expression.
-o=jsonpath-file=<filename>
    Print the fields defined by the jsonpath expression in the <filename> file.
-o=name
    Print only the resource name and nothing else.
-o=wide
    Output in the plain-text format with any additional information. For pods, the node name is included.
-o=yaml
    Output a YAML formatted API object

应用管理

对象

Kubernetes系统中所有内容均通过对象标识,通过对象对外体现系统状态。

对象包含Spec和Status两部分。

  • Spec,对象的期望状态,由外部输入,对对象进行配置管理。
  • Status,对象的当前状态,由Kubernetes系统返回。

Kubernetes通过循环比较对象的期望状态和当前状态,不停修正对象的当前状态直到其达到预期状态或者失败,完成对象的管理。

Kubernetes采用YAML方式标识对象,包含以下主要组成部分:

  • apiVersion,采用的Kubernetes API版本
  • kind,资源的类型
  • metadata,资源的元数据描述
  • spec,资源的配置信息

spec根据具体资源的类型具有不同的配置规则,参考:https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.14/

例如:

kind: Service
apiVersion: v1
metadata:
  # Unique key of the Service instance
  name: service-example
spec:
  ports:
    # Accept traffic sent to port 80
    - name: http
      port: 80
      targetPort: 80
  selector:
    # Loadbalance traffic across Pods matching
    # this label selector
    app: nginx
  # Create an HA proxy in the cloud provider
  # with an External IP address - *Only supported
  # by some cloud providers*
  type: LoadBalancer

机制

alt

Kubernetes以API server为消息总线,以发布订阅的方式完成消息的传递。

  • Kubectl客户端发送部署请求到API Server。
  • API Server通知Controller Manager创建资源。
  • Schedule执行调度任务,讲Pod分发到合适的node上。
  • Node上的kubelet在节点上创建并运行Pod。

应用的配置和当前状态信息保存在etcd中

网络插件weave为每个Pod分配IP

kube-proxy为Service配置相应的iptables规则

kube-dns位Service提供集群内域名解析

Docker等容器运行时为Pod中容器提供运行平台

部署

[node1 ~]$ cat nginx-app.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-nginx-svc
  labels:
    app: nginx
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: nginx
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: my-nginx
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
[node1 ~]$ kubectl apply -f nginx-app.yaml
service "my-nginx-svc" created
deployment "my-nginx" created
[node1 ~]$ kubectl get svc -l app=nginx
NAME           TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
my-nginx-svc   LoadBalancer   10.108.164.23   <pending>     80:30721/TCP   1m
[node1 ~]$ kubectl get deploy -l app=nginx
NAME       DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
my-nginx   3         3         3            3           2m

通过LoadBalancer IP:30721即可访问部署的Nginx应用

升级

升级前:

[node1 ~]$ kubectl get deploy -l app=nginx -o wide
NAME       DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE       CONTAINERS   IMAGES        SELECTOR
my-nginx   3         3         3            3           8m        nginx        nginx:1.7.9   app=nginx

升级:

[node1 ~]$ cat nginx-app.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-nginx-svc
  labels:
    app: nginx
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: nginx
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: my-nginx
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.8
        ports:
        - containerPort: 80
[node1 ~]$ kubectl apply -f nginx-app.yaml
service "my-nginx-svc" unchanged
deployment "my-nginx" configured

升级后:

[node1 ~]$ kubectl get deploy -l app=nginx -o wide
NAME       DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE       CONTAINERS   IMAGES      SELECTOR
my-nginx   3         3         3            3           11m       nginx        nginx:1.8   app=nginx

nginx版本升级至1.8

伸缩

伸缩前:

[node1 ~]$ kubectl get deploy -l app=nginx -o wide
NAME       DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE       CONTAINERS   IMAGES      SELECTOR
my-nginx   3         3         3            3           12m       nginx        nginx:1.8   app=nginx

伸缩:(3->5)

[node1 ~]$ cat nginx-app.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-nginx-svc
  labels:
    app: nginx
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: nginx
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: my-nginx
spec:
  replicas: 5
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.8
        ports:
        - containerPort: 80
[node1 ~]$ kubectl apply -f nginx-app.yaml
service "my-nginx-svc" unchanged
deployment "my-nginx" configured

伸缩后:

[node1 ~]$ kubectl get deploy -l app=nginx -o wide
NAME       DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE       CONTAINERS   IMAGES      SELECTOR
my-nginx   5         5         5            5           14m       nginx        nginx:1.8   app=nginx

nginx实例数扩容至5