一、kubectl的命令参数

1)kubectl 能使用的命令。即查看帮助

  1. [root@k8s6 ~]# kubectl
  2. kubectl controls the Kubernetes cluster manager.
  3.  
  4. Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/
  5.  
  6. Basic Commands (Beginner):
  7. create Create a resource from a file or from stdin.
  8. expose 使用 replication controller, service, deployment 或者 pod 并暴露它作为一个 新的
  9. Kubernetes Service
  10. run 在集群中运行一个指定的镜像
  11. set objects 设置一个指定的特征
  12.  
  13. Basic Commands (Intermediate):
  14. explain 查看资源的文档
  15. get 显示一个或更多 resources
  16. edit 在服务器上编辑一个资源
  17. delete Delete resources by filenames, stdin, resources and names, or by resources and label selector
  18.  
  19. Deploy Commands:
  20. rollout Manage the rollout of a resource
  21. scale Deployment, ReplicaSet, Replication Controller 或者 Job 设置一个新的副本数量
  22. autoscale 自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController 的副本数量
  23.  
  24. Cluster Management Commands:
  25. certificate 修改 certificate 资源.
  26. cluster-info 显示集群信息
  27. top Display Resource (CPU/Memory/Storage) usage.
  28. cordon 标记 node unschedulable
  29. uncordon 标记 node schedulable
  30. drain Drain node in preparation for maintenance
  31. taint 更新一个或者多个 node 上的 taints
  32.  
  33. Troubleshooting and Debugging Commands:
  34. describe 显示一个指定 resource 或者 group resources 详情
  35. logs 输出容器在 pod 中的日志
  36. attach Attach 到一个运行中的 container
  37. exec 在一个 container 中执行一个命令
  38. port-forward Forward one or more local ports to a pod
  39. proxy 运行一个 proxy Kubernetes API server
  40. cp 复制 files directories containers 和从容器中复制 files directories.
  41. auth Inspect authorization
  42.  
  43. Advanced Commands:
  44. diff Diff live version against would-be applied version
  45. apply 通过文件名或标准输入流(stdin)对资源进行配置
  46. patch 使用 strategic merge patch 更新一个资源的 field(s)
  47. replace 通过 filename 或者 stdin替换一个资源
  48. wait Experimental: Wait for a specific condition on one or many resources.
  49. convert 在不同的 API versions 转换配置文件
  50.  
  51. Settings Commands:
  52. label 更新在这个资源上的 labels
  53. annotate 更新一个资源的注解
  54. completion Output shell completion code for the specified shell (bash or zsh)
  55.  
  56. Other Commands:
  57. api-resources Print the supported API resources on the server
  58. api-versions Print the supported API versions on the server, in the form of "group/version"
  59. config 修改 kubeconfig 文件
  60. plugin Provides utilities for interacting with plugins.
  61. version 输出 client server 的版本信息
  62.  
  63. Usage:
  64. kubectl [flags] [options]
  65.  
  66. Use "kubectl <command> --help" for more information about a given command.
  67. Use "kubectl options" for a list of global command-line options (applies to all commands).

kubectl

2.1)跑服务命令。kubectl run --help 查看帮助

  1. [root@k8s6 ~]# kubectl run --help
  2. Create and run a particular image, possibly replicated.
  3.  
  4. Creates a deployment or job to manage the created container(s).
  5.  
  6. Examples:
  7. # Start a single instance of nginx.
  8. kubectl run nginx --image=nginx
  9.  
  10. # Start a single instance of hazelcast and let the container expose port .
  11. kubectl run hazelcast --image=hazelcast --port=
  12.  
  13. # Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default"
  14. in the container.
  15. kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
  16.  
  17. # Start a single instance of hazelcast and set labels "app=hazelcast" and "env=prod" in the container.
  18. kubectl run hazelcast --image=hazelcast --labels="app=hazelcast,env=prod"
  19.  
  20. # Start a replicated instance of nginx.
  21. kubectl run nginx --image=nginx --replicas=
  22.  
  23. # Dry run. Print the corresponding API objects without creating them.
  24. kubectl run nginx --image=nginx --dry-run
  25.  
  26. # Start a single instance of nginx, but overload the spec of the deployment with a partial set of values parsed from
  27. JSON.
  28. kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'
  29.  
  30. # Start a pod of busybox and keep it in the foreground, don't restart it if it exits.
  31. kubectl run -i -t busybox --image=busybox --restart=Never
  32.  
  33. # Start the nginx container using the default command, but use custom arguments (arg1 .. argN) for that command.
  34. kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>
  35.  
  36. # Start the nginx container using a different command and custom arguments.
  37. kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
  38.  
  39. # Start the perl container to compute π to places and print it out.
  40. kubectl run pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'
  41.  
  42. # Start the cron job to compute π to places and print it out every minutes.
  43. kubectl run pi --schedule="0/5 * * * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'
  44.  
  45. Options:
  46. --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
  47. the template. Only applies to golang and jsonpath output formats.
  48. --attach=false: If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...'
  49. were called. Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the
  50. exit code of the container process is returned.
  51. --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
  52. ReplicationController). Default true.
  53. --command=false: If true and extra arguments are present, use them as the 'command' field in the container, rather
  54. than the 'args' field which is the default.
  55. --dry-run=false: If true, only print the object that would be sent, without sending it.
  56. --env=[]: Environment variables to set in the container
  57. --expose=false: If true, a public, external service is created for the container(s) which are run
  58. -f, --filename=[]: to use to replace the resource.
  59. --force=false: Only used when grace-period=. If true, immediately remove resources from API and bypass graceful
  60. deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires
  61. confirmation.
  62. --generator='': 使用 API generator 的名字,
  63. http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators 查看列表.
  64. --grace-period=-: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.
  65. Set to for immediate shutdown. Can only be set to when --force is true (force deletion).
  66. --hostport=-: The host port mapping for the container port. To demonstrate a single-machine container.
  67. --image='': 指定容器要运行的镜像.
  68. --image-pull-policy='': 容器的镜像拉取策略. 如果为空, 这个值将不会 client 指定且使用
  69. server 端的默认值
  70. -l, --labels='': Comma separated labels to apply to the pod(s). Will override previous values.
  71. --leave-stdin-open=false: If the pod is started in interactive mode or with stdin, leave stdin open after the
  72. first attach completes. By default, stdin will be closed after the first attach completes.
  73. --limits='': The resource requirement limits for this container. For example, 'cpu=200m,memory=512Mi'. Note that
  74. server side components may assign limits depending on the server configuration, such as limit ranges.
  75. -o, --output='': Output format. One of:
  76. json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
  77. --overrides='': An inline JSON override for the generated object. If this is non-empty, it is used to override the
  78. generated object. Requires that the object supply a valid apiVersion field.
  79. --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
  80. pod is running
  81. --port='': The port that this container exposes. If --expose is true, this is also the port used by the service
  82. that is created.
  83. --quiet=false: If true, suppress prompt messages.
  84. --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
  85. command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
  86. already exists.
  87. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
  88. related manifests organized within the same directory.
  89. -r, --replicas=: Number of replicas to create for this container. Default is .
  90. --requests='': 资源为 container 请求 requests . 例如, 'cpu=100m,memory=256Mi'.
  91. 注意服务端组件也许会赋予 requests, 这决定于服务器端配置, 比如 limit ranges.
  92. --restart='Always': 这个 Pod restart policy. Legal values [Always, OnFailure, Never]. 如果设置为
  93. 'Always' 一个 deployment 被创建, 如果设置为 OnFailure' 一个 job 被创建, 如果设置为 'Never',
  94. 一个普通的 pod 被创建. 对于后面两个 --replicas 必须为 . 默认 'Always', 为 CronJobs 设置为
  95. `Never`.
  96. --rm=false: If true, delete resources created in this command for attached containers.
  97. --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
  98. annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
  99. --schedule='': A schedule in the Cron format the job should be run with.
  100. --service-generator='service/v2': 使用 gnerator 的名称创建一个 service. 只有在 --expose 为 true
  101. 的时候使用
  102. --service-overrides='': An inline JSON override for the generated service object. If this is non-empty, it is used
  103. to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose is
  104. true.
  105. --serviceaccount='': Service account to set in the pod spec
  106. -i, --stdin=false: Keep stdin open on the container(s) in the pod, even if nothing is attached.
  107. --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
  108. template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
  109. --timeout=0s: The length of time to wait before giving up on a delete, zero means determine a timeout from the
  110. size of the object
  111. -t, --tty=false: Allocated a TTY for each container in the pod.
  112. --wait=false: If true, wait for resources to be gone before returning. This waits for finalizers.
  113.  
  114. Usage:
  115. kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool]
  116. [--overrides=inline-json] [--command] -- [COMMAND] [args...] [options]
  117.  
  118. Use "kubectl options" for a list of global command-line options (applies to all commands).

kubectl run --help

2.2)进入交互式的容器服务

  1. [root@k8s6 ~]# kubectl run clinet --image=busybox --replicas= -it --restart=Never
  2. If you don't see a command prompt, try pressing enter.
  3. / #
  4. / #
  5. / #

kubectl run clinet --image=busybox --replicas=1 -it --restart=Never

2.3)跑服务,但仅在容器内所在宿主机内可以被访问

  1. 运行容器服务
  2. [root@k8s6 ~]# kubectl run nginx-test --image=nginx:1.14-alpine --port= --replicas=
  3. kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
  4. deployment.apps/nginx-test created
  5.  
  6. 查看节点状态
  7. [root@k8s6 ~]# kubectl get pods
  8. NAME READY STATUS RESTARTS AGE
  9. nginx-test-5bbfddf46b-g6sh5 / ContainerCreating 4s
  10.  
  11. 节点状态Running 起来了,则正常
  12. [root@k8s6 ~]# kubectl get pods
  13. NAME READY STATUS RESTARTS AGE
  14. nginx-test-5bbfddf46b-g6sh5 / Running 24s
  15.  
  16. 查看节点在那台机器上面
  17. [root@k8s6 ~]# kubectl get pods -o wide
  18. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  19. nginx-test-5bbfddf46b-g6sh5 / Running 53s 10.200.2.3 node01 <none> <none>
  20.  
  21. 此时只能在node01上的机器进行访问
  22. curl 10.200.2.3
  23.  
  24. 删除该服务节点,又重新被创建出来
  25. [root@k8s6 ~]# kubectl delete pods nginx-test-5bbfddf46b-g6sh5
  26. pod "nginx-test-5bbfddf46b-g6sh5" deleted
  27. [root@k8s6 ~]#
  28. [root@k8s6 ~]# kubectl get pods
  29. NAME READY STATUS RESTARTS AGE
  30. nginx-test-5bbfddf46b-6djc4 / ContainerCreating 6s
  31. [root@k8s6 ~]# kubectl get pods -o wide
  32. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  33. nginx-test-5bbfddf46b-6djc4 / Running 18s 10.200.1.2 node02 <none> <none>

kubectl run nginx-test --image=nginx:1.14-alpine --port=80 --replicas=1

创建nginx-test 服务,只的镜像名为nginx:1.14-alpine,默认从docker官网下载,容器规模为1

3)暴露端口,查看帮助

  1. [root@k8s6 ~]# kubectl expose --help
  2. Expose a resource as a new Kubernetes service.
  3.  
  4. Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector for that
  5. resource as the selector for a new service on the specified port. A deployment or replica set will be exposed as a
  6. service only if its selector is convertible to a selector that service supports, i.e. when the selector contains only
  7. the matchLabels component. Note that if no port is specified via --port and the exposed resource has multiple ports, all
  8. will be re-used by the new service. Also if no labels are specified, the new service will re-use the labels from the
  9. resource it exposes.
  10.  
  11. Possible resources include (case insensitive):
  12.  
  13. pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)
  14.  
  15. Examples:
  16. # Create a service for a replicated nginx, which serves on port and connects to the containers on port .
  17. kubectl expose rc nginx --port= --target-port=
  18.  
  19. # Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml",
  20. which serves on port and connects to the containers on port .
  21. kubectl expose -f nginx-controller.yaml --port= --target-port=
  22.  
  23. # Create a service for a pod valid-pod, which serves on port with the name "frontend"
  24. kubectl expose pod valid-pod --port= --name=frontend
  25.  
  26. # Create a second service based on the above service, exposing the container port as port with the name
  27. "nginx-https"
  28. kubectl expose service nginx --port= --target-port= --name=nginx-https
  29.  
  30. # Create a service for a replicated streaming application on port balancing UDP traffic and named 'video-stream'.
  31. kubectl expose rc streamer --port= --protocol=udp --name=video-stream
  32.  
  33. # Create a service for a replicated nginx using replica set, which serves on port and connects to the containers on
  34. port .
  35. kubectl expose rs nginx --port= --target-port=
  36.  
  37. # Create a service for an nginx deployment, which serves on port and connects to the containers on port .
  38. kubectl expose deployment nginx --port= --target-port=
  39.  
  40. Options:
  41. --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
  42. the template. Only applies to golang and jsonpath output formats.
  43. --cluster-ip='': ClusterIP to be assigned to the service. Leave empty to auto-allocate, or set to 'None' to create
  44. a headless service.
  45. --dry-run=false: If true, only print the object that would be sent, without sending it.
  46. --external-ip='': Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP
  47. is routed to a node, the service can be accessed by this IP in addition to its generated service IP.
  48. -f, --filename=[]: Filename, directory, or URL to files identifying the resource to expose a service
  49. --generator='service/v2': 使用 generator 的名称. 这里有 generators: 'service/v1' 'service/v2'.
  50. 为一个不同地方是服务端口在 v1 的情况下叫 'default', 如果在 v2 中没有指定名称.
  51. 默认的名称是 'service/v2'.
  52. -l, --labels='': Labels to apply to the service created by this call.
  53. --load-balancer-ip='': IP to assign to the LoadBalancer. If empty, an ephemeral IP will be created and used
  54. (cloud-provider specific).
  55. --name='': 名称为最新创建的对象.
  56. -o, --output='': Output format. One of:
  57. json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
  58. --overrides='': An inline JSON override for the generated object. If this is non-empty, it is used to override the
  59. generated object. Requires that the object supply a valid apiVersion field.
  60. --port='': 服务的端口应该被指定. 如果没有指定, 从被创建的资源中复制
  61. --protocol='': 创建 service 的时候伴随着一个网络协议被创建. 默认是 'TCP'.
  62. --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
  63. command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
  64. already exists.
  65. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
  66. related manifests organized within the same directory.
  67. --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
  68. annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
  69. --selector='': A label selector to use for this service. Only equality-based selector requirements are supported.
  70. If empty (the default) infer the selector from the replication controller or replica set.)
  71. --session-affinity='': If non-empty, set the session affinity for the service to this; legal values: 'None',
  72. 'ClientIP'
  73. --target-port='': Name or number for the port on the container that the service should direct traffic to.
  74. Optional.
  75. --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
  76. template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
  77. --type='': Type for this service: ClusterIP, NodePort, LoadBalancer, or ExternalName. Default is 'ClusterIP'.
  78.  
  79. Usage:
  80. kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP|SCTP] [--target-port=number-or-name]
  81. [--name=name] [--external-ip=external-ip-of-service] [--type=type] [options]
  82.  
  83. Use "kubectl options" for a list of global command-line options (applies to all commands).

kubectl expose --help

3.1)端口暴露给了无法访问的ip

  1. [root@k8s6 ~]# kubectl get deployment
  2. NAME READY UP-TO-DATE AVAILABLE AGE
  3. nginx-deploy / 30m
  4. nginx-test / 17m
  5. [root@k8s6 ~]# kubectl expose deployment nginx-test --name=nginx --port= --target-port= --protocol=TCP 暴露80端口
  6. service/nginx exposed
  7. [root@k8s6 ~]# kubectl get svc
  8. NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
  9. kubernetes NodePort 10.96.0.1 <none> :/TCP 38h
  10. nginx ClusterIP 10.107.169.145 <none> /TCP 20s
  11. [root@k8s6 ~]# kubectl get svc -n kube-system # 查看dns
  12. NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
  13. kube-dns ClusterIP 10.96.0.10 <none> /UDP,/TCP 38h
  14. [root@k8s6 ~]# kubectl get pods -o wide
  15. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  16. nginx-deploy-79b598b88-2q6vr / ImagePullBackOff 34m 10.200.2.2 node01 <none> <none>
  17. nginx-test-5bbfddf46b-6djc4 / Running 14m 10.200.1.2 node02 <none> <none>
  18. [root@k8s6 ~]# kubectl describe svc nginx 查看暴露出来的ip
  19. Name: nginx
  20. Namespace: default
  21. Labels: run=nginx-test
  22. Annotations: <none>
  23. Selector: run=nginx-test
  24. Type: ClusterIP
  25. IP: 10.107.169.145
  26. Port: <unset> /TCP
  27. TargetPort: /TCP
  28. Endpoints: 10.200.1.2:
  29. Session Affinity: None
  30. Events: <none>

kubectl expose deployment nginx-test --name=nginx --port=80 --target-port=80 --protocol=TCP

4)查看服务的详细信息

  1. [root@k8s6 ~]# kubectl describe deployment nginx-test
  2. Name: nginx-test
  3. Namespace: default
  4. CreationTimestamp: Wed, Feb :: +
  5. Labels: run=nginx-test
  6. Annotations: deployment.kubernetes.io/revision:
  7. Selector: run=nginx-test
  8. Replicas: desired | updated | total | available | unavailable
  9. StrategyType: RollingUpdate
  10. MinReadySeconds:
  11. RollingUpdateStrategy: % max unavailable, % max surge
  12. Pod Template:
  13. Labels: run=nginx-test
  14. Containers:
  15. nginx-test:
  16. Image: nginx:1.14-alpine
  17. Port: /TCP
  18. Host Port: /TCP
  19. Environment: <none>
  20. Mounts: <none>
  21. Volumes: <none>
  22. Conditions:
  23. Type Status Reason
  24. ---- ------ ------
  25. Progressing True NewReplicaSetAvailable
  26. Available True MinimumReplicasAvailable
  27. OldReplicaSets: <none>
  28. NewReplicaSet: nginx-test-5bbfddf46b (/ replicas created)
  29. Events:
  30. Type Reason Age From Message
  31. ---- ------ ---- ---- -------
  32. Normal ScalingReplicaSet 34m deployment-controller Scaled up replica set nginx-test-5bbfddf46b to

kubectl describe deployment nginx-test

5)更改服务的规模

  1. kubectl run nginx-test --image=nginx:1.14-alpine --port= --replicas= # 创建3个规模的服务
  2. kubectl scale --replicas= deployment nginx-test # 修改规模大小
  3. [root@k8s6 ~]# kubectl get pods
  4. NAME READY STATUS RESTARTS AGE
  5. clinet / Running 12m
  6. nginx-deploy-79b598b88-2q6vr / ImagePullBackOff 54m
  7. nginx-test-5bbfddf46b-6djc4 / Running 35m
  8. nginx-test-5bbfddf46b-cwwfm / Running 64s
  9. nginx-test-5bbfddf46b-pcdf2 / Running 64s
  10. nginx-test-5bbfddf46b-rpb8r / Running 64s
  11. nginx-test-5bbfddf46b-tttrz / Running 64s
  12. [root@k8s6 ~]# kubectl get pods -o wide
  13. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  14. clinet / Running 12m 10.200.1.3 node02 <none> <none>
  15. nginx-test-5bbfddf46b-6djc4 / Running 35m 10.200.1.2 node02 <none> <none>
  16. nginx-test-5bbfddf46b-cwwfm / Running 80s 10.200.1.4 node02 <none> <none>
  17. nginx-test-5bbfddf46b-pcdf2 / Running 80s 10.200.2.6 node01 <none> <none>
  18. nginx-test-5bbfddf46b-rpb8r / Running 80s 10.200.2.5 node01 <none> <none>
  19. nginx-test-5bbfddf46b-tttrz / Running 80s 10.200.2.4 node01 <none> <none>

--replicas=5

6)更换镜像操作

kubectl set image --help  查看帮助

目标: nginx:1.14-alpine   更换为 nginx:1.15-alpine

6.1)更换前查看使用的镜像

  1. [root@k8s6 ~]# kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. clinet / Running 25m
  4. nginx-deploy-79b598b88-2q6vr / ImagePullBackOff 68m
  5. nginx-test-5bbfddf46b-7cpcq / Running 47s
  6. nginx-test-5bbfddf46b-mbfpq / Running 47s
  7. nginx-test-5bbfddf46b-q28zw / Running 46s
  8. nginx-test-5bbfddf46b-qb66g / Running 46s
  9. nginx-test-5bbfddf46b-xfr8w / Running 47s
  10. [root@k8s6 ~]# kubectl describe pods nginx-test-5bbfddf46b-7cpcq 查看该镜像的详细信息

kubectl describe pods nginx-test-5bbf***

6.2)更换镜像版本操作

kubectl set image deployment nginx-test nginx-test=nginx:1.15-alpine

  1. [root@k8s6 ~]# kubectl set image deployment nginx-test nginx-test=nginx:1.15-alpine
  2. deployment.extensions/nginx-test image updated
  3. [root@k8s6 ~]# kubectl get pods
  4. NAME READY STATUS RESTARTS AGE
  5. clinet / Running 28m
  6. nginx-deploy-79b598b88-2q6vr / ImagePullBackOff 71m
  7. nginx-test-67d85d447c-2phzb / Running 24s
  8. nginx-test-67d85d447c-g7cr2 / Running 24s
  9. nginx-test-67d85d447c-j552t / Running 23s
  10. nginx-test-67d85d447c-v7thb / Running 23s
  11. nginx-test-67d85d447c-xx99k / Running 24s
  12. [root@k8s6 ~]# kubectl describe pods nginx-test-67d85d447c-2phzb
  13. Name: nginx-test-67d85d447c-2phzb
  14. Namespace: default
  15. Priority:
  16. PriorityClassName: <none>
  17. Node: node01/192.168.10.23
  18. Start Time: Wed, Feb :: +
  19. Labels: pod-template-hash=67d85d447c
  20. run=nginx-test
  21. Annotations: <none>
  22. Status: Running
  23. IP: 10.200.2.12
  24. Controlled By: ReplicaSet/nginx-test-67d85d447c
  25. Containers:
  26. nginx-test:
  27. Container ID: docker://2e083a772f30777aa86ed8302efed0bb7e2e084cc400886894094ec2c1b3c3ec
  28. Image: nginx:1.15-alpine
  29. Image ID: docker-pullable://nginx@sha256:e0292d158b6b353fde34909243a4886977cb9d1abb8a8a5fef9e0ff7138dd3e2
  30. Port: /TCP
  31. Host Port: /TCP
  32. State: Running
  33. Started: Wed, Feb :: +
  34. Ready: True
  35. Restart Count:
  36. Environment: <none>
  37. Mounts:
  38. /var/run/secrets/kubernetes.io/serviceaccount from default-token-r48df (ro)
  39. Conditions:
  40. Type Status
  41. Initialized True
  42. Ready True
  43. ContainersReady True
  44. PodScheduled True
  45. Volumes:
  46. default-token-r48df:
  47. Type: Secret (a volume populated by a Secret)
  48. SecretName: default-token-r48df
  49. Optional: false
  50. QoS Class: BestEffort
  51. Node-Selectors: <none>
  52. Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
  53. node.kubernetes.io/unreachable:NoExecute for 300s
  54. Events:
  55. Type Reason Age From Message
  56. ---- ------ ---- ---- -------
  57. Normal Scheduled 42s default-scheduler Successfully assigned default/nginx-test-67d85d447c-2phzb to node01
  58. Normal Pulled 41s kubelet, node01 Container image "nginx:1.15-alpine" already present on machine
  59. Normal Created 41s kubelet, node01 Created container
  60. Normal Started 41s kubelet, node01 Started container

6.3)回滚镜像

查看回滚帮助

  1. [root@k8s6 ~]# kubectl rollout --help
  2. Manage the rollout of a resource.
  3.  
  4. Valid resource types include:
  5.  
  6. * deployments
  7. * daemonsets
  8. * statefulsets
  9.  
  10. Examples:
  11. # Rollback to the previous deployment
  12. kubectl rollout undo deployment/abc
  13.  
  14. # Check the rollout status of a daemonset
  15. kubectl rollout status daemonset/foo
  16.  
  17. Available Commands:
  18. history 显示 rollout 历史
  19. pause 标记提供的 resource 为中止状态
  20. resume 继续一个停止的 resource
  21. status 显示 rollout 的状态
  22. undo 撤销上一次的 rollout
  23.  
  24. Usage:
  25. kubectl rollout SUBCOMMAND [options]
  26.  
  27. Use "kubectl <command> --help" for more information about a given command.
  28. Use "kubectl options" for a list of global command-line options (applies to all commands).

kubectl rollout --help

kubectl rollout undo deployment nginx-test   默认回滚到上一个版本

7 ) 编辑服务的 type: ClusterIP  ==》type: NodePort

  1. [root@k8s6 ~]# kubectl get svc
  2. NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
  3. kubernetes NodePort 10.96.0.1 <none> :/TCP 38h
  4. nginx ClusterIP 10.107.169.145 <none> /TCP 20s
  5.  
  6. [root@k8s6 ~]# kubectl edit svc nginx
  7. type: ClusterIP ==》type: NodePort
  8.  
  9. [root@k8s6 ~]# kubectl get svc
  10. NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
  11. kubernetes NodePort 10.96.0.1 <none> :/TCP 39h
  12. nginx NodePort 10.107.169.145 <none> :/TCP 51m

7.1)此时可通过网页进行访问

  1. http://192.168.10.23:31986/
  2. http://192.168.10.24:31986/

二、以资源的方式创建资源

1)查看命令行直接创建的资源所描述的yaml文件,资源清单

  1. [root@k8s6 ~]# kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. clinet / Running 26h
  4. nginx-test-67d85d447c-2phzb / Running 25h
  5. nginx-test-67d85d447c-g7cr2 / Running 25h
  6. nginx-test-67d85d447c-j552t / Running 25h
  7. nginx-test-67d85d447c-v7thb / Running 25h
  8. nginx-test-67d85d447c-xx99k / Running 25h
  9. [root@k8s6 ~]# kubectl get pod nginx-test-67d85d447c-2phzb -o yaml

kubectl get pod **** -o yaml

2)查看自定义的资源清单需要填写的字段

  1. [root@k8s6 ~]# kubectl explain pods
  2. KIND: Pod
  3. VERSION: v1
  4.  
  5. DESCRIPTION:
  6. Pod is a collection of containers that can run on a host. This resource is
  7. created by clients and scheduled onto hosts.
  8.  
  9. FIELDS:
  10. apiVersion <string>
  11. APIVersion defines the versioned schema of this representation of an
  12. object. Servers should convert recognized schemas to the latest internal
  13. value, and may reject unrecognized values. More info:
  14. https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
  15.  
  16. kind <string>
  17. Kind is a string value representing the REST resource this object
  18. represents. Servers may infer this from the endpoint the client submits
  19. requests to. Cannot be updated. In CamelCase. More info:
  20. https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
  21.  
  22. metadata <Object>
  23. Standard object's metadata. More info:
  24. https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
  25.  
  26. spec <Object>
  27. Specification of the desired behavior of the pod. More info:
  28. https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
  29.  
  30. status <Object>
  31. Most recently observed status of the pod. This data may not be up to date.
  32. Populated by the system. Read-only. More info:
  33. https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status

kubectl explain pods

3)定义 yaml 资源清单启动容器

  1. [root@k8s6 ~]# mkdird -p manifests
  2. [root@k8s6 ~]# cd manifests/
  3. [root@k8s6 manifests]# vim pod-demo.yaml
  4. [root@k8s6 manifests]# cat pod-demo.yaml
  5. apiVersion: v1
  6. kind: Pod
  7. metadata:
  8. name: pod-demo
  9. namespace: default
  10. labels:
  11. app: myapp
  12. tier: frontend
  13. spec:
  14. containers:
  15. - name: myapp
  16. image: nginx:1.14-alpine
  17. - name: busybox
  18. image: busybox:latest
  19. command:
  20. - "/bin/sh"
  21. - "-c"
  22. - "echo $(data) >> /usr/share/nginx/html/index.html;sleep 5"

cat pod-demo.yaml

该清单中使用了2个容器,并且使用了命令操作。该命令使用错误,多容器操作需要恭喜存储卷

4)根据清单启动服务

  1. [root@k8s6 manifests]# kubectl create -f pod-demo.yaml
  2. pod/pod-demo created
  3. [root@k8s6 manifests]# kubectl get pods -w
  4. NAME READY STATUS RESTARTS AGE
  5. clinet / Running 28h
  6. nginx-test-67d85d447c-2phzb / Running 27h
  7. nginx-test-67d85d447c-g7cr2 / Running 27h
  8. nginx-test-67d85d447c-j552t / Running 27h
  9. nginx-test-67d85d447c-v7thb / Running 27h
  10. nginx-test-67d85d447c-xx99k / Running 27h
  11. pod-demo / CrashLoopBackOff 100s

kubectl create -f pod-demo.yaml

可以看到该服务只启动了好了一个容器

4.1)对启动的容器进行排查。查看日志

  1. [root@k8s6 manifests]# kubectl logs pod-demo myapp
  2. [root@k8s6 manifests]# kubectl logs pod-demo busybox
  3. /bin/sh: data: not found
  4. /bin/sh: can't create /usr/share/nginx/html/index.html: nonexistent directory

kubectl logs pod-demo busybox

5)删除该服务

  1. [root@k8s6 manifests]# kubectl delete pods pod-demo
  2. pod "pod-demo" deleted

6)修改资源清单,为简单的sleep,再创建,可以看到容器正常跑起来了

  1. [root@k8s6 manifests]# cat pod-demo.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: pod-demo
  6. namespace: default
  7. labels:
  8. app: myapp
  9. tier: frontend
  10. spec:
  11. containers:
  12. - name: myapp
  13. image: nginx:1.14-alpine
  14. - name: busybox
  15. image: busybox:latest
  16. command:
  17. - "/bin/sh"
  18. - "-c"
  19. - "sleep 3600"
  20. kubectl create -f pod-demo.yaml
  21. [root@k8s6 manifests]# kubectl get pods
  22. NAME READY STATUS RESTARTS AGE
  23. clinet / Running 28h
  24. nginx-test-67d85d447c-2phzb / Running 27h
  25. nginx-test-67d85d447c-g7cr2 / Running 27h
  26. nginx-test-67d85d447c-j552t / Running 27h
  27. nginx-test-67d85d447c-v7thb / Running 27h
  28. nginx-test-67d85d447c-xx99k / Running 27h
  29. pod-demo / Running 83s

三、资源清单详细说明

1)镜像的获取的途径

  1. 资源配置清单:
  2. 自主式POd资源
  3.  
  4. 资源的清单格式
  5. 一级字段:apiVersion(group/version),kind,metadata(name,namespace,labels,annotations, ...),spec,status(只读)
  6.  
  7. Pod资源
  8. spec.containers <[]object
  9.  
  10. - name <string>
  11. image <string>
  12. imagePullPolicy <string>
  13. Always,Never,IfNotPresent
  14. 备注:Always镜像总是从官网下载
  15. Never 只从本地获取
  16. IfNotPresent 本地从本地拿,没有就去官网
  17. 如果使用,镜像用latest版本,默认从官网获取

示例

  1. [root@k8s6 manifests]# cat pod-demo.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: pod-demo
  6. namespace: default
  7. labels:
  8. app: myapp
  9. tier: frontend
  10. spec:
  11. containers:
  12. - name: myapp
  13. image: nginx:1.14-alpine
  14. - name: busybox
  15. image: busybox:latest
  16. imagePullPolicy: IfNotPresent
  17. command:
  18. - "/bin/sh"
  19. - "-c"
  20. - "sleep 3600"

2)暴露端口

  1. [root@k8s6 manifests]# cat pod-demo.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: pod-demo
  6. namespace: default
  7. labels:
  8. app: myapp
  9. tier: frontend
  10. spec:
  11. containers:
  12. - name: myapp
  13. image: nginx:1.14-alpine
  14. ports:
  15. - name: http
  16. containerPort:
  17. - name: https
  18. containerPort:
  19. - name: busybox
  20. image: busybox:latest
  21. imagePullPolicy: IfNotPresent
  22. command:
  23. - "/bin/sh"
  24. - "-c"
  25. - "sleep 3600"

containerPort: 80

四、修改镜像中的默认标签。根据标签查看镜像

  1. 修改镜像中的默认应用:
  2. command,args
  3. https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/
  4. 标签:
  5. key=value
  6. key :字母、数字
  7. value: 可以为空,只能字母或数字开头及结尾,中间可使用

1)默认显示的查看的显示方式

  1. [root@k8s6 ~]# kubectl get pods --show-labels
  2. NAME READY STATUS RESTARTS AGE LABELS
  3. nginx-deploy-79b598b88-pt9xq / ImagePullBackOff 2d3h pod-template-hash=79b598b88,run=ngi
  4. nginx-test-67d85d447c-brwb2 / Running 2d3h pod-template-hash=67d85d447c,run=ng
  5. nginx-test-67d85d447c-l7xvs / Running 2d3h pod-template-hash=67d85d447c,run=ng
  6. nginx-test-67d85d447c-qmrrw / Running 2d3h pod-template-hash=67d85d447c,run=ng
  7. nginx-test-67d85d447c-rsmdt / Running 2d3h pod-template-hash=67d85d447c,run=ng
  8. nginx-test-67d85d447c-twk77 / Running 2d3h pod-template-hash=67d85d447c,releas
  9. pod-demo / Running 47h app=myapp,tier=frontend
  10. [root@k8s6 ~]# kubectl get pods -L app
  11. NAME READY STATUS RESTARTS AGE APP
  12. nginx-deploy-79b598b88-pt9xq / ImagePullBackOff 2d3h
  13. nginx-test-67d85d447c-brwb2 / Running 2d3h
  14. nginx-test-67d85d447c-l7xvs / Running 2d3h
  15. nginx-test-67d85d447c-qmrrw / Running 2d3h
  16. nginx-test-67d85d447c-rsmdt / Running 2d3h
  17. nginx-test-67d85d447c-twk77 / Running 2d3h
  18. pod-demo / Running 47h myapp
  19. [root@k8s6 ~]# kubectl get pods -l app
  20. NAME READY STATUS RESTARTS AGE
  21. pod-demo / Running 47h
  22. [root@k8s6 ~]# kubectl get pods -l app --show-labels
  23. NAME READY STATUS RESTARTS AGE LABELS
  24. pod-demo / Running 47h app=myapp,tier=frontend

kubectl label --help   为资源打标签,查看帮助信息

2)给服务打标记

  1. [root@k8s6 ~]# kubectl get pods -l app --show-labels
  2. NAME READY STATUS RESTARTS AGE LABELS
  3. pod-demo / Running 47h app=myapp,tier=frontend
  4. [root@k8s6 ~]# kubectl label pods pod-demo release=stable --overwrite
  5. pod/pod-demo labeled
  6. [root@k8s6 ~]# kubectl get pods -l app --show-labels
  7. NAME READY STATUS RESTARTS AGE LABELS
  8. pod-demo / Running 47h app=myapp,release=stable,tier=frontend

kubectl label pods pod-demo release=stable --overwrite

3)一般标签选择器的使用

  1. 等值关系:=,==,!=
  2. 集合关系:
  3. KEY in (VALUE1,VALUE2,....)
  4. KEY notin (VALUE1,VALUE2,....)
  5. KEY
  6. !KEY

3.1)基本查询

  1. [root@k8s6 ~]# kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. nginx-deploy-79b598b88-pt9xq / ImagePullBackOff 2d3h
  4. nginx-test-67d85d447c-brwb2 / Running 2d3h
  5. nginx-test-67d85d447c-l7xvs / Running 2d3h
  6. nginx-test-67d85d447c-qmrrw / Running 2d3h
  7. nginx-test-67d85d447c-rsmdt / Running 2d3h
  8. nginx-test-67d85d447c-twk77 / Running 2d3h
  9. pod-demo / Running 47h
  10. [root@k8s6 ~]# kubectl get pods -l release
  11. NAME READY STATUS RESTARTS AGE
  12. nginx-test-67d85d447c-twk77 / Running 2d3h
  13. pod-demo / Running 47h
  14. [root@k8s6 ~]# kubectl get pods -l release,app
  15. NAME READY STATUS RESTARTS AGE
  16. pod-demo / Running 47h
  17. [root@k8s6 ~]# kubectl get pods -l release=stable
  18. NAME READY STATUS RESTARTS AGE
  19. pod-demo / Running 47h
  20. [root@k8s6 ~]# kubectl get pods -l release=stable --show-labels
  21. NAME READY STATUS RESTARTS AGE LABELS
  22. pod-demo / Running 47h app=myapp,release=stable,tier=frontend

3.2)直接为pods节点服务器指定标签

  1. [root@k8s6 ~]# kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. nginx-deploy-79b598b88-pt9xq / ImagePullBackOff 2d3h
  4. nginx-test-67d85d447c-brwb2 / Running 2d3h
  5. nginx-test-67d85d447c-l7xvs / Running 2d3h
  6. nginx-test-67d85d447c-qmrrw / Running 2d3h
  7. nginx-test-67d85d447c-rsmdt / Running 2d3h
  8. nginx-test-67d85d447c-twk77 / Running 2d3h
  9. pod-demo / Running 47h
  10. [root@k8s6 ~]# kubectl label pods nginx-test-67d85d447c-twk77 relea=canary
  11. pod/nginx-test-67d85d447c-twk77 labeled
  12. [root@k8s6 ~]# kubectl get pods -l relea
  13. NAME READY STATUS RESTARTS AGE
  14. nginx-test-67d85d447c-twk77 / Running 2d3h

in和notin的用法

  1. kubectl get pods -l "release in (canary,beta,alpha)"
  2. kubectl get pods -l "release notin (canary,beta,alpha)"

4)内嵌字段的标签

  1. 节点默认标签
  2. 许多资源支持内嵌字段定义其使用标签选择器
  3. matchLabels: 直接给定键值
  4. matchExpressions: 基于给定的表达式来定义使用标签选择器,{key:"KEY",operator:"OPERATOR",value:[VALUE1,VALUE2,...]}
  5. 操作符:
  6. In,Notin:values字段的值必须为非空列表
  7. Exists,NotExists:values 字段的值必须非空列表

示例

  1. [root@k8s6 ~]# kubectl get nodes --show-labels
  2. NAME STATUS ROLES AGE VERSION LABELS
  3. k8s6 Ready master 5d18h v1.13.3 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s6,node-role.kubernetes.io/master=
  4. node01 Ready <none> 5d17h v1.13.3 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssd,kubernetes.io/hostname=node01
  5. node02 Ready <none> 5d17h v1.13.3 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node02
  6. [root@k8s6 ~]# kubectl label nodes node02 disktype=ssddd
  7. node/node02 labeled
  8. [root@k8s6 ~]# kubectl get nodes --show-labels
  9. NAME STATUS ROLES AGE VERSION LABELS
  10. k8s6 Ready master 5d18h v1.13.3 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=k8s6,node-role.kubernetes.io/master=
  11. node01 Ready <none> 5d17h v1.13.3 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssd,kubernetes.io/hostname=node01
  12. node02 Ready <none> 5d17h v1.13.3 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disktype=ssddd,kubernetes.io/hostname=node02

后面根据nodeSelector算法,新建的容器规模都只会在这个标签下的主机建立服务

  1. [root@k8s6 manifests]# cat pod-demo.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: pod-demo
  6. namespace: default
  7. labels:
  8. app: myapp
  9. tier: frontend
  10. annotations:
  11. blog.com/created-by: "cluster admin"
  12. spec:
  13. containers:
  14. - name: myapp
  15. image: nginx:1.14-alpine
  16. ports:
  17. - name: http
  18. containerPort:
  19. - name: https
  20. containerPort:
  21. - name: busybox
  22. image: busybox:latest
  23. imagePullPolicy: IfNotPresent
  24. command:
  25. - "/bin/sh"
  26. - "-c"
  27. - "sleep 3600"
  28. nodeSelector:
  29. disktype: ssdd

nodeSelector:

5)annotations 描述该镜像是由谁创建的

  1. [root@k8s6 manifests]# cat pod-demo.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: pod-demo
  6. namespace: default
  7. labels:
  8. app: myapp
  9. tier: frontend
  10. annotations:
  11. blog.com/created-by: "cluster admin"
  12. spec:
  13. containers:
  14. - name: myapp
  15. image: nginx:1.14-alpine
  16. ports:
  17. - name: http
  18. containerPort:
  19. - name: https
  20. containerPort:
  21. - name: busybox
  22. image: busybox:latest
  23. imagePullPolicy: IfNotPresent
  24. command:
  25. - "/bin/sh"
  26. - "-c"
  27. - "sleep 3600"
  28. nodeSelector:
  29. disktype: ssdd

annotations

kubectl describe pods pod-demo  查看详细描述信息

五、k8s的探测行为

  1. 探针类型有三种
  2. ExecActionTCPSockerActionHTTPGetAction

1)命令检测补充。test 命令

  1. [root@k8s6 ~]# test -e aa
  2. [root@k8s6 ~]# echo $?
  3.  
  4. [root@k8s6 ~]# touch aa
  5. [root@k8s6 ~]# test -e aa
  6. [root@k8s6 ~]# echo $?

命令探针使用。busybox镜像使用,测试存在问题

[root@k8s6 manifests]# kubectl create -f liveness-http.yaml

  1. [root@k8s6 manifests]# cat liveness-exec.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: liveness-exec-pod
  6. namespace: default
  7. spec:
  8. containers:
  9. - name: liveness-exec-container
  10. image: busybox:latest
  11. imagePullPolicy: IfNotPresent
  12. command: ["/bin/sh","-c","touch /tmp/healthy;sleep 30; rm -f /tmp/healthy;sleep 3600"]
  13. livenessProbe:
  14. exec:
  15. command: ["test","-e","/tmp/healthy"] # 探针命令,检测
  16. initialDelaySeconds:
  17. periodSeconds:

liveness-http.yaml

2)http的方式检测

  1. [root@k8s6 manifests]# cat liveness-http.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: liveness-httpget-pod
  6. namespace: default
  7. spec:
  8. containers:
  9. - name: liveness-exec-container
  10. image: ikubernetes/myapp:v1
  11. imagePullPolicy: IfNotPresent
  12. ports:
  13. - name: http
  14. containerPort:
  15. livenessProbe:
  16. httpGet:
  17. port: http
  18. path: /index.html
  19. initialDelaySeconds:
  20. periodSeconds:

检测方式

  1. [root@k8s6 ~]# kubectl exec -it liveness-httpget-pod -- /bin/sh 进入容器
  2. / # ls /usr/share/nginx/html/index.html 如果删除该文件,服务器会执行 curl 10.200.1.15 来检测该文件,如果没有,服务器会重启,来生成文件
  3. /usr/share/nginx/html/index.html
  4. / # cat /usr/share/nginx/html/[root@node02 ~]# curl 10.200.1.15
  5. Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
  6. <h1>hello world</h1>
  7. index.html
  8.  
  9. [root@node02 ~]# curl 10.200.1.15
  10. Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
  11. <h1>hello world</h1>

查看服务器是否重启过

  1. [root@k8s6 manifests]# kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. liveness-httpget-pod / Running 2m6s
  4.  
  5. # 可以看到服务器重启了一次
  6. [root@k8s6 manifests]# kubectl get pods
  7. NAME READY STATUS RESTARTS AGE
  8. liveness-httpget-pod / Running 3m23s

3)readinessProbe 探测。

如果删除了指定的index.html 文件,服务状态 变为不就绪状态。如果又创建该文件,服务器又自动变为就绪状态

  1. [root@k8s6 manifests]# cat readiness-httpget.yaml
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5. name: readiness-httpget-pod
  6. namespace: default
  7. spec:
  8. containers:
  9. - name: readiness-httpget-container
  10. image: ikubernetes/myapp:v1
  11. imagePullPolicy: IfNotPresent
  12. ports:
  13. - name: http
  14. containerPort:
  15. readinessProbe:
  16. httpGet:
  17. port: http
  18. path: /index.html
  19. initialDelaySeconds:
  20. periodSeconds:

readinessProbe

该脚本检测到未就绪状态,并不会重启服务

六、脚本修改容器规模大小

1)定义服务的yaml文件,内部临时定义2个规模的大小

  1. [root@k8s6 manifests]# cat rs-demo.yaml
  2. apiVersion: apps/v1
  3. kind: ReplicaSet
  4. metadata:
  5. name: myapp
  6. namespace: default
  7. spec:
  8. replicas:
  9. selector:
  10. matchLabels:
  11. app: myapp
  12. release: canary
  13. template:
  14. metadata:
  15. name: myapp-pod
  16. labels:
  17. app: myapp
  18. release: canary
  19. environment: qa
  20. spec:
  21. containers:
  22. - name: myapp-container
  23. image: ikubernetes/myapp:v1
  24. ports:
  25. - name: http
  26. containerPort:

rs-demo.yaml

查看,目前2个规模

  1. [root@k8s6 manifests]# kubectl create -f rs-demo.yaml
  2. replicaset.apps/myapp created
  3. [root@k8s6 manifests]# kubectl get rs
  4. NAME DESIRED CURRENT READY AGE
  5. myapp 15s

使用  kubectl edit rs myapp  可编辑规模大小

  1. [root@k8s6 ~]# kubectl edit rs myapp
  2. ................
  3. selfLink: /apis/extensions/v1beta1/namespaces/default/replicasets/myapp
  4. uid: 26caf59b-3dc3-11e9-8abb-000c2938db24
  5. spec:
  6. replicas:
  7. ................

再次查看,则变为5个了

  1. [root@k8s6 manifests]# kubectl get rs
  2. NAME DESIRED CURRENT READY AGE
  3. myapp 5m46s

2)另一种方式修改规模的大小。直接修改文件,kubectl apply -f rs-demo.yaml  检测文件的变化

  1. [root@k8s6 manifests]# vim rs-demo.yaml
  2. [root@k8s6 manifests]# kubectl apply -f rs-demo.yaml

kubectl get pods -l app=myapp -w  检测文件的变化

3)以打补丁的方式修改规模大小

  1. [root@k8s6 manifests]# cat rs-demo.yaml
  2. apiVersion: apps/v1
  3. kind: ReplicaSet
  4. metadata:
  5. name: myapp
  6. namespace: default
  7. spec:
  8. replicas:
  9. selector:
  10. matchLabels:
  11. app: myapp
  12. release: canary
  13. template:
  14. metadata:
  15. name: myapp-pod
  16. labels:
  17. app: myapp
  18. release: canary
  19. environment: qa
  20. spec:
  21. containers:
  22. - name: myapp-container
  23. image: ikubernetes/myapp:v1
  24. ports:
  25. - name: http
  26. containerPort:
  27. [root@k8s6 manifests]# kubectl get rs
  28. NAME DESIRED CURRENT READY AGE
  29. myapp 32m
  30. nginx-deploy-79b598b88 4d10h
  31. nginx-test-5bbfddf46b 4d10h
  32. nginx-test-67d85d447c 4d9h
  33. [root@k8s6 manifests]# kubectl patch ReplicaSet myapp -p '{"spec":{"replicas":5}}'
  34. replicaset.extensions/myapp patched
  35. [root@k8s6 manifests]# kubectl get rs
  36. NAME DESIRED CURRENT READY AGE
  37. myapp 32m
  38. nginx-deploy-79b598b88 4d10h
  39. nginx-test-5bbfddf46b 4d10h
  40. nginx-test-67d85d447c 4d9h

4)补充以打补丁的方式修改内容

  1. kubectl patch Deployment myapp-deploy -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}'

描述信息

  1. [root@k8s6 manifests]# kubectl describe deployment myapp-deploy
  2. Name: myapp-deploy
  3. Namespace: default
  4. CreationTimestamp: Sun, Mar :: +
  5. Labels: app=myapp
  6. release=canary
  7. Annotations: deployment.kubernetes.io/revision:
  8. kubectl.kubernetes.io/last-applied-configuration:
  9. {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"myapp-deploy","namespace":"default"},"spec":{"replicas":...
  10. Selector: app=myapp,release=canary
  11. Replicas: desired | updated | total | available | unavailable
  12. StrategyType: RollingUpdate
  13. MinReadySeconds:
  14. RollingUpdateStrategy: max unavailable, max surge

kubectl describe deployment myapp-deploy

六、查看滚动历史,回滚版本系统

1)编辑deploy-demp.yaml 指定kind: Deployment

  1. [root@k8s6 manifests]# cat deploy-demp.yaml
  2. apiVersion: apps/v1
  3. kind: Deployment
  4. metadata:
  5. name: myapp-deploy
  6. namespace: default
  7. spec:
  8. replicas:
  9. selector:
  10. matchLabels:
  11. app: myapp
  12. release: canary
  13. template:
  14. metadata:
  15. name: myapp
  16. labels:
  17. app: myapp
  18. release: canary
  19. spec:
  20. containers:
  21. - name: myapp-container
  22. image: ikubernetes/myapp:v1
  23. ports:
  24. - name: http
  25. containerPort:

deploy-demp.yaml

查看版本历史命令:kubectl rollout history deployment myapp-deploy

  1. [root@k8s6 manifests]# kubectl apply -f deploy-demp.yaml
  2. deployment.apps/myapp-deploy created
  3. [root@k8s6 manifests]# kubectl get rs
  4. NAME DESIRED CURRENT READY AGE
  5. myapp 38m
  6. myapp-deploy-6fdcbf595d 66s
  7. nginx-deploy-79b598b88 4d10h
  8. nginx-test-5bbfddf46b 4d10h
  9. nginx-test-67d85d447c 4d9h
  10. [root@k8s6 manifests]# kubectl rollout history deployment myapp-deploy
  11. deployment.extensions/myapp-deploy
  12. REVISION CHANGE-CAUSE
  13. <none>
  14. <none>

kubectl rollout history deployment myapp-deploy

它的滚动方式为: kubectl patch Deployment myapp-deploy -p '{"spec":{"replicas":5}}'

注意需要了解他们的区别。

  1. kind: Deployment
  2. kind: ReplicaSet

2)以打补丁的方式修改版本容器

  1. kubectl set image deployment myapp-deploy myapp=ikubernetes/myapp:v3 && kubectl rollout pause deployment myapp-deploy

修改时,先更新一个容器服务就被暂停了,后面需要取消暂停,其他容器才会更新

kubectl get pods -l app=myapp -w   监控更新变化

  1. kubectl rollout resume deployment myapp-deploy 取消之前的暂停,继续更新
  2. kubectl get rs -o wide 可查看使用的镜像版本

3)回滚版本

  1. [root@k8s6 manifests]# kubectl rollout history deployment myapp-deploy 查看历史版本
  2. [root@k8s6 manifests]# kubectl rollout undo deployment myapp-deploy --to-revision= 指定回到版本1

七、redis镜像的使用

redis镜像寻找地址:https://hub.docker.com/r/ikubernetes/filebeat/tags

先在节点拉取镜像:docker pull ikubernetes/filebeat:5.6.5-alpine

1)定义yaml文件(2个镜像内容)

  1. [root@k8s6 manifests]# cat ds-demo.yaml
  2. apiVersion: apps/v1
  3. kind: Deployment
  4. metadata:
  5. name: redis
  6. namespace: default
  7. spec:
  8. replicas:
  9. selector:
  10. matchLabels:
  11. app: redis
  12. role: logstor
  13. template:
  14. metadata:
  15. labels:
  16. app: redis
  17. role: logstor
  18. spec:
  19. containers:
  20. - name: redis
  21. image: redis:4.0-alpine
  22. ports:
  23. - name: redis
  24. containerPort:
  25. ---
  26. apiVersion: apps/v1
  27. kind: DaemonSet
  28. metadata:
  29. name: filebeat-ds
  30. namespace: default
  31. spec:
  32. selector:
  33. matchLabels:
  34. app: filebeat
  35. release: stable
  36. template:
  37. metadata:
  38. labels:
  39. app: filebeat
  40. release: stable
  41. spec:
  42. containers:
  43. - name: filebeat
  44. image: ikubernetes/filebeat:5.6.-alpine
  45. env:
  46. - name: REDIS_HOST
  47. value: redis.default.svc.cluster.local
  48. - name: REDOS_LOG_LEVEL
  49. value: info

ds-demo.yaml

创新该服务

  1. [root@k8s6 manifests]# kubectl apply -f ds-demo.yaml
  2. deployment.apps/redis created
  3. daemonset.apps/filebeat-ds created
  4. [root@k8s6 manifests]# kubectl get pods -o wide
  5. NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
  6. filebeat-ds-9q792 / Running 44s 10.200.1.26 node02 <none> <none>
  7. filebeat-ds-fw6r7 / Running 44s 10.200.2.26 node01 <none> <none>
  8. redis-85b846ff9c-g8cdt / Running 44s 10.200.1.25 node02 <none> <none>
  9. [root@k8s6 manifests]# kubectl expose deployment redis --port=
  10. service/redis exposed
  11. [root@k8s6 manifests]# kubectl get svc
  12. NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
  13. kubernetes ClusterIP 10.96.0.1 <none> /TCP 6d1h
  14. nginx NodePort 10.107.169.145 <none> :/TCP 4d11h
  15. redis ClusterIP 10.99.49.232 <none> /TCP 52s

更新定义的filebeat-ds 镜像

  1. [root@k8s6 manifests]# kubectl get ds
  2. NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE
  3. filebeat-ds <none> 22m
  4. [root@k8s6 manifests]# kubectl get ds -o wide
  5. NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE CONTAINERS IMAGES SELECTOR
  6. filebeat-ds <none> 22m filebeat ikubernetes/filebeat:5.6.-alpine app=filebeat,release=stable
  7. [root@k8s6 manifests]# kubectl set image daemonsets filebeat-ds filebeat=ikubernetes/filebeat:5.6.-alpine
  8. daemonset.extensions/filebeat-ds image updated
  9. [root@k8s6 manifests]# kubectl get ds -o wide
  10. NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE CONTAINERS IMAGES SELECTOR
  11. filebeat-ds <none> 24m filebeat ikubernetes/filebeat:5.6.-alpine app=filebeat,release=stable

k8s的基本使用的更多相关文章

  1. 【Kubernetes】K8S网络方案--最近在看的

    K8S网络-最近在看的 Create a Minikube cluster - Kubernetes Kubernetes Documentation - Kubernetes Kubernetes ...

  2. 【Kubernetes】K8S 网络隔离 方案

    参考资料: K8S-网络隔离参考 OpenContrail is an open source network virtualization platform for the cloud. – Kub ...

  3. k8s入门系列之guestbook快速部署

    k8s集群以及一些扩展插件已经安装完毕,本篇文章介绍一下如何在k8s集群上快速部署guestbook应用. •实验环境为集群:master(1)+node(4),详细内容参考<k8s入门系列之集 ...

  4. k8s volume

        只有nfs和rbd的,本人翻译确实很渣         在容器中磁盘文件寿命是短暂的,当在容器中运行一些重要程序时,这会产生一些问题. 首先,当一个容器崩溃后,kubelet将重新启动该容器, ...

  5. k8s pv

    这个文档描述当前在k8s中PersistentVolumes的使用. 我们建议和volume一起进行了解   Introduction     管理存储和管理计算是截然不同的问题. 持久存储子系统对用 ...

  6. k8s DNS 服务发现的一个坑

    按照官当文档,以及大家的实践进行k8s dns 服务发现搭建还是比较简单的,但是会有一个因为系统默认dns 配置造成的一个问题 1. linux  默认dns 配置在 /etc/resolv.conf ...

  7. k8s dns 服务安装配置说明

    1. 提前条件 安装k8s 集群 2.  dns  安装配置 安装方式: 使用controller  service controller  脚本: 基于官方改动 apiVersion: v1 kin ...

  8. 第四十四章 微服务CICD(6)- gitlab + jenkins + docker + k8s

    总体流程: 在开发机开发代码后提交到gitlab 之后通过webhook插件触发jenkins进行构建,jenkins将代码打成docker镜像,push到docker-registry 之后将在k8 ...

  9. k8s入门系列之扩展组件(二)kube-ui安装篇

    kube-ui是k8s提供的web管理界面,可以展示节点的内存.CPU.磁盘.Pod.RC.SVC等信息. 1.编辑kube-dashboard-rc.yml定义文件[root@master kube ...

  10. k8s入门系列之扩展组件(一)DNS安装篇

    DNS (domain name system),提供域名解析服务,解决了难于记忆的IP地址问题,以更人性可读可记忆可标识的方式映射对应IP地址. Cluster DNS扩展插件用于支持k8s集群系统 ...

随机推荐

  1. 深度学习原理与框架-图像补全(原理与代码) 1.tf.nn.moments(求平均值和标准差) 2.tf.control_dependencies(先执行内部操作) 3.tf.cond(判别执行前或后函数) 4.tf.nn.atrous_conv2d 5.tf.nn.conv2d_transpose(反卷积) 7.tf.train.get_checkpoint_state(判断sess是否存在

    1. tf.nn.moments(x, axes=[0, 1, 2])  # 对前三个维度求平均值和标准差,结果为最后一个维度,即对每个feature_map求平均值和标准差 参数说明:x为输入的fe ...

  2. 查看log日志

    本地环境的的log日志 可以直接查看, 对于新手来说怎么查看正式环境下的log日志呢 1, SSH到服务器 2,cd 到logs所在目录 3, tail -f 对应日志名字

  3. Linux OS7 常用

    查看防火墙状态: firewall-cmd --state;停止firewall: systemctl stop firewalld.service;禁止firewall开机启动:systemctl ...

  4. .net Cache 需要注意的地方

    CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ti ...

  5. 基于innodb_print_all_deadlocks从errorlog中解析MySQL死锁日志

    本文是说明如何获取死锁日志记录的,不是说明如何解决死锁问题的. MySQL的死锁可以通过show engine innodb status;来查看,但是show engine innodb statu ...

  6. hbase 存储结构和原理

    HBase的表结构 建表时要指定的是:表名.列族 建表语句 create 'user_info', 'base_info', 'ext_info' 意思是新建一个表,名称是user_info,包含两个 ...

  7. eclipse中的web项目部署路径

    elipse添加了server之后,如果不对tomcat的部署路径做更改,则eclipse默认对工程的部署在 eclipse-workspace\.metadata.plugins\org.eclip ...

  8. Linux /etc/hosts文件

    均为转载 ———————— 1.主机名: 无论在局域网还是INTERNET上,每台主机都有一个IP地址,是为了区分此台主机和彼台主机,也就是说IP地址就是主机的门牌号. 公网:IP地址不方便记忆,所以 ...

  9. mysql内容总体回顾

    数据类型: 数值类型: 整形 浮点型 字符串: char(定长)\varchar(不定长) char(定长):插入数据或查询数据都快,因为char在磁盘上插入数据时的存储空间是固定的,简单粗暴,直接就 ...

  10. myhabits where in foreach

    myhabits传入参数:类,其中类中包含字符串数组String[] 当查询where in String[]时 <select id="selectData" parame ...