[root@mcwk8s04 ~]# kubectl -h
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 Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
run Run a particular image on the cluster
set Set specific features on objects
Basic Commands (Intermediate):
explain Documentation of resources
get Display one or many resources
edit Edit a resource on the server
delete Delete resources by filenames, stdin, resources and names, or by resources and label selector
Deploy Commands:
rollout Manage the rollout of a resource
scale Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job
autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController
Cluster Management Commands:
certificate Modify certificate resources.
cluster-info Display cluster info
top Display Resource (CPU/Memory/Storage) usage.
cordon Mark node as unschedulable
uncordon Mark node as schedulable
drain Drain node in preparation for maintenance
taint Update the taints on one or more nodes
Troubleshooting and Debugging Commands:
describe Show details of a specific resource or group of resources
logs Print the logs for a container in a pod
attach Attach to a running container
exec Execute a command in a container
port-forward Forward one or more local ports to a pod
proxy Run a proxy to the Kubernetes API server
cp Copy files and directories to and from containers.
auth Inspect authorization
Advanced Commands:
diff Diff live version against would-be applied version
apply Apply a configuration to a resource by filename or stdin
patch Update field(s) of a resource using strategic merge patch
replace Replace a resource by filename or stdin
wait Experimental: Wait for a specific condition on one or many resources.
convert Convert config files between different API versions
kustomize Build a kustomization target from a directory or a remote url.
Settings Commands:
label Update the labels on a resource
annotate Update the annotations on a resource
completion Output shell completion code for the specified shell (bash or zsh)
Other Commands:
api-resources Print the supported API resources on the server
api-versions Print the supported API versions on the server, in the form of "group/version"
config Modify kubeconfig files
plugin Provides utilities for interacting with plugins.
version Print the client and server version information
Usage:
kubectl [flags] [options]
Use "kubectl --help"for more information about a given command.
Use "kubectl options"for a list of global command-line options (applies to all commands).
[root@mcwk8s04 ~]#
kubectl run 命令帮助信息
[root@mcwk8s04 ~]# kubectl run --help
Create and run a particular image, possibly replicated.
Creates a deployment or job to manage the created container(s).
Examples:
# Start a single instance of nginx.
kubectl run nginx --image=nginx
# Start a single instance of hazelcast and let the container expose port 5701 .
kubectl run hazelcast --image=hazelcast --port=5701
# Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default"in the container.
kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
# Start a single instance of hazelcast and set labels "app=hazelcast" and "env=prod"in the container.
kubectl run hazelcast --image=hazelcast --labels="app=hazelcast,env=prod"
# Start a replicated instance of nginx.
kubectl run nginx --image=nginx --replicas=5
# Dry run. Print the corresponding API objects without creating them.
kubectl run nginx --image=nginx --dry-run
# Start a single instance of nginx, but overload the spec of the deployment with a partialset of values parsed from
JSON.
kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'
# Start a pod of busybox 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 container using the default command, but use custom arguments (arg1 .. argN) for that command.
kubectl run nginx --image=nginx -- ...
# Start the nginx container using a different command and custom arguments.
kubectl run nginx --image=nginx --command -- ...
# Start the perl container to compute π to 2000 places and print it out.
kubectl run pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'
# Start the cron job to compute π to 2000 places and print it out every 5 minutes.
kubectl run pi --schedule="0/5 * * * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'
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.
--attach=false: If true, wait for the Pod to start running, and then attach to the Pod asif'kubectl attach ...'
were called. Default false, unless '-i/--stdin'isset, in which case the defaultistrue. With '--restart=Never' the
exit code of the container process is returned.
--cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
ReplicationController). Default true.
--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=false: If true, only print the object that would be sent, without sending it.
--env=[]: Environment variables to setin the container
--expose=false: If true, a public, external service is created for the container(s) which are run
-f, --filename=[]: to use to replace the resource.
--force=false: Only used when grace-period=0. 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.
--generator='': The name of the API generator to use, see
http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators for a list.
--grace-period=-1: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.
Set to 1for immediate shutdown. Can only be set to 0 when --force istrue (force deletion).
--hostport=-1: The host port mapping for the container port. To demonstrate a single-machine container.
--image='': The image for the container to run.
--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(s). 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.
--limits='': The resource requirement limits forthis container. For example, 'cpu=200m,memory=512Mi'. Note that
server side components may assign limits depending on the server configuration, such as limit ranges.
-o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
--overrides='': An inline JSON overridefor the generated object. If thisis 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. If --expose istrue, thisis also the port used by the service
that is created.
--quiet=false: If true, suppress prompt messages.
--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.
-r, --replicas=1: Number of replicas to create forthis container. Default is1.
--requests='': The resource requirement requests forthis container. For example, 'cpu=100m,memory=256Mi'. Note
that server side components may assign requests depending on the server configuration, such as limit ranges.
--restart='Always': The restart policy forthis Pod. Legal values [Always, OnFailure, Never]. If set to 'Always'
a deployment is created, ifset to 'OnFailure' a job is created, ifset to 'Never', a regular pod is created. For the
latter two --replicas must be 1. Default 'Always', for CronJobs `Never`.
--rm=false: If true, delete resources created inthis command for attached containers.
--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 thisobjectin the future.
--schedule='': A schedule in the Cron format the job should be run with.
--service-generator='service/v2': The name of the generator to use for creating a service. Only used if --expose
istrue
--service-overrides='': An inline JSON overridefor the generated service object. If thisis non-empty, it is used
to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose istrue.
--serviceaccount='': Service account to setin the pod spec
-i, --stdin=false: Keep stdin open on the container(s) 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: Allocated a TTY for each 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] [--replicas=replicas] [--dry-run=bool]
[--overrides=inline-json] [--command] -- [COMMAND] [args...] [options]
Use "kubectl options"for a list of global command-line options (applies to all commands).
[root@mcwk8s04 ~]#
kubectl expose帮助信息
[root@mcwk8s04 ~]# kubectl expose -h
Expose a resource as a new Kubernetes service.
Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector for that
resource as the selector for a new service on the specified port. A deployment or replica set will be exposed as a
service only if its selector is convertible to a selector that service supports, i.e. when the selector contains only
the matchLabels component. Note that if no port is specified via --port and the exposed resource has multiple ports, all
will be re-used by the new service. Also if no labels are specified, the new service will re-use the labels from the
resource it exposes.
Possible resources include (case insensitive):
pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)
Examples:
# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000.
kubectl expose rc nginx --port=80 --target-port=8000
# Create a service for a replication controller identified by type and name specified in"nginx-controller.yaml",
which serves on port 80 and connects to the containers on port 8000.
kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000
# Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"
kubectl expose pod valid-pod --port=444 --name=frontend
# Create a second service based on the above service, exposing the container port 8443as port 443 with the name
"nginx-https"
kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https
# Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'.
kubectl expose rc streamer --port=4100 --protocol=UDP --name=video-stream
# Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on
port 8000.
kubectl expose rs nginx --port=80 --target-port=8000
# Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000.
kubectl expose deployment nginx --port=80 --target-port=8000
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.
--cluster-ip='': ClusterIP to be assigned to the service. Leave empty to auto-allocate, or set to 'None' to create
a headless service.
--dry-run=false: If true, only print the object that would be sent, without sending it.
--external-ip='': Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP
is routed to a node, the service can be accessed by this IP in addition to its generated service IP.
-f, --filename=[]: Filename, directory, or URL to files identifying the resource to expose a service
--generator='service/v2': The name of the API generator to use. There are 2 generators: 'service/v1' and
'service/v2'. The only difference between them is that service port in v1 is named 'default', while it is left unnamed
in v2. Default is'service/v2'.
-k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
-l, --labels='': Labels to apply to the service created by this call.
--load-balancer-ip='': IP to assign to the LoadBalancer. If empty, an ephemeral IP will be created and used
(cloud-provider specific).
--name='': The name for the newly created object.
-o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
--overrides='': An inline JSON overridefor the generated object. If thisis non-empty, it is used to override the
generated object. Requires that the object supply a valid apiVersion field.
--port='': The port that the service should serve on. Copied from the resource being exposed, if unspecified
--protocol='': The network protocol for the service to be created. Default is'TCP'.
--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 thisobjectin the future.
--selector='': A label selector to use forthis service. Only equality-based selector requirements are supported.
If empty (the default) infer the selector from the replication controller or replica set.)
--session-affinity='': If non-empty, set the session affinity for the service to this; legal values: 'None',
'ClientIP'
--target-port='': Name or number for the port on the container that the service should direct traffic to.
Optional.
--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].
--type='': Type forthis service: ClusterIP, NodePort, LoadBalancer, or ExternalName. Default is'ClusterIP'.
Usage:
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]
Use "kubectl options"for a list of global command-line options (applies to all commands).
[root@mcwk8s04 ~]#
kubectl logs帮助信息
[root@mcwk8s04 ~]# kubectl logs -h
Print the logs for a container in a pod or specified resource. If the pod has only one container, the container name is
optional.
Aliases:
logs, log
Examples:
# Return snapshot logs from pod nginx with only one container
kubectl logs nginx
# Return snapshot logs from pod nginx with multi containers
kubectl logs nginx --all-containers=true
# Return snapshot logs from all containers in pods defined by label app=nginx
kubectl logs -lapp=nginx --all-containers=true
# Return snapshot of previous terminated ruby container logs from pod web-1
kubectl logs -p -c ruby web-1
# Begin streaming the logs of the ruby container in pod web-1
kubectl logs -f -c ruby web-1
# Begin streaming the logs from all containers in pods defined by label app=nginx
kubectl logs -f -lapp=nginx --all-containers=true
# Display only the most recent 20 lines of output in pod nginx
kubectl logs --tail=20 nginx
# Show all logs from pod nginx written in the last hour
kubectl logs --since=1h nginx
# Return snapshot logs from first container of a job named hello
kubectl logs job/hello
# Return snapshot logs from container nginx-1 of a deployment named nginx
kubectl logs deployment/nginx -c nginx-1
Options:
--all-containers=false: Get all containers' logs in the pod(s).
-c, --container='': Print the logs of this container
-f, --follow=false: Specify if the logs should be streamed.
--ignore-errors=false: If watching / following pod logs, allow for any errors that occur to be non-fatal
--limit-bytes=0: Maximum bytes of logs to return. Defaults to no limit.
--max-log-requests=5: Specify maximum number of concurrent logs to follow when using by a selector. Defaults to 5.
--pod-running-timeout=20s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running
-p, --previous=false: If true, print the logs for the previous instance of the container in a pod if it exists.
-l, --selector='': Selector (label query) to filter on.
--since=0s: Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of
since-time / since may be used.
--since-time='': Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time /
since may be used.
--tail=-1: Lines of recent log file to display. Defaults to -1 with no selector, showing all log lines otherwise
10, if a selector is provided.
--timestamps=false: Include timestamps on each line in the log output
Usage:
kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER] [options]
Use "kubectl options"for a list of global command-line options (applies to all commands).
[root@mcwk8s04 ~]#
kubectl set 帮助信息
[root@mcwk8s03 ~]# kubectl set -h
Configure application resources
These commands help you make changes to existing application resources.
Available Commands:
env Update environment variables on a pod template
image Update image of a pod template
resources Update resource requests/limits on objects with pod templates
selector Set the selector on a resource
serviceaccount Update ServiceAccount of a resource
subject Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding
Usage:
kubectl set SUBCOMMAND [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).
[root@mcwk8s03 ~]#
kubectl set image帮助信息
[root@mcwk8s03 ~]# kubectl set image -h
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 getfrom a server.
-k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
--local=false: If true, set image will NOT contact api-server but run locally.
-o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|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@mcwk8s03 ~]#
kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...] [options]
NAM:容器的名称
--image:指定使用的镜像
--env:指定容器内的环境变量,
--port:指定容器中需要映射的端口,也就是需要暴露的服务的端口
--replicas:指定副本数
--dry-run:指定是创建还是测试用
--overrides:可以重写配置
--command :可以替换容器启动时的命令。
[root@mcwk8s04 ~]#
[root@mcwk8s04 ~]# kubectl run mcw-nginx-deployment --image=nginx --port=80 --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.
deployment.apps/mcw-nginx-deployment created
[root@mcwk8s04 ~]#
[root@mcwk8s04 ~]# kubectl get pod -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
mcw-nginx-deployment-86466dbd78-fkrs7 1/1 Running 0 27m 172.17.13.2 mcwk8s05
mcw-nginx-deployment-86466dbd78-rnvsc 1/1 Running 0 27m 172.17.13.4 mcwk8s05
mcw-nginx-deployment-86466dbd78-znjbm 1/1 Running 0 27m 172.17.21.3 mcwk8s06
[root@mcwk8s04 ~]#
kubectl get
指定查看多个资源
[root@mcwk8s04 ~]# kubectl get deploy,pods
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.extensions/mcw-nginx-deployment 3/333 29m
NAME READY STATUS RESTARTS AGE
pod/mcw-nginx-deployment-86466dbd78-fkrs7 1/1 Running 0 29m
pod/mcw-nginx-deployment-86466dbd78-rnvsc 1/1 Running 0 29m
pod/mcw-nginx-deployment-86466dbd78-znjbm 1/1 Running 0 29m
[root@mcwk8s04 ~]#
查看副本
[root@mcwk8s04 ~]# kubectl get replicasets
NAME DESIRED CURRENT READY AGE
mcw-nginx-deployment-86466dbd78 333 31m
[root@mcwk8s04 ~]# kubectl get rs
NAME DESIRED CURRENT READY AGE
mcw-nginx-deployment-86466dbd78 333 31m
[root@mcwk8s04 ~]#
[root@mcwk8s04 ~]# kubectl expose deployment --port=80 --target-port=80 --name=mcw-nginx-service --type=NodePort
error: resource(s) were provided, but no name, label selector, or --all flag specified
See 'kubectl expose -h'for help and examples
[root@mcwk8s04 ~]# kubectl get deployment
NAME READY UP-TO-DATE AVAILABLE AGE
mcw-nginx-deployment 3/333 54m
[root@mcwk8s04 ~]# kubectl expose deployment mcw-nginx-deployment --port=80 --target-port=80 --name=mcw-nginx-service --type=NodePort
service/mcw-nginx-service exposed
[root@mcwk8s04 ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.2.0.1443/TCP 5d19h
mcw-nginx-service NodePort 10.2.0.25280:39719/TCP 11s
[root@mcwk8s04 ~]#
使用k8s,使用的是镜像。我们需要更新应用,就是换新的镜像。kubectl set可以替换镜像。它还有一些子命令 env Update environment variables on a pod template image Update image of a pod template resources 可以对资源,比如cpu等进行限制,Update resource requests/limits on objects with pod templates selector 修改标签,Set the selector on a resource serviceaccount Update ServiceAccount of a resource subject 角色绑定 。Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding
kubectl -h
kubectl set -h
kubectl set image -h
我们可以层层去看帮助信息,找到我们需要的命令。
比如我们就用下面的改改,
当我们请求网站的时候,响应头里面带了服务的版本信息
我们将nginx改为1.14版本的镜像
kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
[root@mcwk8s04 ~]# kubectl get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
mcw-nginx-deployment 3/333 3h54m
[root@mcwk8s04 ~]# kubectl rollout history deployment/mcw-nginx-deployment
deployment.extensions/mcw-nginx-deployment
REVISION CHANGE-CAUSE
12
[root@mcwk8s04 ~]#
回滚到上一个版本以及查看回滚的状态
[root@mcwk8s04 ~]# kubectl rollout undo deployment/mcw-nginx-deployment
deployment.extensions/mcw-nginx-deployment rolled back
[root@mcwk8s04 ~]# kubectl rollout status deployment/mcw-nginx-deployment
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 1out of 3new replicas have been updated...
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 1out of 3new replicas have been updated...
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 1out of 3new replicas have been updated...
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 2out of 3new replicas have been updated...
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 2out of 3new replicas have been updated...
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 2 old replicas are pending termination...
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "mcw-nginx-deployment" rollout to finish: 1 old replicas are pending termination...
deployment "mcw-nginx-deployment" successfully rolled out
[root@mcwk8s04 ~]# kubectl rollout status deployment/mcw-nginx-deployment
deployment "mcw-nginx-deployment" successfully rolled out
[root@mcwk8s04 ~]#
再刷新一下,页面上已经显示之前的那个版本了
删除资源
[root@mcwk8s04 ~]# kubectl get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
mcw-nginx-deployment 3/333 4h1m
[root@mcwk8s04 ~]# kubectl delete deploy mcw-nginx-deployment
deployment.extensions "mcw-nginx-deployment" deleted
[root@mcwk8s04 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
mcw-nginx-deployment-86466dbd78-8r5wr 0/1 Terminating 0 4m23s
[root@mcwk8s04 ~]# kubectl get pod
No resources found.
[root@mcwk8s04 ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.2.0.1443/TCP 5d22h
mcw-nginx-service NodePort 10.2.0.25280:39719/TCP 3h6m
[root@mcwk8s04 ~]# kubectl delete svc mcw-nginx-service
service "mcw-nginx-service" deleted
[root@mcwk8s04 ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.2.0.1443/TCP 5d22h
[root@mcwk8s04 ~]#
kubectl run --image=nginx my-deploy -o yaml --dry-run > my-deploy.yaml
• 用get命令导出
kubectl get my-deploy/nginx -o=yaml --export > my-deploy.yaml
• Pod容器的字段拼写忘记了
kubectl explain pods.spec.containers
用run命令生成 --dry-run生成配置文件
[root@mcwk8s03 demo]# kubectl run mcw-nginx-deployment --image=nginx --port=80 --replicas=3 --dry-run #执行部署的命令后面接--dry-run,不会进行部署,可以检查是否有语法错误
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.
deployment.apps/mcw-nginx-deployment created (dry run)
[root@mcwk8s03 demo]# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-deployment-7fd6966748-mxg8p 1/1 Running 0 36m
nginx-deployment-7fd6966748-pgfgq 1/1 Running 0 36m
nginx-deployment-7fd6966748-wsfj4 1/1 Running 0 36m
[root@mcwk8s03 demo]# kubectl get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-deployment 3/333 37m
[root@mcwk8s03 demo]#
[root@mcwk8s03 demo]# kubectl get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-deployment 3/333 51m
[root@mcwk8s03 demo]# kubectl get deploy/nginx-deployment --export -o yaml
Flag --export has been deprecated, This flag is deprecated and will be removed in future.
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: null
generation: 1
labels:
app: nginx
name: nginx-deployment
selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/nginx-deployment
spec:
progressDeadlineSeconds: 600
replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
creationTimestamp: null
labels:
app: nginx
spec:
containers:
- image: nginx:1.14.2
imagePullPolicy: IfNotPresent
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@mcwk8s03 demo]#
[root@mcwk8s03 demo]#
[root@mcwk8s03 demo]#
[root@mcwk8s03 demo]# kubectl get deploy/nginx-deployment --export -o=yaml
Flag --export has been deprecated, This flag is deprecated and will be removed in future.
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: null
generation: 1
labels:
app: nginx
name: nginx-deployment
selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/nginx-deployment
spec:
progressDeadlineSeconds: 600
replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
creationTimestamp: null
labels:
app: nginx
spec:
containers:
- image: nginx:1.14.2
imagePullPolicy: IfNotPresent
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@mcwk8s03 demo]# kubectl get deploy/nginx-deployment --export -o=yaml >myGet.yaml
Flag --export has been deprecated, This flag is deprecated and will be removed in future.
[root@mcwk8s03 demo]# head -3 myGet.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
[root@mcwk8s03 demo]#
Pod容器的字段拼写忘记了explain
比如我们忘了哪个字段是怎么拼写了可以像下面这样找到
[root@mcwk8s03 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 ifthisis 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 setin 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
如下,找元数据下的标签的一个过程
[root@mcwk8s03 demo]# head mcwTest.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
run: mcw-nginx-deployment
name: mcw-nginx-deployment
spec:
replicas: 3
selector:
[root@mcwk8s03 demo]# kubectl explain pods
KIND: Pod
VERSION: v1
DESCRIPTION:
Pod is a collection of containers that can run on a host. This resource is
created by clients and scheduled onto hosts.
FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representation of an
object. Servers should convert recognized schemas to the latest internal
value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
kind <string>
Kind is a string value representing the REST resource thisobject
represents. Servers may infer thisfrom the endpoint the client submits
requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
metadata
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
spec
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
status
Most recently observed status of the pod. This data may not be up to date.
Populated by the system. Read-only. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
[root@mcwk8s03 demo]# kubectl explain pods.metadata
KIND: Pod
VERSION: v1
RESOURCE: metadata
DESCRIPTION:
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
ObjectMeta is metadata that all persisted resources must have, which
includes all objects users must create.
FIELDS:
annotations
[root@mcwk8s03 demo]# kubectl create -f mcw-tomcat.yaml
service/tomcat-service created
Error from server (AlreadyExists): error when creating "mcw-tomcat.yaml": deployments.apps "tomcat-deployment" already exists
[root@mcwk8s03 demo]#
[root@mcwk8s03 demo]# kubectl apply -f mcw-tomcat.yaml
Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
deployment.apps/tomcat-deployment configured
Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
service/tomcat-service configured
[root@mcwk8s03 demo]#
我们看下,tomcat已经部署起来了。
[root@mcwk8s03 demo]# kubectl get deploy,pod,svc
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.extensions/nginx-deployment 3/333 47h
deployment.extensions/tomcat-deployment 3/333 7m6s
NAME READY STATUS RESTARTS AGE
pod/mcwpod 1/1 Running 3 24h
pod/nginx-deployment-7fd6966748-mxg8p 1/1 Running 2 47h
pod/nginx-deployment-7fd6966748-pgfgq 1/1 Running 2 47h
pod/nginx-deployment-7fd6966748-wsfj4 1/1 Running 2 47h
pod/tomcat-deployment-7bbd6dc5cf-9kvp6 1/1 Running 0 7m5s
pod/tomcat-deployment-7bbd6dc5cf-rvhhh 1/1 Running 0 7m5s
pod/tomcat-deployment-7bbd6dc5cf-svfvr 1/1 Running 0 7m5s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.2.0.1443/TCP 7d21h
service/nginx-service NodePort 10.2.0.24780:33851/TCP 47h
service/tomcat-service NodePort 10.2.0.3080:49516/TCP 3m6s
[root@mcwk8s03 demo]#
[root@mcwk8s05 harbor]# docker images 10.0.0.35/library/tomcat:v1
REPOSITORY TAG IMAGE ID CREATED SIZE
10.0.0.35/library/tomcat v1 3500a757f51d 4 days ago 473MB
[root@mcwk8s05 harbor]#
[root@mcwk8s05 harbor]# docker images 10.0.0.35/library/tomcat:v1 REPOSITORY TAG IMAGE ID CREATED SIZE 10.0.0.35/library/tomcat v1 3500a757f51d 4 days ago 473MB [root@mcwk8s05 harbor]# [root@mcwk8s05 harbor]# docker rmi 10.0.0.35/library/tomcat:v1 Untagged: 10.0.0.35/library/tomcat:v1 [root@mcwk8s05 harbor]# docker images 10.0.0.35/library/tomcat:v1 REPOSITORY TAG IMAGE ID CREATED SIZE [root@mcwk8s05 harbor]#
Warning Failed 4m17s (x4 over 5m39s) kubelet, mcwk8s05 Failed to pull image "10.0.0.35/library/tomcat:v1": rpc error: code = Unknown desc = Error response from daemon: pull access denied for 10.0.0.35/library/tomcat, repository does not exist or may require 'docker login': denied: requested access to the resource is denied Warning Failed 4m17s (x4 over 5m39s) kubelet, mcwk8s05 Error: ErrImagePull
[root@mcwk8s03 demo]# kubectl create -f registry-pull-secret.yaml
secret/registry-pull-secret created
[root@mcwk8s03 demo]# kubectl get secret
NAME TYPE DATA AGE
default-token-j9l4k kubernetes.io/service-account-token 3 4d23h
registry-pull-secret kubernetes.io/dockerconfigjson 1 9s
[root@mcwk8s03 demo]#