kubernets管理(kubectl+文件形式管理)

kubernets管理

kubectl

Kubectl是管理k8s集群的命令行工具,通过生成的json格式传递给apiserver进行创建、查看、管理的操作。

//帮助信息

[root@master dashboard]# 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            在集群中运行一个指定的镜像 //等同于docker 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          为 Deployment, ReplicaSet, Replication Controller 或者 Job
设置一个新的副本数量  //设置副本数量(弹性伸缩)
  autoscale      自动调整一个 Deployment, ReplicaSet, 或者
ReplicationController 的副本数量  //自动调整一个副本集 自动弹性伸缩

Cluster Management Commands:集群管理指令
  certificate    修改 certificate 资源.  //申请证书颁发时
  cluster-info   显示集群信息
  top            Display Resource (CPU/Memory/Storage) usage.  //查看资源状态
  cordon         标记 node 为 unschedulable  //设置标记 配合taint使用
  uncordon       标记 node 为 schedulable  //设置标记
  drain          Drain node in preparation for maintenance  //节点维护时使用的指令
  taint          更新一个或者多个 node 上的 taints  //污点 一旦node被设置为污点,pod资源不会创建在污点标记上

Troubleshooting and Debugging Commands:
  describe       显示一个指定 resource 或者 group 的 resources 详情  //作用于排障 查看pod资源详细信息
  logs           输出容器在 pod 中的日志  //作用于排障 输出容器在pod中的日志
  attach         Attach 到一个运行中的 container  //用于远程连接
  exec           在一个 container 中执行一个命令  //用于进入容器 跟容器进行交互
  port-forward   Forward one or more local ports to a pod  //端口转发 转发到一个和多个本地的端口
  proxy          运行一个 proxy 到 Kubernetes API server  //做代理 代理apiserver
  cp             复制 files 和 directories 到 containers  //复制
和从容器中复制 files 和 directories.
  auth           Inspect authorization  //验证

Advanced Commands:
  apply          通过文件名或标准输入流(stdin)对资源进行配置  //通过文件名或标准输入流对资源进行配置
  patch          使用 strategic merge patch 更新一个资源的 field(s)  //更新一个资源
  replace        通过 filename 或者 stdin替换一个资源  //替换
  wait           Experimental: Wait for a specific condition on one or many
resources.
  convert        在不同的 API versions 转换配置文件  //二次开发

Settings Commands:
  label          更新在这个资源上的 labels //打标签注释
  annotate       更新一个资源的注解 //设置
  completion     Output shell completion code for the specified shell (bash or
zsh) //输出终端的代码

Other Commands:
  alpha          Commands for features in alpha
  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 <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all
commands).

pod
deployment 控制器 业务更新/回滚
replicaset 副本集 宕机,先创建再删除
service 做负载均衡

-w 查看创建资源的过程
-o wide 查看创建资源的地址

项目的生命周期
创建—>发布—>更新—>回滚—>删除
//创建 kubectl run命令

1.创建nginx

kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas]
[--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...] [options
[root@master ~]# kubectl run nginx --image=nginx:latest --port=80 --replicas=3
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx created

kubectl get pods -w //查看资源创建
[root@master ~]# kubectl get pods -w
NAME                     READY   STATUS              RESTARTS   AGE
nginx-7697996758-2jwtg   0/1     ContainerCreating   0          2s
nginx-7697996758-hf572   0/1     ContainerCreating   0          2s
nginx-7697996758-z47pt   0/1     ContainerCreating   0          2s
nginx-7697996758-hf572   1/1   Running   0     3s
nginx-7697996758-2jwtg   1/1   Running   0     3s
nginx-7697996758-z47pt   1/1   Running   0     6s

kubectl get pods -o wide //查看创建资源的地址
[root@master ~]# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE
nginx-7697996758-2jwtg   1/1     Running   0          38s   172.17.59.2   192.168.20.30   <none>
nginx-7697996758-hf572   1/1     Running   0          38s   172.17.42.4   192.168.20.20   <none>
nginx-7697996758-z47pt   1/1     Running   0          38s   172.17.42.2   192.168.20.20   <none>

kubectl get all //查看所有资源
[root@master ~]# kubectl get pods 
NAME                     READY   STATUS    RESTARTS   AGE
nginx-7697996758-2jwtg   1/1     Running   0          18s
nginx-7697996758-hf572   1/1     Running   0          18s
nginx-7697996758-z47pt   1/1     Running   0          18s
[root@master ~]# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP            NODE            NOMINATED NODE
nginx-7697996758-2jwtg   1/1     Running   0          38s   172.17.59.2   192.168.20.30   <none>
nginx-7697996758-hf572   1/1     Running   0          38s   172.17.42.4   192.168.20.20   <none>
nginx-7697996758-z47pt   1/1     Running   0          38s   172.17.42.2   192.168.20.20   <none>
[root@master ~]# kubectl get all
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-7697996758-2jwtg   1/1     Running   0          82s
pod/nginx-7697996758-hf572   1/1     Running   0          82s
pod/nginx-7697996758-z47pt   1/1     Running   0          82s

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP   2d15h

NAME                    DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   3         3         3            3           82s

NAME                               DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-7697996758   3         3         3       82s

[root@master ~]# kubectl get pods,deployment
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-7697996758-2jwtg   1/1     Running   0          105s
pod/nginx-7697996758-hf572   1/1     Running   0          105s
pod/nginx-7697996758-z47pt   1/1     Running   0          105s

NAME                          DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.extensions/nginx   3         3         3            3           105s

[root@master ~]# kubectl get pods,deployment,replicaset
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-7697996758-2jwtg   1/1     Running   0          2m11s
pod/nginx-7697996758-hf572   1/1     Running   0          2m11s
pod/nginx-7697996758-z47pt   1/1     Running   0          2m11s

NAME                          DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.extensions/nginx   3         3         3            3           2m11s

NAME                                     DESIRED   CURRENT   READY   AGE
replicaset.extensions/nginx-7697996758   3         3         3       2m11s

2.发布nginx service提供负载均衡的功能

kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP|SCTP]
[--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]
[options]

[root@master ~]# kubectl expose deployment nginx --port=80 --target-port=80 --name=nginx-service --type=NodePort
service/nginx-service exposed

[root@master ~]# kubectl get pods,svc
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-7697996758-2jwtg   1/1     Running   0          3m4s
pod/nginx-7697996758-hf572   1/1     Running   0          3m4s
pod/nginx-7697996758-z47pt   1/1     Running   0          3m4s

NAME                    TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
service/kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        2d15h
service/nginx-service   NodePort    10.0.0.193   <none>        80:35505/TCP   22s
[root@master ~]# kubectl api-resources //查看资源对象简写

kubectl get ep //查看内部的终端节点的ip及端口 (查看关联后端的端口)
[root@master ~]# kubectl get endpoints
NAME            ENDPOINTS                                      AGE
kubernetes      192.168.20.10:6443,192.168.20.40:6443          2d15h
nginx-service   172.17.42.2:80,172.17.42.4:80,172.17.59.2:80   115s
[root@master ~]#  kubectl get ep
NAME            ENDPOINTS                                      AGE
kubernetes      192.168.20.10:6443,192.168.20.40:6443          2d15h
nginx-service   172.17.42.2:80,172.17.42.4:80,172.17.59.2:80   2m36s

//网络状态详细信息

[root@master ~]#  kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE     IP            NODE            NOMINATED NODE
nginx-7697996758-2jwtg   1/1     Running   0          6m17s   172.17.59.2   192.168.20.30   <none>
nginx-7697996758-hf572   1/1     Running   0          6m17s   172.17.42.4   192.168.20.20   <none>
nginx-7697996758-z47pt   1/1     Running   0          6m17s   172.17.42.2   192.168.20.20   <none>

[root@node1 ~]# docker ps -a 
CONTAINER ID        IMAGE                                                                 COMMAND                  CREATED             STATUS                  PORTS               NAMES
30cc224dc19a        nginx                                                                 "/docker-entrypoint.…"   42 minutes ago      Up 42 minutes                               k8s_nginx_nginx-7697996758-z47pt_default_68b819ba-0b81-11eb-aede-000c29959657_0
8c8d43d5cbee        nginx                                                                 "/docker-entrypoint.…"   42 minutes ago      Up 42 minutes                               k8s_nginx_nginx-7697996758-hf572_default_68b9cb4f-0b81-11eb-aede-000c29959657_0
[root@node2 ~]# docker ps -a 
CONTAINER ID        IMAGE                                                                 COMMAND                  CREATED             STATUS                    PORTS               NAMES
8195ecf87b94        nginx                                                                 "/docker-entrypoint.…"   43 minutes ago      Up 43 minutes                                 k8s_nginx_nginx-7697996758-2jwtg_default_68b9b4ee-0b81-11eb-aede-000c29959657_0

//服务暴露的端口

[root@master ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        2d15h
nginx-service   NodePort    10.0.0.193   <none>        80:35505/TCP   4m21s

[root@master ~]# kubectl get all
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-7697996758-2jwtg   1/1     Running   0          46m
pod/nginx-7697996758-hf572   1/1     Running   0          46m
pod/nginx-7697996758-z47pt   1/1     Running   0          46m

NAME                    TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
service/kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        2d16h
service/nginx-service   NodePort    10.0.0.193   <none>        80:35505/TCP   44m

NAME                    DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   3         3         3            3           46m

NAME                               DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-7697996758   3         3         3       46m

//可以在浏览器访问

http://192.168.20.20:35505/
http://192.168.20.30:35505/

在这里插入图片描述在这里插入图片描述

//在node01操作,查看负载均衡端口35505
//kubernetes里kube-proxy支持三种模式,在v1.8之前我们使用的是iptables 以及 userspace两种模式,在kubernetes 1.8之后引入了ipvs模式

[root@node1 ~]# yum -y install ipvsadm
//可以跨节点的负载均衡 flannel组件完成
三个副本 不论访问哪个节点,都是轮询的访问这三个 proxy组件完成 rr轮询
[root@node1 ~]# ipvsadm -L -n
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  127.0.0.1:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  172.17.42.0:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  172.17.42.0:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  172.17.42.1:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  192.168.20.20:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  192.168.20.20:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  192.168.122.1:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  192.168.122.1:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  10.0.0.1:443 rr
  -> 192.168.20.10:6443           Masq    1      0          0         
  -> 192.168.20.40:6443           Masq    1      1          0         
TCP  10.0.0.193:80 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  10.0.0.224:443 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  127.0.0.1:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  172.17.42.1:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         

//在node02操作 同样安装ipvsadmin工具查看

[root@node1 ~]# yum -y install ipvsadm
[root@node2 ~]# ipvsadm -L -n
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  127.0.0.1:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  172.17.59.0:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  172.17.59.1:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  172.17.59.1:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  192.168.20.30:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  192.168.20.30:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  192.168.122.1:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  192.168.122.1:35505 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  10.0.0.1:443 rr
  -> 192.168.20.10:6443           Masq    1      0          0         
  -> 192.168.20.40:6443           Masq    1      0          0         
TCP  10.0.0.193:80 rr
  -> 172.17.42.2:80               Masq    1      0          0         
  -> 172.17.42.4:80               Masq    1      0          0         
  -> 172.17.59.2:80               Masq    1      0          0         
TCP  10.0.0.224:443 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  127.0.0.1:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         
TCP  172.17.59.0:30001 rr
  -> 172.17.42.3:8443             Masq    1      0          0         

//在master01操作 查看访问日志(注意:如果访问其他node无法访问检查proxy组件)

[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-7697996758-2jwtg   1/1     Running   0          59m
nginx-7697996758-hf572   1/1     Running   0          59m
nginx-7697996758-z47pt   1/1     Running   0          59m

[root@master ~]# kubectl logs nginx-7697996758-2jwtg
/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: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: 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: Configuration complete; ready for start up
172.17.59.1 - - [11/Oct/2020:06:10:26 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4270.0 Safari/537.36" "-"
2020/10/11 06:10:26 [error] 28#28: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.59.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.20.30:35505", referrer: "http://192.168.20.30:35505/"
172.17.59.1 - - [11/Oct/2020:06:10:26 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.20.30:35505/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4270.0 Safari/537.36" "-"
[root@master ~]# kubectl logs nginx-7697996758-hf572
[root@master ~]# kubectl logs nginx-7697996758-z47pt

3:更新nginx 为1.14版本
//谷歌浏览器重新加载刷新页面查看nginx版本信息
在这里插入图片描述

[root@master ~]# kubectl set --help
Configure application resources 

These commands help you make changes to existing application resources.

Available Commands:
  env            Update environment variables on a pod template  //环境变量
  image          更新一个 pod template 的镜像  //镜像
  resources      在对象的 pod templates 上更新资源的 requests/limits  //资源
  selector       设置 resource 的 selector  //选择器
  serviceaccount Update ServiceAccount of a resource
  subject        Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding  //项目

Usage:
  kubectl set SUBCOMMAND [options]

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

//获取修改模板

[root@master ~]# kubectl set image --help
Update existing container image(s) of resources. 

Possible resources include (case insensitive): 

  pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), replicaset (rs)

Examples:
  # Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.
  kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
  
  # Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'
  kubectl set image deployments,rc nginx=nginx:1.9.1 --all
  
  # Update image of all containers of daemonset abc to 'nginx:1.9.1'
  kubectl set image daemonset abc *=nginx:1.9.1
  
  # Print result (in yaml format) of updating nginx container image from local file, without hitting the server
  kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml

Options:
      --all=false: Select all resources, including uninitialized ones, in the namespace of the specified resource types
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server.
      --include-uninitialized=false: If true, the kubectl command applies to uninitialized objects. If explicitly set to
false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all".
Objects with empty metadata.initializers are regarded as initialized.
      --local=false: If true, set image will NOT contact api-server but run locally.
  -o, --output='': Output format. One of:
json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath|jsonpath-file.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
  -l, --selector='': Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and
'!='.(e.g. -l key1=value1,key2=value2)
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

Usage:
  kubectl set image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N
[options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

[root@master ~]# kubectl set image deployment/nginx nginx=nginx:1.14
deployment.extensions/nginx image updated
[root@master ~]#  kubectl get pods -w  //更新的过程,先创建再删除
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6ff7c89c7c-zp5d9   0/1     ContainerCreating   0          11s
nginx-7697996758-2jwtg   1/1     Running             0          106m
nginx-7697996758-hf572   1/1     Running             0          106m
nginx-7697996758-z47pt   1/1     Running             0          106m
nginx-6ff7c89c7c-zp5d9   1/1   Running   0     13s
nginx-7697996758-z47pt   1/1   Terminating   0     106m
nginx-6ff7c89c7c-w787k   0/1   Pending   0     0s
nginx-6ff7c89c7c-w787k   0/1   Pending   0     0s
nginx-6ff7c89c7c-w787k   0/1   ContainerCreating   0     0s
nginx-7697996758-z47pt   0/1   Terminating   0     106m
nginx-6ff7c89c7c-w787k   1/1   Running   0     11s
nginx-7697996758-2jwtg   1/1   Terminating   0     106m
nginx-6ff7c89c7c-7rd4p   0/1   Pending   0     0s
nginx-6ff7c89c7c-7rd4p   0/1   Pending   0     0s
nginx-6ff7c89c7c-7rd4p   0/1   ContainerCreating   0     0s
nginx-7697996758-2jwtg   0/1   Terminating   0     106m
nginx-7697996758-z47pt   0/1   Terminating   0     107m
nginx-7697996758-z47pt   0/1   Terminating   0     107m
nginx-7697996758-2jwtg   0/1   Terminating   0     107m
nginx-7697996758-2jwtg   0/1   Terminating   0     107m
nginx-6ff7c89c7c-7rd4p   1/1   Running   0     3s
nginx-7697996758-hf572   1/1   Terminating   0     107m
nginx-7697996758-hf572   0/1   Terminating   0     107m
nginx-7697996758-hf572   0/1   Terminating   0     107m
nginx-7697996758-hf572   0/1   Terminating   0     107m
//Ctrl+c中断监听
[root@master ~]#  kubectl get pods 
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6ff7c89c7c-7rd4p   1/1     Running   0          95s
nginx-6ff7c89c7c-w787k   1/1     Running   0          106s
nginx-6ff7c89c7c-zp5d9   1/1     Running   0          119s

滚从更新,副本数量不能低于 replicaset创建数量

4:回滚nginx

[root@master ~]# kubectl rollout --help
Manage the rollout of a resource.
  
Valid resource types include: 

  * deployments  
  * daemonsets  
  * statefulsets

Examples:
  # Rollback to the previous deployment
  kubectl rollout undo deployment/abc
  
  # Check the rollout status of a daemonset
  kubectl rollout status daemonset/foo

Available Commands:
  history     显示 rollout 历史
  pause       标记提供的 resource 为中止状态
  resume      继续一个停止的 resource
  status      显示 rollout 的状态
  undo        撤销上一次的 rollout

Usage:
  kubectl rollout SUBCOMMAND [options]

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

//查看历史版本

[root@master ~]# kubectl rollout history deployment/nginx
deployment.extensions/nginx 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>

//执行回滚

[root@master ~]# kubectl rollout undo deployment/nginx
deployment.extensions/nginx
[root@master ~]# kubectl get pods -w
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6ff7c89c7c-7rd4p   1/1     Running             0          15m
nginx-6ff7c89c7c-w787k   1/1     Running             0          15m
nginx-6ff7c89c7c-zp5d9   1/1     Running             0          15m
nginx-7697996758-rnrvx   0/1     ContainerCreating   0          1s
nginx-7697996758-rnrvx   1/1   Running   0     3s
nginx-6ff7c89c7c-7rd4p   1/1   Terminating   0     15m
nginx-7697996758-95hhq   0/1   Pending   0     0s
nginx-7697996758-95hhq   0/1   Pending   0     0s
nginx-7697996758-95hhq   0/1   ContainerCreating   0     0s
nginx-6ff7c89c7c-7rd4p   0/1   Terminating   0     15m
nginx-7697996758-95hhq   1/1   Running   0     4s
nginx-6ff7c89c7c-w787k   1/1   Terminating   0     15m
nginx-7697996758-pd7xz   0/1   Pending   0     0s
nginx-7697996758-pd7xz   0/1   Pending   0     0s
nginx-7697996758-pd7xz   0/1   ContainerCreating   0     0s
nginx-6ff7c89c7c-w787k   0/1   Terminating   0     15m
nginx-7697996758-pd7xz   1/1   Running   0     4s
nginx-6ff7c89c7c-zp5d9   1/1   Terminating   0     15m
nginx-6ff7c89c7c-w787k   0/1   Terminating   0     15m
nginx-6ff7c89c7c-w787k   0/1   Terminating   0     15m
nginx-6ff7c89c7c-7rd4p   0/1   Terminating   0     15m
nginx-6ff7c89c7c-7rd4p   0/1   Terminating   0     15m
nginx-6ff7c89c7c-zp5d9   0/1   Terminating   0     15m
nginx-6ff7c89c7c-zp5d9   0/1   Terminating   0     15m
nginx-6ff7c89c7c-zp5d9   0/1   Terminating   0     15m
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-7697996758-95hhq   1/1     Running   0          106s
nginx-7697996758-pd7xz   1/1     Running   0          102s
nginx-7697996758-rnrvx   1/1     Running   0          109s

//检查回滚状态

[root@master ~]# kubectl rollout status deployment/nginx
deployment "nginx" successfully rolled out

5:删除nginx

//查看deployment
[root@master ~]# kubectl get deploy
NAME    DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx   3         3         3            3           128m

[root@master ~]# kubectl delete deployment/nginx
deployment.extensions "nginx" deleted
[root@master ~]# kubectl get deploy
No resources found.
[root@master ~]# kubectl get pods
No resources found.

//删除服务SVC

[root@master ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        2d18h
nginx-service   NodePort    10.0.0.193   <none>        80:35505/TCP   129m
[root@master ~]# kubectl delete svc/nginx-service
service "nginx-service" deleted
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.0.0.1     <none>        443/TCP   2d18h

//查看具体资源的详细信息

[root@master ~]# kubectl run nginx --image=nginx:latest --port=80 --replicas=3
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx created
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-7697996758-7cqjr   1/1     Running   0          5s
nginx-7697996758-hfwdb   1/1     Running   0          5s
nginx-7697996758-xbn8w   1/1     Running   0          5s

[root@master ~]# kubectl describe pod nginx-7697996758-7cqjr
Name:               nginx-7697996758-7cqjr
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               192.168.20.20/192.168.20.20
Start Time:         Sun, 11 Oct 2020 15:32:51 +0800
Labels:             pod-template-hash=7697996758
                    run=nginx
Annotations:        <none>
Status:             Running
IP:                 172.17.42.2
Controlled By:      ReplicaSet/nginx-7697996758
Containers:
  nginx:
    Container ID:   docker://94fbfbf79227b2f9ffb25f08659764096bffcb8388afb17f2f02579fdbb7d153
    Image:          nginx:latest
    Image ID:       docker-pullable://nginx@sha256:fc66cdef5ca33809823182c9c5d72ea86fd2cef7713cf3363e1a0b12a5d77500
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Sun, 11 Oct 2020 15:32:54 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-kfkw4 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-kfkw4:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-kfkw4
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type    Reason     Age   From                    Message
  ----    ------     ----  ----                    -------
  Normal  Scheduled  61s   default-scheduler       Successfully assigned default/nginx-7697996758-7cqjr to 192.168.20.20
  Normal  Pulling    60s   kubelet, 192.168.20.20  pulling image "nginx:latest"
  Normal  Pulled     58s   kubelet, 192.168.20.20  Successfully pulled image "nginx:latest"
  Normal  Created    58s   kubelet, 192.168.20.20  Created container
  Normal  Started    58s   kubelet, 192.168.20.20  Started container

//查看deployment资源

[root@master ~]# kubectl describe deployment/nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Sun, 11 Oct 2020 15:32:51 +0800
Labels:                 run=nginx
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               run=nginx
Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  run=nginx
  Containers:
   nginx:
    Image:        nginx:latest
    Port:         80/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-7697996758 (3/3 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  2m23s  deployment-controller  Scaled up replica set nginx-7697996758 to 3

//进入pod

[root@master ~]# kubectl exec -it nginx-7697996758-7cqjr bash
root@nginx-7697996758-7cqjr:/# ls
bin   dev		   docker-entrypoint.sh  home  lib64  mnt  proc  run   srv  tmp  var
boot  docker-entrypoint.d  etc			 lib   media  opt  root  sbin  sys  usr

文件形式管理

文件形式管理 yaml json
Kubernetes支持YAML和JSON格式创建资源对象
JSON格式用于接口之间消息的传递 接口与之间消息的传递 开发
YAML格式用于配置和管理 配置和管理

YAML是一种简洁的非标记性语言
语法格式:
缩进标识层级关系
不支持制表符缩进,使用空格缩进
通常开头缩进两个空格
字符后缩进一个空格,如冒号,逗号,短横杠等
"—"标识YAML格式,一个文件的开始
"#"标识注释

文件解析

# yaml格式的pod定义文件完整内容:
apiVersion: v1       #必选,版本号,例如v1
kind: Pod       #必选,Pod
metadata:       #必选,元数据
  name: string       #必选,Pod名称
  namespace: string    #必选,Pod所属的命名空间
  labels:      #自定义标签
    - name: string     #自定义标签名字
  annotations:       #自定义注释列表
    - name: string
spec:         #必选,Pod中容器的详细定义
  containers:      #必选,Pod中容器列表
  - name: string     #必选,容器名称
    image: string    #必选,容器的镜像名称
    imagePullPolicy: [Always | Never | IfNotPresent] #获取镜像的策略 Alawys表示下载镜像 IfnotPresent表示优先使用本地镜像,否则下载镜像,Nerver表示仅使用本地镜像
    command: [string]    #容器的启动命令列表,如不指定,使用打包时使用的启动命令
    args: [string]     #容器的启动命令参数列表
    workingDir: string     #容器的工作目录
    volumeMounts:    #挂载到容器内部的存储卷配置
    - name: string     #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名
      mountPath: string    #存储卷在容器内mount的绝对路径,应少于512字符
      readOnly: boolean    #是否为只读模式
    ports:       #需要暴露的端口库号列表
    - name: string     #端口号名称
      containerPort: int   #容器需要监听的端口号
      hostPort: int    #容器所在主机需要监听的端口号,默认与Container相同
      protocol: string     #端口协议,支持TCP和UDP,默认TCP
    env:       #容器运行前需设置的环境变量列表
    - name: string     #环境变量名称
      value: string    #环境变量的值
    resources:       #资源限制和请求的设置
      limits:      #资源限制的设置
        cpu: string    #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数
        memory: string     #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数
      requests:      #资源请求的设置
        cpu: string    #Cpu请求,容器启动的初始可用数量
        memory: string     #内存清楚,容器启动的初始可用数量
    livenessProbe:     #对Pod内个容器健康检查的设置,当探测无响应几次后将自动重启该容器,检查方法有exec、httpGet和tcpSocket,对一个容器只需设置其中一种方法即可
      exec:      #对Pod容器内检查方式设置为exec方式
        command: [string]  #exec方式需要制定的命令或脚本
      httpGet:       #对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port
        path: string
        port: number
        host: string
        scheme: string
        HttpHeaders:
        - name: string
          value: string
      tcpSocket:     #对Pod内个容器健康检查方式设置为tcpSocket方式
         port: number
       initialDelaySeconds: 0  #容器启动完成后首次探测的时间,单位为秒
       timeoutSeconds: 0   #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒
       periodSeconds: 0    #对容器监控检查的定期探测时间设置,单位秒,默认10秒一次
       successThreshold: 0
       failureThreshold: 0
       securityContext:
         privileged:false
    restartPolicy: [Always | Never | OnFailure]#Pod的重启策略,Always表示一旦不管以何种方式终止运行,kubelet都将重启,OnFailure表示只有Pod以非0退出码退出才重启,Nerver表示不再重启该Pod
    nodeSelector: obeject  #设置NodeSelector表示将该Pod调度到包含这个label的node上,以key:value的格式指定
    imagePullSecrets:    #Pull镜像时使用的secret名称,以key:secretkey格式指定
    - name: string
    hostNetwork:false      #是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络
    volumes:       #在该pod上定义共享存储卷列表
    - name: string     #共享存储卷名称 (volumes类型有很多种)
      emptyDir: {}     #类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值
      hostPath: string     #类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录
        path: string     #Pod所在宿主机的目录,将被用于同期中mount的目录
      secret:      #类型为secret的存储卷,挂载集群与定义的secre对象到容器内部
        scretname: string  
        items:     
        - key: string
          path: string
      configMap:     #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部
        name: string
        items:
        - key: string
          path: string
[root@master ~]#  kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
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/v1beta1
coordination.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
networking.k8s.io/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
	//v1beta 表示测试版本
	//v1 表示正式版本
[root@master ~]# mkdir demo
[root@master ~]# cd demo/
[root@master demo]# vim nginx-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.15.4
        ports:
        - containerPort: 80

apiVersion:apps/v1 //版本号
kind:Deployment //资源的类型 无状态化的资源
metadata: //描述性信息 标签
name:nginx-deployment //资源的名称
labers: //标签
app: nginx //后面的要跟这个一致
spec: //资源的属性 标签
replicas: //副本集
selector: //选择器
mathLabels
app: nginx
template: //选择性的 模板
metadata:
labels:
app: nginx
spec: //容器的属性
containers: //容器
- name: //名称
image:nginx:1.15.4 //镜像
ports:
- containerPort: 80 //端口

[root@master demo]# kubectl create --help
Create a resource from a file or from stdin. 

JSON and YAML formats are accepted.

Examples:
  # Create a pod using the data in pod.json.
  kubectl create -f ./pod.json
  
  # Create a pod based on the JSON passed into stdin.
  cat pod.json | kubectl create -f -
  
  # Edit the data in docker-registry.yaml in JSON then create the resource using
the edited data.
  kubectl create -f docker-registry.yaml --edit -o json

Available Commands:
  clusterrole         Create a ClusterRole.
  clusterrolebinding  为一个指定的 ClusterRole 创建一个
ClusterRoleBinding
  configmap           从本地 file, directory 或者 literal value
创建一个 configmap
  deployment          创建一个指定名称的 deployment.
  job                 Create a job with the specified name.
  namespace           创建一个指定名称的 namespace
  poddisruptionbudget 创建一个指定名称的 pod disruption budget.
  priorityclass       Create a priorityclass with the specified name.
  quota               创建一个指定名称的 quota.
  role                Create a role with single rule.
  rolebinding         为一个指定的 Role 或者 ClusterRole创建一个
RoleBinding
  secret              使用指定的 subcommand 创建一个 secret
  service             使用指定的 subcommand 创建一个 service.
  serviceaccount      创建一个指定名称的 service account

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in
templates when a field or map key is missing in the template. Only applies to
golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent,
without sending it.
      --edit=false: Edit the API resource before creating
  -f, --filename=[]: Filename, directory, or URL to files to use to create the
resource
  -o, --output='': Output format. One of:
json|yaml|name|go-template-file|templatefile|template|go-template|jsonpath|jsonpath-file.
      --raw='': Raw URI to POST to the server.  Uses the transport specified by
the kubeconfig file.
      --record=false: Record current kubectl command in the resource annotation.
If set to false, do not record the command. If set to true, record the command.
If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename
recursively. Useful when you want to manage related manifests organized within
the same directory.
      --save-config=false: If true, the configuration of current object will be
saved in its annotation. Otherwise, the annotation will be unchanged. This flag
is useful when you want to perform kubectl apply on this object in the future.
  -l, --selector='': Selector (label query) to filter on, supports '=', '==',
and '!='.(e.g. -l key1=value1,key2=value2)
      --template='': Template string or path to template file to use when
-o=go-template, -o=go-template-file. The template format is golang templates
[http://golang.org/pkg/text/template/#pkg-overview].
      --validate=true: If true, use a schema to validate the input before
sending it
      --windows-line-endings=false: Only relevant if --edit=true. Defaults to
the line ending native to your platform.

Usage:
  kubectl create -f FILENAME [options]

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

[root@master demo]# kubectl create -f nginx-deployment.yaml 
deployment.apps/nginx-deployment created
[root@master demo]# kubectl get pods
NAME                              READY   STATUS    RESTARTS   AGE
nginx-deployment-d55b94fd-gzsvv   1/1     Running   0          27s
nginx-deployment-d55b94fd-rhp67   1/1     Running   0          27s
nginx-deployment-d55b94fd-tkdjs   1/1     Running   0          27s

[root@master demo]# vim nginx-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  labels:
    app: nginx
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
  selector:
    app: nginx

详解k8s中的port

port
port是k8s集群内部访问service的端口,即通过clusterIP: port可以访问到某个service
nodePort
nodePort是外部访问k8s集群中service的端口,通过nodeIP: nodePort可以从外部访问到某个service。
targetPort
targetPort是pod的端口,从port和nodePort来的流量经过kube-proxy流入到后端pod的targetPort上,最后进入容器。
containerPort
containerPort是pod内部容器的端口,targetPort映射到containerPort。
在这里插入图片描述

[root@master demo]# kubectl create -f nginx-service.yaml 
service/nginx-service created

[root@master demo]# kubectl get svc
NAME            TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.0.0.1     <none>        443/TCP        2d22h
nginx-service   NodePort    10.0.0.217   <none>        80:32302/TCP   53s

//自动测试命令的正确性,并不执行创建

[root@master demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx-deployment created (dry run)

//查看生成yaml格式

[root@master demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run -o yaml
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    run: nginx-deployment
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      run: nginx-deployment
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx-deployment
    spec:
      containers:
      - image: nginx
        name: nginx-deployment
        ports:
        - containerPort: 80
        resources: {}
status: {}

//查看生成json格式

[root@master demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run -o json
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
{
    "kind": "Deployment",
    "apiVersion": "apps/v1beta1",
    "metadata": {
        "name": "nginx-deployment",
        "creationTimestamp": null,
        "labels": {
            "run": "nginx-deployment"
        }
    },
    "spec": {
        "replicas": 3,
        "selector": {
            "matchLabels": {
                "run": "nginx-deployment"
            }
        },
        "template": {
            "metadata": {
                "creationTimestamp": null,
                "labels": {
                    "run": "nginx-deployment"
                }
            },
            "spec": {
                "containers": [
                    {
                        "name": "nginx-deployment",
                        "image": "nginx",
                        "ports": [
                            {
                                "containerPort": 80
                            }
                        ],
                        "resources": {}
                    }
                ]
            }
        },
        "strategy": {}
    },
    "status": {}
}
[root@master demo]# kubectl run nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run -o yaml > my-deployment.yaml
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
[root@master demo]# ls
my-deployment.yaml  nginx-deployment.yaml  nginx-service.yaml

//将现有的资源生成模板导出

[root@master demo]# kubectl run nginx --image=nginx:latest --port=80 --replicas=3
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
deployment.apps/nginx created
[root@master demo]# kubectl get deploy/nginx --export -o yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: null
  generation: 1
  labels:
    run: nginx
  name: nginx
  selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/nginx
spec:
  progressDeadlineSeconds: 600
  replicas: 3
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      run: nginx
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx
    spec:
      containers:
      - image: nginx:latest
        imagePullPolicy: Always
        name: nginx
        ports:
        - containerPort: 80
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status: {}

//保存到文件中

[root@master demo]# kubectl get deploy/nginx --export -o yaml > my-deploy.yaml
[root@master demo]# ls
my-deployment.yaml  my-deploy.yaml  nginx-deployment.yaml  nginx-service.yaml

//查看字段帮助信息

[root@master demo]# kubectl explain pods.spec.containers
KIND:     Pod
VERSION:  v1

RESOURCE: containers <[]Object>

DESCRIPTION:
     List of containers belonging to the pod. Containers cannot currently be
     added or removed. There must be at least one container in a Pod. Cannot be
     updated.

     A single application container that you want to run within a pod.

FIELDS:
   args	<[]string>
     Arguments to the entrypoint. The docker image's CMD is used if this is not
     provided. Variable references $(VAR_NAME) are expanded using the
     container's environment. If a variable cannot be resolved, the reference in
     the input string will be unchanged. The $(VAR_NAME) syntax can be escaped
     with a double $$, ie: $$(VAR_NAME). Escaped references will never be
     expanded, regardless of whether the variable exists or not. Cannot be
     updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

   command	<[]string>
     Entrypoint array. Not executed within a shell. The docker image's
     ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
     are expanded using the container's environment. If a variable cannot be
     resolved, the reference in the input string will be unchanged. The
     $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME).
     Escaped references will never be expanded, regardless of whether the
     variable exists or not. Cannot be updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

   env	<[]Object>
     List of environment variables to set in the container. Cannot be updated.

   envFrom	<[]Object>
     List of sources to populate environment variables in the container. The
     keys defined within a source must be a C_IDENTIFIER. All invalid keys will
     be reported as an event when the container is starting. When a key exists
     in multiple sources, the value associated with the last source will take
     precedence. Values defined by an Env with a duplicate key will take
     precedence. Cannot be updated.

   image	<string>
     Docker image name. More info:
     https://kubernetes.io/docs/concepts/containers/images This field is
     optional to allow higher level config management to default or override
     container images in workload controllers like Deployments and StatefulSets.

   imagePullPolicy	<string>
     Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always
     if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated.
     More info:
     https://kubernetes.io/docs/concepts/containers/images#updating-images

   lifecycle	<Object>
     Actions that the management system should take in response to container
     lifecycle events. Cannot be updated.

   livenessProbe	<Object>
     Periodic probe of container liveness. Container will be restarted if the
     probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   name	<string> -required-
     Name of the container specified as a DNS_LABEL. Each container in a pod
     must have a unique name (DNS_LABEL). Cannot be updated.

   ports	<[]Object>
     List of ports to expose from the container. Exposing a port here gives the
     system additional information about the network connections a container
     uses, but is primarily informational. Not specifying a port here DOES NOT
     prevent that port from being exposed. Any port which is listening on the
     default "0.0.0.0" address inside a container will be accessible from the
     network. Cannot be updated.

   readinessProbe	<Object>
     Periodic probe of container service readiness. Container will be removed
     from service endpoints if the probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   resources	<Object>
     Compute Resources required by this container. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

   securityContext	<Object>
     Security options the pod should run with. More info:
     https://kubernetes.io/docs/concepts/policy/security-context/ More info:
     https://kubernetes.io/docs/tasks/configure-pod-container/security-context/

   stdin	<boolean>
     Whether this container should allocate a buffer for stdin in the container
     runtime. If this is not set, reads from stdin in the container will always
     result in EOF. Default is false.

   stdinOnce	<boolean>
     Whether the container runtime should close the stdin channel after it has
     been opened by a single attach. When stdin is true the stdin stream will
     remain open across multiple attach sessions. If stdinOnce is set to true,
     stdin is opened on container start, is empty until the first client
     attaches to stdin, and then remains open and accepts data until the client
     disconnects, at which time stdin is closed and remains closed until the
     container is restarted. If this flag is false, a container processes that
     reads from stdin will never receive an EOF. Default is false

   terminationMessagePath	<string>
     Optional: Path at which the file to which the container's termination
     message will be written is mounted into the container's filesystem. Message
     written is intended to be brief final status, such as an assertion failure
     message. Will be truncated by the node if greater than 4096 bytes. The
     total message length across all containers will be limited to 12kb.
     Defaults to /dev/termination-log. Cannot be updated.

   terminationMessagePolicy	<string>
     Indicate how the termination message should be populated. File will use the
     contents of terminationMessagePath to populate the container status message
     on both success and failure. FallbackToLogsOnError will use the last chunk
     of container log output if the termination message file is empty and the
     container exited with an error. The log output is limited to 2048 bytes or
     80 lines, whichever is smaller. Defaults to File. Cannot be updated.

   tty	<boolean>
     Whether this container should allocate a TTY for itself, also requires
     'stdin' to be true. Default is false.

   volumeDevices	<[]Object>
     volumeDevices is the list of block devices to be used by the container.
     This is an alpha feature and may change in the future.

   volumeMounts	<[]Object>
     Pod volumes to mount into the container's filesystem. Cannot be updated.

   workingDir	<string>
     Container's working directory. If not specified, the container runtime's
     default will be used, which might be configured in the container image.
     Cannot be updated.
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值