Kubernetes(k8s)进阶

发布时间:2024-04-03 15:01

kubctl常用命令

内置kubectl --help

​ kubectl [选项] --help

kubectl 命令 官方文档

[root@master ~]# kubectl --help
kubectl controls the Kubernetes cluster manager.

 Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/

Basic Commands (Beginner):
  create        Create a resource from a file or from stdin.
  expose        使用 replication controller, service, deployment 或者 pod 并暴露它作为一个 新的 Kubernetes Service
  run           在集群中运行一个指定的镜像
  set           为 objects 设置一个指定的特征

Basic Commands (Intermediate):
  explain       查看资源的文档
  get           显示一个或更多 resources
  edit          在服务器上编辑一个资源
  delete        Delete resources by filenames, stdin, resources and names, or by resources and label selector

Deploy Commands:
  rollout       Manage the rollout of a resource
  scale         Set a new size for a Deployment, ReplicaSet or Replication Controller
  autoscale     自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController 的副本数量

Cluster Management Commands:
  certificate   修改 certificate 资源.
  cluster-info  显示集群信息
  top           Display Resource (CPU/Memory/Storage) usage.
  cordon        标记 node 为 unschedulable
  uncordon      标记 node 为 schedulable
  drain         Drain node in preparation for maintenance
  taint         更新一个或者多个 node 上的 taints

Troubleshooting and Debugging Commands:
  describe      显示一个指定 resource 或者 group 的 resources 详情
  logs          输出容器在 pod 中的日志
  attach        Attach 到一个运行中的 container
  exec          在一个 container 中执行一个命令
  port-forward  Forward one or more local ports to a pod
  proxy         运行一个 proxy 到 Kubernetes API server
  cp            复制 files 和 directories 到 containers 和从容器中复制 files 和 directories.
  auth          Inspect authorization
  debug         Create debugging sessions for troubleshooting workloads and nodes

Advanced Commands:
  diff          Diff live version against would-be applied version
  apply         通过文件名或标准输入流(stdin)对资源进行配置
  patch         Update field(s) of a resource
  replace       通过 filename 或者 stdin替换一个资源
  wait          Experimental: Wait for a specific condition on one or many resources.
  kustomize     Build a kustomization target from a directory or a remote url.

Settings Commands:
  label         更新在这个资源上的 labels
  annotate      更新一个资源的注解
  completion    Output shell completion code for the specified shell (bash or zsh)

Other Commands:
  api-resources Print the supported API resources on the server
  api-versions  Print the supported API versions on the server, in the form of "group/version"
  config        修改 kubeconfig 文件
  plugin        Provides utilities for interacting with plugins.
  version       输出 client 和 server 的版本信息

Usage:
  kubectl [flags] [options]

Use "kubectl  --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).


create创建

//创建类型为dep的nginx pod
[root@master ~]# kubectl create deployment nginx --image nginx
deployment.apps/nginx created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-wknpz   1/1     Running   0          8s

[root@master ~]# kubectl create deployment b1 --image busybox -- date
deployment.apps/b1 created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   1          8s
nginx-6799fc88d8-wknpz   1/1     Running            0          101s

[root@master ~]# kubectl create deployment b2 --image busybox -- sleep 1000
deployment.apps/b2 created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   3          78s
b2-6b45bddb99-zh7n7      1/1     Running            0          9s
nginx-6799fc88d8-wknpz   1/1     Running            0          2m51s

///创建多个 类型为dep的myapp pod
[root@master ~]# kubectl create deployment myapp --image nginx --replicas 3
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   4          2m48s
b2-6b45bddb99-zh7n7      1/1     Running            0          99s
myapp-6d8d776547-49csx   1/1     Running            0          21s
myapp-6d8d776547-79kbw   1/1     Running            0          21s
myapp-6d8d776547-kvc2q   1/1     Running            0          21s
nginx-6799fc88d8-wknpz   1/1     Running            0          4m21s
//创建pod暴露端口号
[root@master ~]# kubectl create deployment test --image nginx --port 80
deployment.apps/test created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   5          4m36s
b2-6b45bddb99-zh7n7      1/1     Running            0          3m27s
myapp-6d8d776547-49csx   1/1     Running            0          2m9s
myapp-6d8d776547-79kbw   1/1     Running            0          2m9s
myapp-6d8d776547-kvc2q   1/1     Running            0          2m9s
nginx-6799fc88d8-wknpz   1/1     Running            0          6m9s
test-7968d6985c-xcvpz    1/1     Running            0          4s
[root@master ~]# kubectl get pods -o wide
NAME                     READY   STATUS             RESTARTS   AGE     IP            NODE                NOMINATED NODE   READINESS GATES
b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   5          4m52s   10.244.1.9    node1.example.com              
b2-6b45bddb99-zh7n7      1/1     Running            0          3m43s   10.244.2.11   node2.example.com              
myapp-6d8d776547-49csx   1/1     Running            0          2m25s   10.244.1.10   node1.example.com              
myapp-6d8d776547-79kbw   1/1     Running            0          2m25s   10.244.1.11   node1.example.com              
myapp-6d8d776547-kvc2q   1/1     Running            0          2m25s   10.244.2.12   node2.example.com              
nginx-6799fc88d8-wknpz   1/1     Running            0          6m25s   10.244.2.10   node2.example.com              
test-7968d6985c-xcvpz    1/1     Running            0          20s     10.244.2.13   node2.example.com              


expose暴露

//查看deployment管理信息
[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
b1      0/1     1            0           6m56s
b2      1/1     1            1           5m48s
myapp   3/3     3            3           4m29s
nginx   1/1     1            1           8m29s
test    1/1     1            1           2m24s
//expose暴露
[root@master ~]# kubectl expose deployment myapp --port 8080 --target-port 80
service/myapp exposed
//已经暴露8080
[root@master ~]# kubectl get svc,pods
NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
service/kubernetes   ClusterIP   10.96.0.1               443/TCP    30h
service/myapp        ClusterIP   10.104.232.97           8080/TCP   33s

NAME                         READY   STATUS             RESTARTS   AGE
pod/b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   6          10m
pod/b2-6b45bddb99-zh7n7      1/1     Running            0          9m20s
pod/myapp-6d8d776547-49csx   1/1     Running            0          8m2s
pod/myapp-6d8d776547-79kbw   1/1     Running            0          8m2s
pod/myapp-6d8d776547-kvc2q   1/1     Running            0          8m2s
pod/nginx-6799fc88d8-wknpz   1/1     Running            0          12m
pod/test-7968d6985c-xcvpz    1/1     Running            0          5m57s
//service IP 加8080
[root@master ~]# curl 10.104.232.97:8080



Welcome to nginx!



Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

//暴露容器80 主机随机端口号 [root@master ~]# kubectl expose deployment nginx --port 80 --type NodePort service/nginx exposed [root@master ~]# kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 443/TCP 30h myapp ClusterIP 10.104.232.97 8080/TCP 5m55s nginx NodePort 10.111.40.207 80:30730/TCP 19s //service访问 [root@master ~]# curl 10.111.40.207 Welcome to nginx!

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

//主机ip加端口号访问 [root@master ~]# curl 192.168.143.140:30730 Welcome to nginx!

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

get获取

root@master ~]# kubectl get nodes
NAME                 STATUS   ROLES                  AGE   VERSION
master.example.com   Ready    control-plane,master   30h   v1.20.0
node1.example.com    Ready                     30h   v1.20.0
node2.example.com    Ready                     30h   v1.20.0
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1               443/TCP        30h
myapp        ClusterIP   10.104.232.97           8080/TCP       11m
nginx        NodePort    10.111.40.207           80:30730/TCP   5m32s
//查看名称空间
[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   30h
kube-node-lease   Active   30h
kube-public       Active   30h
kube-system       Active   30h
//查看dep的控制器信息
[root@master ~]# kubectl get deployment myapp
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
myapp   3/3     3            3           20m
[root@master ~]# kubectl get deployment 
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
b1      0/1     1            0           23m
b2      1/1     1            1           22m
myapp   3/3     3            3           20m
nginx   1/1     1            1           24m
test    1/1     1            1           18m
//查看pod详细信息
[root@master ~]# kubectl get deployment myapp -o json
{
    "apiVersion": "apps/v1",
    "kind": "Deployment",
    "metadata": {
        "annotations": {
            "deployment.kubernetes.io/revision": "1"
        },
        "creationTimestamp": "2021-12-19T15:01:28Z",
        "generation": 1,
        "labels": {
            "app": "myapp"
        },
        "managedFields": [
            {
                "apiVersion": "apps/v1",
                "fieldsType": "FieldsV1",
                "fieldsV1": {
                    "f:metadata": {
                        "f:labels": {
                            ".": {},
                            "f:app": {}
                        }
                    },
                    "f:spec": {
.....以下多行省略                       
[root@master ~]# kubectl get deployment myapp -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2021-12-19T15:01:28Z"
  generation: 1
  labels:
    app: myapp
  managedFields:
  - apiVersion: apps/v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:labels:
          .: {}
          f:app: {}
      f:spec:
        f:progressDeadlineSeconds: {}
        f:replicas: {}
        f:revisionHistoryLimit: {}
        f:selector: {}
        f:strategy:
          f:rollingUpdate:
            .: {}
            f:maxSurge: {}
            f:maxUnavailable: {}
          f:type: {}
        f:template:
          f:metadata:
            f:labels:
              .: {}
              f:app: {}
          f:spec:
            f:containers:
              k:{"name":"nginx"}:
                .: {}
                f:image: {}
                f:imagePullPolicy: {}
                f:name: {}
                f:resources: {}
                f:terminationMessagePath: {}
                f:terminationMessagePolicy: {}
            f:dnsPolicy: {}
            f:restartPolicy: {}
            f:schedulerName: {}
            f:securityContext: {}
            f:terminationGracePeriodSeconds: {}
.....以下多行省略 

delete 删除

//删除myapp pod与svc
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   10         28m
b2-6b45bddb99-zh7n7      1/1     Running            1          27m
myapp-6d8d776547-49csx   1/1     Running            0          26m
myapp-6d8d776547-79kbw   1/1     Running            0          26m
myapp-6d8d776547-kvc2q   1/1     Running            0          26m
nginx-6799fc88d8-wknpz   1/1     Running            0          30m
test-7968d6985c-xcvpz    1/1     Running            0          23m
[root@master ~]# kubectl delete deployment,svc myapp
deployment.apps "myapp" deleted
service "myapp" deleted
[root@master ~]# kubectl get pods
NAME                     READY   STATUS             RESTARTS   AGE
b1-689554bb54-hzbgp      0/1     CrashLoopBackOff   10         29m
b2-6b45bddb99-zh7n7      1/1     Running            1          27m
myapp-6d8d776547-kvc2q   0/1     Terminating        0          26m
nginx-6799fc88d8-wknpz   1/1     Running            0          30m
test-7968d6985c-xcvpz    1/1     Running            0          24m
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1               443/TCP        31h
nginx        NodePort    10.111.40.207           80:30730/TCP   13m
//删除一个pod
[root@master ~]# kubectl delete deployment b1
deployment.apps "b1" deleted
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
b2-6b45bddb99-zh7n7      1/1     Running   1          30m
nginx-6799fc88d8-wknpz   1/1     Running   0          33m
test-7968d6985c-xcvpz    1/1     Running   0          27m
//删除pod不会影响svc,相反也一样
[root@master ~]# kubectl delete deployment nginx
deployment.apps "nginx" deleted
[root@master ~]# kubectl get pods
NAME                    READY   STATUS    RESTARTS   AGE
b2-6b45bddb99-zh7n7     1/1     Running   1          31m
test-7968d6985c-xcvpz   1/1     Running   0          28m
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1               443/TCP        31h
nginx        NodePort    10.111.40.207           80:30730/TCP   17m

[root@master ~]# kubectl delete svc nginx
service "nginx" deleted
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1            443/TCP   31h
//删除所有pod,指定dep控制器类型
[root@master ~]# kubectl delete deployment --all
deployment.apps "b2" deleted
deployment.apps "test" deleted
[root@master ~]# kubectl get pods
No resources found in default namespace.

run运行

//run 创建的是pod类型是自主式
[root@master ~]# kubectl run nginx --image nginx
pod/nginx created
[root@master ~]# kubectl get pod
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          20s
//删除类型也是pod
[root@master ~]# kubectl delete pod nginx
pod "nginx" deleted
[root@master ~]# kubectl get pod
No resources found in default namespace.

//创建一个pod,带标签
[root@master ~]# kubectl run nginx --image nginx --labels "app=nginx"
pod/nginx created
[root@master ~]# kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          6s
//describe描述nginx pod信息找到标签
[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node2.example.com/192.168.143.142
Start Time:   Sun, 19 Dec 2021 23:41:45 +0800
Labels:       app=nginx
.....以下多行省略
//删除带标签删除pod
[root@master ~]# kubectl get pods
NAME    READY   STATUS    RESTARTS   AGE
app     1/1     Running   0          10s
nginx   1/1     Running   0          3m3s
test    1/1     Running   0          16s
[root@master ~]# kubectl delete pod -l "app=nginx"
pod "app" deleted
pod "nginx" deleted
pod "test" deleted
[root@master ~]# kubectl get pods
No resources found in default namespace.
//dry-run 干运行 只是假装运行,没有运行,类似于测试
[root@master ~]# kubectl run app --image nginx --labels "app=nginx" --dry-run=client
pod/app created (dry run)
[root@master ~]# kubectl get pods
No resources found in default namespace.
//用-i -t 选项 进入pod
[root@master ~]# kubectl run -i -t busybox --image=busybox --restart=Never
If you don't see a command prompt, try pressing enter.
/ # 
/ # 
/ # ls
bin   dev   etc   home  proc  root  sys   tmp   usr   var
/ # ip a
1: lo:  mtu 65536 qdisc noqueue qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
3: eth0@if19:  mtu 1450 qdisc noqueue 
    link/ether 22:f1:73:35:96:2d brd ff:ff:ff:ff:ff:ff
    inet 10.244.2.17/24 brd 10.244.2.255 scope global eth0
       valid_lft forever preferred_lft forever
/ # exit
//命令完成后,就直接退出了
[root@master ~]# kubectl get pods
NAME      READY   STATUS      RESTARTS   AGE
busybox   0/1     Completed   0          96s

edit 编辑

[root@master ~]# kubectl run nginx --image nginx --labels "app=txt"
pod/nginx created
[root@master ~]# kubectl get pods
NAME      READY   STATUS      RESTARTS   AGE
busybox   0/1     Completed   0          22h
nginx     1/1     Running     0          15s
[root@master ~]# kubectl edit pods/nginx

# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2021-12-20T14:46:40Z"
  labels:
    app: txts //可以编辑标签
  name: nginx
  namespace: default
  resourceVersion: "15355"
  uid: 46c4dd31-5e7b-4dbc-b7cb-133859dc80cd
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: nginx
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-rbqzh
      readOnly: true
 //zz或wq!退出   
[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.143.141
Start Time:   Mon, 20 Dec 2021 22:46:40 +0800
Labels:       app=txts	//标签已经修改
......以下多行省略

scale扩展

//创建一个dep控制器的nginx
[root@master ~]# kubectl create deployment nginx --image nginx
deployment.apps/nginx created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          8m54s
nginx-6799fc88d8-bfcxp   1/1     Running     0          3s
//动态扩展
[root@master ~]# kubectl scale --replicas 6 deployment/nginx
deployment.apps/nginx scaled
[root@master ~]# kubectl get pods
NAME                     READY   STATUS              RESTARTS   AGE
busybox                  0/1     Completed           0          23h
nginx                    1/1     Running             0          9m45s
nginx-6799fc88d8-2cjw8   0/1     ContainerCreating   0          10s
nginx-6799fc88d8-bfcxp   1/1     Running             0          54s
nginx-6799fc88d8-bpkgq   1/1     Running             0          10s
nginx-6799fc88d8-gjfpn   1/1     Running             0          10s
nginx-6799fc88d8-lxh8g   1/1     Running             0          10s
nginx-6799fc88d8-v5dhn   1/1     Running             0          10s
//动态扩展调整
[root@master ~]# kubectl scale --replicas 2 deployment/nginx
deployment.apps/nginx scaled
[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          10m
nginx-6799fc88d8-2cjw8   1/1     Running     0          81s
nginx-6799fc88d8-bpkgq   1/1     Running     0          81s

autoscale 自动扩展

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          13m
nginx-6799fc88d8-2cjw8   1/1     Running     0          4m4s
nginx-6799fc88d8-bpkgq   1/1     Running     0          4m4s
//最少一个最多3个
[root@master ~]# kubectl autoscale --min 1 --max 3 --cpu-percent 70 deployment/nginx
horizontalpodautoscaler.autoscaling/nginx autoscaled
//hpa详细
[root@master ~]# kubectl get hpa
NAME    REFERENCE          TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
nginx   Deployment/nginx   /70%   1         3         0          10s
//还是运行了2个
[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          16m
nginx-6799fc88d8-2cjw8   1/1     Running     0          6m31s
nginx-6799fc88d8-bpkgq   1/1     Running     0          6m31s
[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          16m
nginx-6799fc88d8-2cjw8   1/1     Running     0          6m50s
nginx-6799fc88d8-bpkgq   1/1     Running     0          6m50s

describe描述

[root@master ~]# kubectl describe pod/nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.143.141
Start Time:   Mon, 20 Dec 2021 22:46:40 +0800
Labels:       app=txts
Annotations:  
Status:       Running
IP:           10.244.1.13
IPs:
  IP:  10.244.1.13

logs日志

//默认pod/nginx不需要指定,其他为,控制/nginx
[root@master ~]# kubectl logs nginx
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/12/20 14:46:43 [notice] 1#1: using the "epoll" event method
2021/12/20 14:46:43 [notice] 1#1: nginx/1.21.4
2021/12/20 14:46:43 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2021/12/20 14:46:43 [notice] 1#1: OS: Linux 3.10.0-862.el7.x86_64
2021/12/20 14:46:43 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/20 14:46:43 [notice] 1#1: start worker processes
2021/12/20 14:46:43 [notice] 1#1: start worker process 32
2021/12/20 14:46:43 [notice] 1#1: start worker process 33
2021/12/20 14:46:43 [notice] 1#1: start worker process 34
2021/12/20 14:46:43 [notice] 1#1: start worker process 35

exec进入容器

//pod类型
[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          24m
nginx-6799fc88d8-2cjw8   1/1     Running     0          15m
nginx-6799fc88d8-bpkgq   1/1     Running     0          15m
[root@master ~]# kubectl exec nginx -- date
Mon Dec 20 15:11:40 UTC 2021
[root@master ~]# kubectl exec -it nginx -- /bin/bash
root@nginx:/# ls
bin   docker-entrypoint.d   home   media  proc	sbin  tmp
boot  docker-entrypoint.sh  lib    mnt	  root	srv   usr
dev   etc		    lib64  opt	  run	sys   var
root@nginx:/# exit
exit
//deployment类型
[root@master ~]# kubectl exec nginx-6799fc88d8-2cjw8 -- date
Mon Dec 20 15:13:27 UTC 2021
[root@master ~]#  kubectl exec -it nginx-6799fc88d8-2cjw8 /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@nginx-6799fc88d8-2cjw8:/# ls
bin   docker-entrypoint.d   home   media  proc	sbin  tmp
boot  docker-entrypoint.sh  lib    mnt	  root	srv   usr
dev   etc		    lib64  opt	  run	sys   var
root@nginx-6799fc88d8-2cjw8:/# exit
exit

//svc模式
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1            443/TCP   2d6h
[root@master ~]# kubectl expose pod nginx --port 8080 --target-port 80
service/nginx exposed
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1             443/TCP    2d6h
nginx        ClusterIP   10.99.42.70           8080/TCP   23s
[root@master ~]# kubectl exec svc/nginx -- date
Mon Dec 20 15:18:40 UTC 2021
[root@master ~]# kubectl exec -it svc/nginx /bin/sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
# ls
bin   docker-entrypoint.d   home   media  proc	sbin  tmp
boot  docker-entrypoint.sh  lib    mnt	  root	srv   usr
dev   etc		    lib64  opt	  run	sys   var
# exit


port-forward端口转发

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          34m
nginx-6799fc88d8-2cjw8   1/1     Running     0          25m
nginx-6799fc88d8-bpkgq   1/1     Running     0          25m
[root@master ~]# kubectl port-forward deployment/nginx 80
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80

//此处前台运行开另一个终端查看
[root@master ~]# curl 127.0.0.1:80



Welcome to nginx!



Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

[root@master ~]# kubectl port-forward deployment/nginx :80 Forwarding from 127.0.0.1:45847 -> 80 Forwarding from [::1]:45847 -> 80 Handling connection for 45847 //此处前台运行开另一个终端查看 [root@master ~]# curl 127.0.0.1:45847 Welcome to nginx!

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

[root@master ~]# kubectl port-forward --address 0.0.0.0 deployment/nginx :80 Forwarding from 0.0.0.0:32930 -> 80 Handling connection for 32930 //此处前台运行开另一个终端查看 //因为0.0.0.0是所有主机,本机ip也可以访问 [root@master ~]# curl 192.168.143.140:32930 Welcome to nginx!

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

cp复制

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          42m
nginx-6799fc88d8-2cjw8   1/1     Running     0          32m
nginx-6799fc88d8-bpkgq   1/1     Running     0          32m
[root@master ~]# kubectl exec nginx test -- ls /opt/
[root@master ~]# 
[root@master ~]# ls
anaconda-ks.cfg  flannel.yaml  init
//本机文件复制到容器
[root@master ~]# kubectl cp /root/anaconda-ks.cfg nginx:/opt/
[root@master ~]# kubectl exec nginx test -- ls /opt/
anaconda-ks.cfg
[root@master ~]# 

overwrite覆盖标签

[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.143.141
Start Time:   Mon, 20 Dec 2021 22:46:40 +0800
Labels:       app=txts
......以下多行省略
//覆盖原有标签
[root@master ~]# kubectl label pod nginx --overwrite app=hy
pod/nginx labeled
[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.143.141
Start Time:   Mon, 20 Dec 2021 22:46:40 +0800
Labels:       app=hy

api-resources查看api资源信息

[root@master ~]# kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1 
.......以下多行省略

api-versions 查看版本号

[root@master ~]# kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
flowcontrol.apiserver.k8s.io/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

自愈功能

[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          50m
nginx-6799fc88d8-2cjw8   1/1     Running     0          40m
nginx-6799fc88d8-bpkgq   1/1     Running     0          40m
[root@master ~]# kubectl delete pod nginx-6799fc88d8-2cjw8
pod "nginx-6799fc88d8-2cjw8" deleted
//因为pod中的控制器有自愈功能,自动补全
[root@master ~]# kubectl get pods
NAME                     READY   STATUS      RESTARTS   AGE
busybox                  0/1     Completed   0          23h
nginx                    1/1     Running     0          50m
nginx-6799fc88d8-bpkgq   1/1     Running     0          41m
nginx-6799fc88d8-w8h48   1/1     Running     0          6s
//删除deployment/nginx
[root@master ~]# kubectl delete deployment nginx
deployment.apps "nginx" deleted
[root@master ~]# kubectl get pods
NAME                     READY   STATUS        RESTARTS   AGE
busybox                  0/1     Completed     0          23h
nginx                    1/1     Running       0          52m
nginx-6799fc88d8-bpkgq   0/1     Terminating   0          43m
nginx-6799fc88d8-w8h48   0/1     Terminating   0          2m5s
[root@master ~]# kubectl get pods
NAME      READY   STATUS      RESTARTS   AGE
busybox   0/1     Completed   0          23h
nginx     1/1     Running     0          52m

nginx测试创建

[root@master ~]# kubectl expose deployment nginx --port 8080 --target-port 80 --type NodePort
service/nginx exposed
[root@master ~]# kubectl get svc,pods
NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/kubernetes   ClusterIP   10.96.0.1                443/TCP          2d7h
service/nginx        NodePort    10.109.177.153           8080:32618/TCP   28s

NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-6799fc88d8-rhbz7   1/1     Running   0          2m5s
[root@master ~]# curl 10.109.177.153:8080



Welcome to nginx!



Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

Kubernetes(k8s)进阶_第1张图片

滚动更新,回滚

//制作apache镜像
[root@master apache]# cat Dockerfile 
FROM busybox

RUN mkdir /data && \
    echo "test page with v1" > /data/index.html

ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master apache]# docker build -t hyhxy0206/apache:v1 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> ffe9d497c324
Step 2/3 : RUN mkdir /data &&     echo "test page with v1" > /data/index.html
 ---> Running in 6ef5a9999027
Removing intermediate container 6ef5a9999027
 ---> 1f55d1956ec6
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in 9e953c76320f
Removing intermediate container 9e953c76320f
 ---> 8171aabbee2d
Successfully built 8171aabbee2d
Successfully tagged hyhxy0206/apache:v1
[root@master apache]# vim Dockerfile
[root@master apache]# docker build -t hyhxy0206/apache:v2 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> ffe9d497c324
Step 2/3 : RUN mkdir /data &&     echo "test page with v2" > /data/index.html
 ---> Running in 591e79d258a9
Removing intermediate container 591e79d258a9
 ---> 47cda9c6f56f
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in 03aab99e17ce
Removing intermediate container 03aab99e17ce
 ---> 9731bddd2d85
Successfully built 9731bddd2d85
Successfully tagged hyhxy0206/apache:v2
[root@master apache]# docker images
REPOSITORY                                                        TAG        IMAGE ID       CREATED              SIZE
hyhxy0206/apache                                                  v2         9731bddd2d85   About a minute ago   1.24MB
hyhxy0206/apache                                                  v1         8171aabbee2d   About a minute ago   1.24MB

[root@master apache]# docker login
[root@master apache]# docker push hyhxy0206/apache:v1
[root@master apache]# docker push hyhxy0206/apache:v2、

//用v1版本运行3个pod
[root@master ~]# kubectl create deployment web --image hyhxy0206/apache:v1 --replicas 3
deployment.apps/web created
[root@master ~]# kubectl get pods
NAME                   READY   STATUS              RESTARTS   AGE
web-65bbbfdf58-7gfnr   0/1     ContainerCreating   0          6s
web-65bbbfdf58-k52hl   0/1     ContainerCreating   0          6s
web-65bbbfdf58-nf6tg   0/1     ContainerCreating   0          6s
[root@master ~]# kubectl expose deploy web --port 80 --target-port 80
service/web exposed
[root@master ~]# kubectl get svc,pods
NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1                443/TCP   2d23h
service/web          ClusterIP   10.106.145.169           80/TCP    13s

NAME                       READY   STATUS    RESTARTS   AGE
pod/web-65bbbfdf58-7gfnr   1/1     Running   0          60s
pod/web-65bbbfdf58-k52hl   1/1     Running   0          60s
pod/web-65bbbfdf58-nf6tg   1/1     Running   0          60s

[root@master ~]# while :;do curl 10.106.145.169;done
//设置镜像使其滚动升级
[root@master ~]# kubectl set image deploy/web apache=hyhxy0206/apache:v2
deployment.apps/web image updated

[root@master ~]# while :;do curl 10.101.67.172;done
test page with v2
test page with v2
test page with v2
test page with v2
test page with v2
test page with v2

//运行命令回滚,上一版本
[root@master ~]# kubectl rollout undo deploy/web
deployment.apps/web rolled back
[root@master ~]# while :;do curl 10.101.67.172;done
test page with v1
test page with v1
test page with v1
test page with v1
test page with v1
test page with v1

[root@master ~]# kubectl rollout undo deploy/web
deployment.apps/web rolled back
[root@master ~]# while :;do curl 10.101.67.172;done
test page with v2
test page with v2
test page with v2
test page with v2
test page with v2
test page with v2


k8s,yaml语言,配置pod

[root@master manifest]# vi deploy.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: default
spec: 
  replicas: 3
  selector:
    matchLabels: 
      app: apache
  template:
    metadata:
      labels: 
        app: apache
    spec:
      containers:
      - image: hyhxy0206/apache:v1
        imagePullPolicy: IfNotPresent
        name: httpd
        
 //删除       
[root@master manifest]# kubectl delete -f deploy.yaml
deployment.apps "web" deleted

//创建        
[root@master manifest]# kubectl create -f deploy.yaml
deployment.apps/web created
[root@master manifest]# kubectl get pods
NAME                  READY   STATUS    RESTARTS   AGE
web-958568cb4-4v9m2   1/1     Running   0          6s
web-958568cb4-cb8jf   1/1     Running   0          6s
web-958568cb4-wn277   1/1     Running   0          6s
//应用
[root@master manifest]# kubectl apply -f deploy.yaml
Warning: resource deployments/web is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically.
deployment.apps/web configured

[root@master manifest]# vi svc-deploy.yaml 
apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: default
spec:
  ports:
  - port: 8001
    protocol: TCP
    targetPort: 80
  selector:
    app: apache
  type: NodePort

[root@master manifest]# kubectl apply -f svc-deploy.yaml 
service/web created

[root@master manifest]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
kubernetes   ClusterIP   10.96.0.1               443/TCP          3d
web          NodePort    10.102.127.93           8001:32310/TCP   43s
[root@master manifest]# curl 192.168.143.140:32310
test page with v1

[root@master manifest]# vim deploy.yaml
//v1版本修改为v2
[root@master manifest]# kubectl apply -f deploy.yaml 
deployment.apps/web configured
[root@master manifest]# curl 192.168.143.140:32310
test page with v2

合并
[root@master manifest]# cat deploy.yaml 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: default
spec: 
  replicas: 3
  selector:
    matchLabels: 
      app: apache
  template:
    metadata:
      labels: 
        app: apache
    spec:
      containers:
      - image: hyhxy0206/apache:v2
        imagePullPolicy: IfNotPresent
        name: httpd
---
apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: default
spec:
  ports:
  - port: 8001
    protocol: TCP
    targetPort: 80
  selector:
    app: apache
  type: NodePort
//创建查看效果
[root@master manifest]# kubectl create -f deploy.yaml 
deployment.apps/web created
service/web created
[root@master manifest]# kubectl get svc,pods
NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/kubernetes   ClusterIP   10.96.0.1                443/TCP          3d1h
service/web          NodePort    10.100.255.213           8001:32184/TCP   21s

NAME                       READY   STATUS    RESTARTS   AGE
pod/web-5d8db7d5d5-bqxv6   1/1     Running   0          21s
pod/web-5d8db7d5d5-tbvcd   1/1     Running   0          21s
pod/web-5d8db7d5d5-tglzc   1/1     Running   0          21s

[root@master manifest]# vim deploy.yaml 
//v2版本改为v1
[root@master manifest]# kubectl  -f deploy.yaml 
deploy.yaml      svc-deploy.yaml 
[root@master manifest]# kubectl apply -f deploy.yaml 
Warning: resource deployments/web is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically.
deployment.apps/web configured
Warning: resource services/web is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically.
service/web configured
[root@master manifest]# kubectl get svc,pods
NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/kubernetes   ClusterIP   10.96.0.1                443/TCP          3d1h
service/web          NodePort    10.100.255.213           8001:32184/TCP   93s

NAME                       READY   STATUS        RESTARTS   AGE
pod/web-5d8db7d5d5-bqxv6   1/1     Terminating   0          93s
pod/web-5d8db7d5d5-tbvcd   1/1     Terminating   0          93s
pod/web-5d8db7d5d5-tglzc   1/1     Terminating   0          93s
pod/web-958568cb4-g6vjb    1/1     Running       0          11s
pod/web-958568cb4-hjndq    1/1     Running       0          9s
pod/web-958568cb4-n76tt    1/1     Running       0          13s
[root@master manifest]# curl 192.168.143.140:32184
test page with v1


create命令导出yaml格式

[root@master manifest]# kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx.yaml
[root@master manifest]# cat nginx.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: nginx
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
status: {}

get命令导出yaml格式

[root@master manifest]# kubectl create deployment nginx --image=nginx --replicas 3
deployment.apps/nginx created
[root@master manifest]# kubectl get deploy
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   2/3     3            2           7s
web     3/3     3            3           7m54s
[root@master manifest]# kubectl get deploy -o yaml > nginx1.yaml
[root@master manifest]# cat nginx1.yaml 
apiVersion: v1
items:
- apiVersion: apps/v1
  kind: Deployment
  metadata:
    annotations:
      deployment.kubernetes.io/revision: "1"
    creationTimestamp: "2021-12-21T09:38:04Z"
    generation: 1
    labels:
      app: nginx
    managedFields:
    - apiVersion: apps/v1
      fieldsType: FieldsV1
      fieldsV1:
        f:metadata:
          f:labels:
            .: {}
            f:app: {}
        f:spec:
          f:progressDeadlineSeconds: {}
          f:replicas: {}
          f:revisionHistoryLimit: {}
          f:selector: {}
          f:strategy:
            f:rollingUpdate:
              .: {}
              f:maxSurge: {}
              f:maxUnavailable: {}
            f:type: {}
          f:template:
            f:metadata:
              f:labels:
                .: {}
                f:app: {}
            f:spec:
              f:containers:
                k:{"name":"nginx"}:
                  .: {}
                  f:image: {}
                  f:imagePullPolicy: {}
                  f:name: {}
                  f:resources: {}
                  f:terminationMessagePath: {}
                  f:terminationMessagePolicy: {}
              f:dnsPolicy: {}
              f:restartPolicy: {}
              f:schedulerName: {}
              f:securityContext: {}
              f:terminationGracePeriodSeconds: {}
      manager: kubectl-create
      operation: Update
      time: "2021-12-21T09:38:04Z"
    - apiVersion: apps/v1
      fieldsType: FieldsV1
      fieldsV1:
        f:metadata:
          f:annotations:
            .: {}
            f:deployment.kubernetes.io/revision: {}
        f:status:
          f:availableReplicas: {}
          f:conditions:
            .: {}
            k:{"type":"Available"}:
              .: {}
              f:lastTransitionTime: {}
              f:lastUpdateTime: {}
              f:message: {}
              f:reason: {}
              f:status: {}
              f:type: {}
            k:{"type":"Progressing"}:
              .: {}
              f:lastTransitionTime: {}
              f:lastUpdateTime: {}
              f:message: {}
              f:reason: {}
              f:status: {}
              f:type: {}
          f:observedGeneration: {}
          f:readyReplicas: {}
          f:replicas: {}
          f:updatedReplicas: {}
      manager: kube-controller-manager
      operation: Update
      time: "2021-12-21T09:38:33Z"
    name: nginx
    namespace: default
    resourceVersion: "32145"
    uid: 6d8c9da2-8538-4291-a0b1-dbf72f41504b
  spec:
    progressDeadlineSeconds: 600
    replicas: 3
    revisionHistoryLimit: 10
    selector:
      matchLabels:
        app: nginx
    strategy:
      rollingUpdate:
        maxSurge: 25%
        maxUnavailable: 25%
      type: RollingUpdate
    template:
      metadata:
        creationTimestamp: null
        labels:
          app: nginx
      spec:
        containers:
        - image: nginx
          imagePullPolicy: Always
          name: nginx
          resources: {}
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
        dnsPolicy: ClusterFirst
        restartPolicy: Always
        schedulerName: default-scheduler
        securityContext: {}
        terminationGracePeriodSeconds: 30
  status:
    availableReplicas: 3
    conditions:
    - lastTransitionTime: "2021-12-21T09:38:33Z"
      lastUpdateTime: "2021-12-21T09:38:33Z"
      message: Deployment has minimum availability.
      reason: MinimumReplicasAvailable
      status: "True"
      type: Available
    - lastTransitionTime: "2021-12-21T09:38:04Z"
      lastUpdateTime: "2021-12-21T09:38:33Z"
      message: ReplicaSet "nginx-6799fc88d8" has successfully progressed.
      reason: NewReplicaSetAvailable
      status: "True"
      type: Progressing
    observedGeneration: 1
    readyReplicas: 3
    replicas: 3
    updatedReplicas: 3
- apiVersion: apps/v1
  kind: Deployment
  metadata:
    annotations:
      deployment.kubernetes.io/revision: "2"
      kubectl.kubernetes.io/last-applied-configuration: |
        {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"web","namespace":"default"},"spec":{"replicas":3,"selector":{"matchLabels":{"app":"apache"}},"template":{"metadata":{"labels":{"app":"apache"}},"spec":{"containers":[{"image":"hyhxy0206/apache:v1","imagePullPolicy":"IfNotPresent","name":"httpd"}]}}}}
    creationTimestamp: "2021-12-21T09:30:17Z"
    generation: 2
    managedFields:
    - apiVersion: apps/v1
      fieldsType: FieldsV1
      fieldsV1:
        f:spec:
          f:progressDeadlineSeconds: {}
          f:replicas: {}
          f:revisionHistoryLimit: {}
          f:selector: {}
          f:strategy:
            f:rollingUpdate:
              .: {}
              f:maxSurge: {}
              f:maxUnavailable: {}
            f:type: {}
          f:template:
            f:metadata:
              f:labels:
                .: {}
                f:app: {}
            f:spec:
              f:containers:
                k:{"name":"httpd"}:
                  .: {}
                  f:imagePullPolicy: {}
                  f:name: {}
                  f:resources: {}
                  f:terminationMessagePath: {}
                  f:terminationMessagePolicy: {}
              f:dnsPolicy: {}
              f:restartPolicy: {}
              f:schedulerName: {}
              f:securityContext: {}
              f:terminationGracePeriodSeconds: {}
      manager: kubectl-create
      operation: Update
      time: "2021-12-21T09:30:17Z"
    - apiVersion: apps/v1
      fieldsType: FieldsV1
      fieldsV1:
        f:metadata:
          f:annotations:
            f:kubectl.kubernetes.io/last-applied-configuration: {}
        f:spec:
          f:template:
            f:spec:
              f:containers:
                k:{"name":"httpd"}:
                  f:image: {}
      manager: kubectl-client-side-apply
      operation: Update
      time: "2021-12-21T09:31:37Z"
    - apiVersion: apps/v1
      fieldsType: FieldsV1
      fieldsV1:
        f:metadata:
          f:annotations:
            .: {}
            f:deployment.kubernetes.io/revision: {}
        f:status:
          f:availableReplicas: {}
          f:conditions:
            .: {}
            k:{"type":"Available"}:
              .: {}
              f:lastTransitionTime: {}
              f:lastUpdateTime: {}
              f:message: {}
              f:reason: {}
              f:status: {}
              f:type: {}
            k:{"type":"Progressing"}:
              .: {}
              f:lastTransitionTime: {}
              f:lastUpdateTime: {}
              f:message: {}
              f:reason: {}
              f:status: {}
              f:type: {}
          f:observedGeneration: {}
          f:readyReplicas: {}
          f:replicas: {}
          f:updatedReplicas: {}
      manager: kube-controller-manager
      operation: Update
      time: "2021-12-21T09:31:43Z"
    name: web
    namespace: default
    resourceVersion: "31516"
    uid: 0e15d3ef-a2ca-412b-bb09-d2387542581f
  spec:
    progressDeadlineSeconds: 600
    replicas: 3
    revisionHistoryLimit: 10
    selector:
      matchLabels:
        app: apache
    strategy:
      rollingUpdate:
        maxSurge: 25%
        maxUnavailable: 25%
      type: RollingUpdate
    template:
      metadata:
        creationTimestamp: null
        labels:
          app: apache
      spec:
        containers:
        - image: hyhxy0206/apache:v1
          imagePullPolicy: IfNotPresent
          name: httpd
          resources: {}
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
        dnsPolicy: ClusterFirst
        restartPolicy: Always
        schedulerName: default-scheduler
        securityContext: {}
        terminationGracePeriodSeconds: 30
  status:
    availableReplicas: 3
    conditions:
    - lastTransitionTime: "2021-12-21T09:30:19Z"
      lastUpdateTime: "2021-12-21T09:30:19Z"
      message: Deployment has minimum availability.
      reason: MinimumReplicasAvailable
      status: "True"
      type: Available
    - lastTransitionTime: "2021-12-21T09:30:17Z"
      lastUpdateTime: "2021-12-21T09:31:43Z"
      message: ReplicaSet "web-958568cb4" has successfully progressed.
      reason: NewReplicaSetAvailable
      status: "True"
      type: Progressing
    observedGeneration: 2
    readyReplicas: 3
    replicas: 3
    updatedReplicas: 3
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""

pod容器字段帮助文档

[root@master manifest]# kubectl explain deployment
KIND:     Deployment
VERSION:  apps/v1

DESCRIPTION:
     Deployment enables declarative updates for Pods and ReplicaSets.

FIELDS:
   apiVersion	
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind	
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata	
     Standard object metadata.

   spec	
     Specification of the desired behavior of the Deployment.

   status	
     Most recently observed status of the Deployment.

[root@master manifest]# kubectl explain pods
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion	
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind	
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata	
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec	
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status	
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status


 
  

创建新的名称空间

[root@master manifest]# vim deploy.yaml 
---
apiVersion: v1
kind: Namespace
metadata:
  name: runtime
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: runtime
spec: 
  replicas: 3
  selector:
    matchLabels: 
      app: apache
  template:
    metadata:
      labels: 
        app: apache
    spec:
      containers:
      - image: hyhxy0206/apache:v1
        imagePullPolicy: IfNotPresent
        name: httpd
---
apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: runtime
spec:
  ports:
  - port: 8001
    protocol: TCP
    targetPort: 80
  selector:
    app: apache
  type: NodePort

[root@master manifest]# kubectl get pods,svc
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1            443/TCP   3d5h
[root@master manifest]# kubectl create -f deploy.yaml 
namespace/runtime created
deployment.apps/web created
service/web created
[root@master manifest]# kubectl get ns
NAME              STATUS   AGE
default           Active   3d5h
kube-node-lease   Active   3d5h
kube-public       Active   3d5h
kube-system       Active   3d5h
runtime           Active   20s
[root@master manifest]# kubectl get pods -n runtime
NAME                  READY   STATUS    RESTARTS   AGE
web-958568cb4-jkkb7   1/1     Running   0          39s
web-958568cb4-kk8vt   1/1     Running   0          39s
web-958568cb4-msqnl   1/1     Running   0          39s
[root@master manifest]# kubectl get deploy -n runtime
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    3/3     3            3           76s
[root@master manifest]# kubectl get svc -n runtime
NAME   TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
web    NodePort   10.109.160.27           8001:30057/TCP   87s
[root@master manifest]# curl 10.109.160.27:8001
test page with v1
[root@master manifest]# curl 192.168.143.140:30057
test page with v1

重启策略
Always:当容器终止退出后,总是重启容器,默认策略。

OnFailure:当容器异常退出(退出状态码非0)时,才重启容器。

Never:当容器终止退出,从不重启容器。

健康检查类型
livenessProbe (存活检查)∶如果检查失败,将杀死容器,根据Pod的restartPolicy来操作。

readinessProbe (就绪检查)︰如果检查失败,Kubernetes会把Podservice endpoints中剔除

支持的检查方法
httpGet:发送HTTP请求,返回200-400范围状态码为成功。
exec:执行Shell命令返回状态码是0为成功。
tcpSocket:发起TCP Socket建立成功。

初始化容器
InitContainer:顾名思义,用于初始化工作,执行完就结束,可以理解为一次性任务
支持大部分应用容器配置,但不支持健康检查
优先应用容器执行

通过资源定义方式创建haproxy的pod进行负载均衡yml文件

[root@master manifest]# cat haproxy.yaml 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rs1
  namespace: default
spec: 
  replicas: 1
  selector:
    matchLabels: 
      app: apache
  template:
    metadata:
      labels: 
        app: apache
    spec:
      containers:
      - image: hyhxy0206/apache:v1
        imagePullPolicy: IfNotPresent
        name: httpd
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: haproxy
  namespace: default
spec: 
  replicas: 1
  selector:
    matchLabels: 
      app: haproxy
  template:
    metadata:
      labels: 
        app: haproxy
    spec:
      containers:
      - image: hyhxy0206/haproxy:v3
        imagePullPolicy: IfNotPresent
        name: haproxy
        volumeMounts:
        - mountPath: /tmp
          name: nfs
      volumes:
      - name: nfs
        nfs:
          server: 192.168.143.102       
          path: /nfs
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rs2
  namespace: default
spec: 
  replicas: 1
  selector:
    matchLabels: 
      app: apache
  template:
    metadata:
      labels: 
        app: apache
    spec:
      containers:
      - image: hyhxy0206/apache:v2
        imagePullPolicy: IfNotPresent
        name: httpd
---
apiVersion: v1
kind: Service
metadata:
  name: rs1
  namespace: default
spec:
  ports:
  - port: 8001
    protocol: TCP
    targetPort: 80
  selector:
    app: apache
  type: NodePort
---
apiVersion: v1
kind: Service
metadata:
  name: rs2
  namespace: default
spec:
  ports:
  - port: 8002
    protocol: TCP
    targetPort: 80
  selector:
    app: apache
  type: NodePort
---
apiVersion: v1
kind: Service
metadata:
  name: haproxy
  namespace: default
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: haproxy
  type: NodePort
[root@master manifest]# kubectl create -f haproxy.yaml 
deployment.apps/rs1 created
deployment.apps/haproxy created
deployment.apps/rs2 created
service/rs1 created
service/rs2 created
service/haproxy created

[root@master manifest]# kubectl get svc,pods
NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/haproxy      NodePort    10.105.152.235           80:31969/TCP     61s
service/kubernetes   ClusterIP   10.96.0.1                443/TCP          3d8h
service/rs1          NodePort    10.99.151.119            8001:31939/TCP   61s
service/rs2          NodePort    10.101.239.75            8002:30515/TCP   61s

NAME                          READY   STATUS              RESTARTS   AGE
pod/haproxy-7cf79cc57-4jzvl   0/1     ContainerCreating   0          61s
pod/rs1-958568cb4-8tcpn       1/1     Running             0          61s
pod/rs2-5d8db7d5d5-s5qpz      1/1     Running             0          61s
[root@master manifest]# curl 10.101.239.75:8002
test page with v2
[root@master manifest]# curl 10.99.151.119:8001
test page with v1


ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号