kubernetes学习笔记-命令篇

kubectl create命令:

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 registry.yaml in JSON then create the resource using the edited data
  kubectl create -f registry.yaml --edit -o json

Available Commands:
  clusterrole           Create a cluster role
  clusterrolebinding    Create a cluster role binding for a particular cluster role
  configmap             Create a config map from a local file, directory or literal value
  cronjob               Create a cron job with the specified name
  deployment            Create a deployment with the specified name
  ingress               Create an ingress with the specified name
  job                   Create a job with the specified name
  namespace             创建一个指定名称的 namespace
  poddisruptionbudget   Create a pod disruption budget with the specified name
  priorityclass         Create a priority class with the specified name
  quota                 Create a quota with the specified name
  role                  Create a role with single rule
  rolebinding           Create a role binding for a particular role or cluster role
  secret                使用指定的 subcommand 创建一个 secret
  service               Create a service using a specified subcommand
  serviceaccount        创建一个指定名称的 service account
  token                 Request a service account token

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='none':
	Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without
	sending it. If server strategy, submit server-side request without persisting the resource.

    --edit=false:
	Edit the API resource before creating

    --field-manager='kubectl-create':
	Name of the manager used to track field ownership.

    -f, --filename=[]:
	Filename, directory, or URL to files to use to create the resource

    -k, --kustomize='':
	Process the kustomization directory. This flag can't be used together with -f or -R.

    -o, --output='':
	Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath,
	jsonpath-as-json, jsonpath-file).

    --raw='':
	Raw URI to POST to the server.  Uses the transport specified by the kubeconfig file.

    -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). Matching
	objects must satisfy all of the specified label constraints.

    --show-managed-fields=false:
	If true, keep the managedFields when printing objects in JSON or YAML format.

    --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='strict':
	Must be one of: strict (or true), warn, ignore (or false). 		"true" or "strict" will use a schema to validate
	the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation
	is enabled on the api-server, but will fall back to less reliable client-side validation if not. 		"warn" will
	warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled
	on the API server, and behave as "ignore" otherwise. 		"false" or "ignore" will not perform any schema
	validation, silently dropping any unknown or duplicate fields.

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

kubectl run命令:

Create and run a particular image in a pod.

Examples:
  # Start a nginx pod
  kubectl run nginx --image=nginx
  
  # Start a hazelcast pod and let the container expose port 5701
  kubectl run hazelcast --image=hazelcast/hazelcast --port=5701
  
  # Start a hazelcast pod and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default" in the
container
  kubectl run hazelcast --image=hazelcast/hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
  
  # Start a hazelcast pod and set labels "app=hazelcast" and "env=prod" in the container
  kubectl run hazelcast --image=hazelcast/hazelcast --labels="app=hazelcast,env=prod"
  
  # Dry run; print the corresponding API objects without creating them
  kubectl run nginx --image=nginx --dry-run=client
  
  # Start a nginx pod, but overload the spec with a partial set of values parsed from JSON
  kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'
  
  # Start a busybox pod and keep it in the foreground, don't restart it if it exits
  kubectl run -i -t busybox --image=busybox --restart=Never
  
  # Start the nginx pod using the default command, but use custom arguments (arg1 .. argN) for that command
  kubectl run nginx --image=nginx --   ... 
  
  # Start the nginx pod using a different command and custom arguments
  kubectl run nginx --image=nginx --command --   ... 

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.

    --annotations=[]:
	Annotations to apply to the pod.

    --attach=false:
	If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...' were called.
	Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the exit
	code of the container process is returned.

    --cascade='background':
	Must be "background", "orphan", or "foreground". Selects the deletion cascading strategy for the dependents
	(e.g. Pods created by a ReplicationController). Defaults to background.

    --command=false:
	If true and extra arguments are present, use them as the 'command' field in the container, rather than the
	'args' field which is the default.

    --dry-run='none':
	Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without
	sending it. If server strategy, submit server-side request without persisting the resource.

    --env=[]:
	Environment variables to set in the container.

    --expose=false:
	If true, create a ClusterIP service associated with the pod.  Requires `--port`.

    --field-manager='kubectl-run':
	Name of the manager used to track field ownership.

    -f, --filename=[]:
	to use to replace the resource.

    --force=false:
	If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of
	some resources may result in inconsistency or data loss and requires confirmation.

    --grace-period=-1:
	Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for
	immediate shutdown. Can only be set to 0 when --force is true (force deletion).

    --image='':
	指定容器要运行的镜像.

    --image-pull-policy='':
	The image pull policy for the container.  If left empty, this value will not be specified by the client and
	defaulted by the server.

    -k, --kustomize='':
	Process a kustomization directory. This flag can't be used together with -f or -R.

    -l, --labels='':
	Comma separated labels to apply to the pod. Will override previous values.

    --leave-stdin-open=false:
	If the pod is started in interactive mode or with stdin, leave stdin open after the first attach completes. By
	default, stdin will be closed after the first attach completes.

    -o, --output='':
	Output format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath,
	jsonpath-as-json, jsonpath-file).

    --override-type='merge':
	The method used to override the generated object: json, merge, or strategic.

    --overrides='':
	An inline JSON override for the generated object. If this is non-empty, it is used to override the generated
	object. Requires that the object supply a valid apiVersion field.

    --pod-running-timeout=1m0s:
	The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running

    --port='':
	The port that this container exposes.

    --privileged=false:
	If true, run the container in privileged mode.

    -q, --quiet=false:
	If true, suppress prompt messages.

    -R, --recursive=false:
	Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests
	organized within the same directory.

    --restart='Always':
	The restart policy for this Pod.  Legal values [Always, OnFailure, Never].

    --rm=false:
	If true, delete the pod after it exits.  Only valid when attaching to the container, e.g. with '--attach' or
	with '-i/--stdin'.

    --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.

    --show-managed-fields=false:
	If true, keep the managedFields when printing objects in JSON or YAML format.

    -i, --stdin=false:
	Keep stdin open on the container in the pod, even if nothing is attached.

    --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].

    --timeout=0s:
	The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the
	object

    -t, --tty=false:
	Allocate a TTY for the container in the pod.

    --wait=false:
	If true, wait for resources to be gone before returning. This waits for finalizers.

Usage:
  kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client] [--overrides=inline-json]
[--command] -- [COMMAND] [args...] [options]

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

kubectl describe命令:

Show details of a specific resource or group of resources.

 Print a detailed description of the selected resources, including related resources such as events or controllers. You
may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example:

  $ kubectl describe TYPE NAME_PREFIX
  
 will first check for an exact match on TYPE and NAME_PREFIX. If no such resource exists, it will output details for
every resource that has a name prefixed with NAME_PREFIX.

Use "kubectl api-resources" for a complete list of supported resources.

Examples:
  # Describe a node
  kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
  
  # Describe a pod
  kubectl describe pods/nginx
  
  # Describe a pod identified by type and name in "pod.json"
  kubectl describe -f pod.json
  
  # Describe all pods
  kubectl describe pods
  
  # Describe pods by label name=myLabel
  kubectl describe po -l name=myLabel
  
  # Describe all pods managed by the 'frontend' replication controller
  # (rc-created pods get the name of the rc as a prefix in the pod name)
  kubectl describe pods frontend

Options:
    -A, --all-namespaces=false:
	If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even
	if specified with --namespace.

    --chunk-size=500:
	Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in
	the future.

    -f, --filename=[]:
	Filename, directory, or URL to files containing the resource to describe

    -k, --kustomize='':
	Process the kustomization directory. This flag can't be used together with -f or -R.

    -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, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching
	objects must satisfy all of the specified label constraints.

    --show-events=true:
	If true, display events related to the described object.

Usage:
  kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME) [options]

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

kubectl delete命令:

Delete resources by file names, stdin, resources and names, or by resources and label selector.

 JSON and YAML formats are accepted. Only one type of argument may be specified: file names, resources and names, or
resources and label selector.

 Some resources, such as pods, support graceful deletion. These resources define a default period before they are
forcibly terminated (the grace period) but you may override that value with the --grace-period flag, or pass --now to
set a grace-period of 1. Because these resources often represent entities in the cluster, deletion may not be
acknowledged immediately. If the node hosting a pod is down or cannot reach the API server, termination may take
significantly longer than the grace period. To force delete a resource, you must specify the --force flag. Note: only a
subset of resources support graceful deletion. In absence of the support, the --grace-period flag is ignored.

 IMPORTANT: Force deleting pods does not wait for confirmation that the pod's processes have been terminated, which can
leave those processes running until the node detects the deletion and completes graceful deletion. If your processes use
shared storage or talk to a remote API and depend on the name of the pod to identify themselves, force deleting those
pods may result in multiple processes running on different machines using the same identification which may lead to data
corruption or inconsistency. Only force delete pods when you are sure the pod is terminated, or if your application can
tolerate multiple copies of the same pod running at once. Also, if you force delete pods, the scheduler may place new
pods on those nodes before the node has released those resources and causing those pods to be evicted immediately.

 Note that the delete command does NOT do resource version checks, so if someone submits an update to a resource right
when you submit a delete, their update will be lost along with the rest of the resource.

 After a CustomResourceDefinition is deleted, invalidation of discovery cache may take up to 10 minutes. If you don't
want to wait, you might want to run "kubectl api-resources" to refresh the discovery cache.

Examples:
  # Delete a pod using the type and name specified in pod.json
  kubectl delete -f ./pod.json
  
  # Delete resources from a directory containing kustomization.yaml - e.g. dir/kustomization.yaml
  kubectl delete -k dir
  
  # Delete resources from all files that end with '.json' - i.e. expand wildcard characters in file names
  kubectl apply -f '*.json'
  
  # Delete a pod based on the type and name in the JSON passed into stdin
  cat pod.json | kubectl delete -f -
  
  # Delete pods and services with same names "baz" and "foo"
  kubectl delete pod,service baz foo
  
  # Delete pods and services with label name=myLabel
  kubectl delete pods,services -l name=myLabel
  
  # Delete a pod with minimal delay
  kubectl delete pod foo --now
  
  # Force delete a pod on a dead node
  kubectl delete pod foo --force
  
  # Delete all pods
  kubectl delete pods --all

Options:
    --all=false:
	Delete all resources, in the namespace of the specified resource types.

    -A, --all-namespaces=false:
	If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even
	if specified with --namespace.

    --cascade='background':
	Must be "background", "orphan", or "foreground". Selects the deletion cascading strategy for the dependents
	(e.g. Pods created by a ReplicationController). Defaults to background.

    --dry-run='none':
	Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without
	sending it. If server strategy, submit server-side request without persisting the resource.

    --field-selector='':
	Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector
	key1=value1,key2=value2). The server only supports a limited number of field queries per type.

    -f, --filename=[]:
	containing the resource to delete.

    --force=false:
	If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of
	some resources may result in inconsistency or data loss and requires confirmation.

    --grace-period=-1:
	Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for
	immediate shutdown. Can only be set to 0 when --force is true (force deletion).

    --ignore-not-found=false:
	Treat "resource not found" as a successful delete. Defaults to "true" when --all is specified.

    -k, --kustomize='':
	Process a kustomization directory. This flag can't be used together with -f or -R.

    --now=false:
	If true, resources are signaled for immediate shutdown (same as --grace-period=1).

    -o, --output='':
	Output mode. Use "-o name" for shorter output (resource/name).

    --raw='':
	Raw URI to DELETE to the server.  Uses the transport specified by the kubeconfig file.

    -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, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching
	objects must satisfy all of the specified label constraints.

    --timeout=0s:
	The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the
	object

    --wait=true:
	If true, wait for resources to be gone before returning. This waits for finalizers.

Usage:
  kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)]) [options]

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

创建名称为space的命名空间:

kubectl create namespace space

删除名称为space的命名空间:

kubectl delete namespace space

创建nginx名称为pod-name的pod

kubectl run pod-name --image=nginx

pod相关配置yaml(括号为解释说明):

apiVersion: v1
kind: Pod
metadata:
  labels:
    run: xxx (名称)
  name: xxx (名称)
spec: 
  restartPolicy: Always    (重启策略) [Always|Never|OnFailure] 节点挂掉总是重启|从不重启|异常出错时重启
  containers: 
    - image: xxx (镜像)
      name: XXX (名称)
  hostAliases:
    - ip: "192.168.1.2"
      hostnames:
        - "xx1"
        - "xx2"
  dnsPolicy: Default        (dns策略) [ClusterFirst|Default]  使用集群内部coredns|使用集群所在宿主机/etc/resolv.conf内配置的dns,建议指定,默认ClusterFirst而不是Default
  imagePullPolicy: Always     (镜像拉取策略) [Always|Never|IfNotPresent]  总是拉取|从不拉取(使用本地镜像)|本地不存在镜像时拉取
  env: (环境变量)
    - key1: value1
    - key2: value2
  ports: (端口号 一般不写)
    - containerPort (容器监听端口)
    - hostPort
    - protocol
 command: (命令,一般不怎么用,以下为两个1800秒睡眠,两条命令并列)
    - sleep
    - "1800"  (睡眠1800秒,不要这么用,举例子...)
    - ";"
    - "sleep 1800"
 args: (给command传参)
 resources: (资源限制)
   limits: (上限)
      memory:  128M    (限制内存,超过后pod会oom,自动重启1G = 1000M, 1G = 1024Mi)
      cpu: 0.5       (cpu核数 1代表1核=1000m,软限制,当使用到配置的上限时,还有空余cpu,那么可以继续使用更多的cpu,程序不会被杀死)
   requests: (初始化时申请的资源数量)
      memory:  32M     (最低标准使用内存,当最低标准仍然高于实际使用,默认会以最低标准为准申请内存)
      cpu: 0.1  (最低标准cup使用率)

列出pod

kubectl get pods

列出 命名空间为kube-system下的pod

kubectl get pods -o wide -n kube-system

查看pod详细信息

kubectl describe po podname -n kube-system

查看后显示的相关信息

name (名称)
namespace (命名空间)
ip
node
label
annotation (注释)
event (事件)

进入pod (类似于docker命令进入pod)

kubectl exec -it podname /bin/bash

node查看

kubectl get nodes
kubectl get nodes -o wide 

查看node详细信息

kubectl describe node nodename

删除node

kubectl delete node nodename

你可能感兴趣的:(kubernetes)