Kubectl基础命令

Kubectl 常用命令

help 帮助信息

# kubectl --help
kubectl controls the Kubernetes cluster manager.
 
Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/
 
Basic Commands (Beginner):
  create         Create a resource from a file or from stdin.
  expose         使用 replication controller, service, deployment 或者 pod 并暴露它作为一个新的Kubernetes Service
  run            在集群中运行一个指定的镜像
  set            为 objects 设置一个指定的特征
 
Basic Commands (Intermediate):
  explain        查看资源的文档
  get            显示一个或更多 resources
  edit           在服务器上编辑一个资源
  delete         Delete resources by filenames, stdin, resources and names, or by resources and label selector
 
Deploy Commands:
  rollout        Manage the rollout of a resource
  scale          为 Deployment, ReplicaSet, Replication Controller 或者 Job 设置一个新的副本数量
  autoscale      自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController 的副本数量
 
Cluster Management Commands:
  certificate    修改 certificate 资源.
  cluster-info   显示集群信息
  top            Display Resource (CPU/Memory/Storage) usage.
  cordon         标记 node 为 unschedulable
  uncordon       标记 node 为 schedulable
  drain          Drain node in preparation for maintenance
  taint          更新一个或者多个 node 上的 taints
 
Troubleshooting and Debugging Commands:
  describe       显示一个指定 resource 或者 group 的 resources 详情
  logs           输出容器在 pod 中的日志
  attach         Attach 到一个运行中的 container
  exec           在一个 container 中执行一个命令
  port-forward   Forward one or more local ports to a pod
  proxy          运行一个 proxy 到 Kubernetes API server
  cp             复制 files 和 directories 到 containers 和从容器中复制 files 和 directories.
  auth           Inspect authorization
 
Advanced Commands:
  diff           Diff live version against would-be applied version
  apply          通过文件名或标准输入流(stdin)对资源进行配置
  patch          使用 strategic merge patch 更新一个资源的 field(s)
  replace        通过 filename 或者 stdin替换一个资源
  wait           Experimental: Wait for a specific condition on one or many resources.
  convert        在不同的 API versions 转换配置文件
 
Settings Commands:
  label          更新在这个资源上的 labels
  annotate       更新一个资源的注解
  completion     Output shell completion code for the specified shell (bash or zsh)
 
Other Commands:
  api-resources  Print the supported API resources on the server
  api-versions   Print the supported API versions on the server, in the form of "group/version"
  config         修改 kubeconfig 文件
  plugin         Provides utilities for interacting with plugins.
  version        输出 client 和 server 的版本信息
 
Usage:
  kubectl [flags] [options]
 
Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands). 

kubect create

创建一个资源从一个文件或标准输入

kubectl create deployment nginx --image=nginx:1.14 
kubectl create -f my-nginx.yaml

kubectl run

在集群中运行一个指定的镜像,设置副本数5

kubectl run nginx --image=nginx:1.16 --port=80 --replicas 5

kubectl expose

nginx创建service,并通过Service的80端口转发至容器的8000端口上。

kubectl expose deployment/nginx  --type="NodePort" --port=80 --name=nginx

kubectl get

显示一个或更多resources

kubectl get cs                          # 查看集群状态
kubectl get nodes                       # 查看集群节点信息
kubectl get ns                          # 查看集群命名空间
kubectl get svc -n kube-system          # 查看指定命名空间的服务
kubectl get pod <pod-name> -o wide      # 查看Pod详细信息
kubectl get pod <pod-name> -o yaml      # 以yaml格式查看Pod详细信息
kubectl get pods                        # 查看资源对象,查看所有Pod列表
kubectl get rc,service                  # 查看资源对象,查看rc和service列表
kubectl get pod,svc,ep --show-labels    # 查看pod,svc,ep能及标签信息
kubectl get all --all-namespaces        # 查看所有的命名空间

kubectl delete

通过配置文件名、stdin、资源名称或label选择器来删除资源。

//删除所有pod
kubectl delete pods --all

//强制删除pod
kubectl delete pod --grace-period=0 --force

explain

//获取资源及其字段的文档
[root@master ~]# 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/sig-architecture/api-conventions.md#resources

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

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

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

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

edit

编辑资源

//设置label标签
[root@master ~]# kubectl edit deployment nginx
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2021-12-21T03:35:26Z"
  generation: 1
  labels:
    app: nginx
    name: aaa
......

//查看
[root@master ~]# kubectl describe deploy nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Tue, 21 Dec 2021 11:35:26 +0800
Labels:                 app=nginx
                        name=aaa		#已经添加
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=nginx
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-6799fc88d8 (1/1 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  21m   deployment-controller  Scaled up replica set nginx-6799fc88d8 to 1

scale

[root@master ~]# kubectl scale deployment/nginx --replicas 3
deployment.apps/nginx scaled
[root@master ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-c5lct   1/1     Running   0          12s
nginx-6799fc88d8-cxmwl   1/1     Running   0          12s
nginx-6799fc88d8-ggssg   1/1     Running   0          23m

//设置只需要一个,它会随机删除两个
[root@master ~]# kubectl scale deployment/nginx --replicas 1
deployment.apps/nginx scaled
[root@master ~]# kubectl get pod
NAME                     READY   STATUS        RESTARTS   AGE
nginx-6799fc88d8-c5lct   0/1     Terminating   0          52s
nginx-6799fc88d8-cxmwl   0/1     Terminating   0          52s
nginx-6799fc88d8-ggssg   1/1     Running       0          24m

autoscale

//最少三个,最多五个
[root@master ~]# kubectl autoscale deployment/nginx --min 3 --max=5
horizontalpodautoscaler.autoscaling/nginx autoscaled

//一个不满足设置的条件,它会自动创建两个满足最少三个
[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6799fc88d8-bzz45   0/1     ContainerCreating   0          1s
nginx-6799fc88d8-d8rtf   0/1     ContainerCreating   0          2s
nginx-6799fc88d8-ggssg   1/1     Running             0          26m

cluster-info

显示集群信息

[root@master ~]# kubectl cluster-info
Kubernetes control plane is running at https://192.168.172.142:6443
KubeDNS is running at https://192.168.172.142:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

describe

显示指定pod的详细信息

[root@master ~]# kubectl describe pod nginx
Name:         nginx-6799fc88d8-bzz45
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.172.153
Start Time:   Tue, 21 Dec 2021 12:02:12 +0800
Labels:       app=nginx
              pod-template-hash=6799fc88d8
Annotations:  <none>
Status:       Running
IP:           10.244.1.6
IPs:
  IP:           10.244.1.6
Controlled By:  ReplicaSet/nginx-6799fc88d8
Containers:
  nginx:
    Container ID:   docker://316e8d07bfdca9320883ba7e74027b20b7658d21366c92a7f95bb17e2aa418cb
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:d13dca1855de09e2fe392c58a66dd73d4ff4b71da4d1720bcf3f47b48c53ca1d
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Tue, 21 Dec 2021 12:02:20 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-29mxh (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-29mxh:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-29mxh
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  10m   default-scheduler  Successfully assigned default/nginx-6799fc88d8-bzz45 to node1.example.com
  Normal  Pulling    10m   kubelet            Pulling image "nginx"
  Normal  Pulled     10m   kubelet            Successfully pulled image "nginx" in 7.223539678s
  Normal  Created    10m   kubelet            Created container nginx
  Normal  Started    10m   kubelet            Started container nginx

logs

查看日志

[root@master ~]# kubectl logs deployment/nginx
Found 3 pods, using pod/nginx-6799fc88d8-ggssg
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/12/21 03:37:24 [notice] 1#1: using the "epoll" event method
2021/12/21 03:37:24 [notice] 1#1: nginx/1.21.4
2021/12/21 03:37:24 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2021/12/21 03:37:24 [notice] 1#1: OS: Linux 3.10.0-862.el7.x86_64
2021/12/21 03:37:24 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/21 03:37:24 [notice] 1#1: start worker processes
2021/12/21 03:37:24 [notice] 1#1: start worker process 31
2021/12/21 03:37:24 [notice] 1#1: start worker process 32

attach

[root@master ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-bzz45   1/1     Running   0          14m
nginx-6799fc88d8-d8rtf   1/1     Running   0          14m
nginx-6799fc88d8-ggssg   1/1     Running   0          40m
[root@master ~]# kubectl attach nginx-6799fc88d8-bzz45
Defaulting container name to nginx.
Use 'kubectl describe pod/nginx-6799fc88d8-bzz45 -n default' to see all of the containers in this pod.
If you don't see a command prompt, try pressing enter.

exec

执行容器命令,进入容器

[root@master ~]# kubectl exec nginx-6799fc88d8-bzz45 -- date
Tue Dec 21 04:18:13 UTC 2021

//进入容器里面执行命令
[root@master ~]# kubectl exec -it nginx-6799fc88d8-bzz45 -- /bin/bash
root@nginx-6799fc88d8-bzz45:/# ls
bin   docker-entrypoint.d   home   media  proc  sbin  tmp
boot  docker-entrypoint.sh  lib    mnt    root  srv   usr
dev   etc                   lib64  opt    run   sys   var
root@nginx-6799fc88d8-bzz45:/# date
Tue Dec 21 04:18:40 UTC 2021

prot-forward

端口转发

[root@master ~]# kubectl port-forward deployment/web 80
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80
Handling connection for 80

[root@master ~]# ss -antl
State      Recv-Q     Send-Q           Local Address:Port           Peer Address:Port     
LISTEN     0          128                  127.0.0.1:10248               0.0.0.0:*        
LISTEN     0          128                  127.0.0.1:10249               0.0.0.0:*        
LISTEN     0          128            192.168.172.142:2379                0.0.0.0:*        
LISTEN     0          128                  127.0.0.1:2379                0.0.0.0:*        
LISTEN     0          128            192.168.172.142:2380                0.0.0.0:*        
LISTEN     0          128                  127.0.0.1:2381                0.0.0.0:*        
LISTEN     0          128                  127.0.0.1:80                  0.0.0.0:*        
LISTEN     0          128                  127.0.0.1:10257               0.0.0.0:*        
LISTEN     0          128                  127.0.0.1:10259               0.0.0.0:*        
LISTEN     0          128                    0.0.0.0:22                  0.0.0.0:*        
LISTEN     0          128                  127.0.0.1:34813               0.0.0.0:*        
LISTEN     0          128                          *:10250                     *:*        
LISTEN     0          128                          *:6443                      *:*        
LISTEN     0          128                      [::1]:80                     [::]:*        
LISTEN     0          128                          *:10256                     *:*        
LISTEN     0          128                       [::]:22                     [::]:*        
[root@master ~]# curl 127.0.0.1
<html><body><h1>It works!</h1></body></html>


//允许所有IP访问
[root@master ~]# kubectl port-forward --address 0.0.0.0 deployment/web 80
Forwarding from 0.0.0.0:80 -> 80
Handling connection for 80

[root@master ~]# curl 192.168.172.142
<html><body><h1>It works!</h1></body></html>

cp

拷贝文件或目录到容器中,或者从容器内向外拷贝

[root@master ~]# kubectl cp anaconda-ks.cfg nginx-6799fc88d8-bzz45:/tmp/
[root@master ~]# kubectl exec nginx-6799fc88d8-bzz45 -- ls /tmp/
anaconda-ks.cfg

label

给资源设置、更新标签

[root@master ~]# kubectl run web --image httpd
pod/web created
[root@master ~]# kubectl describe pod web
Name:         web
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.172.153
Start Time:   Tue, 21 Dec 2021 12:30:48 +0800
Labels:       run=web
Annotations:  <none>
Status:       Running
IP:           10.244.1.8
IPs:
  IP:  10.244.1.8


//追加标签
[root@master ~]# kubectl label pods web app=test
pod/web labeled

[root@master ~]# kubectl describe pod web
Name:         web
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.172.153
Start Time:   Tue, 21 Dec 2021 12:30:48 +0800
Labels:       app=test
              run=web
Annotations:  <none>
Status:       Running
IP:           10.244.1.8
IPs:
  IP:  10.244.1.8


//更改标签
[root@master ~]# kubectl label --overwrite pods web app=aaa
pod/web labeled
[root@master ~]# kubectl describe pod web
Name:         web
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.172.153
Start Time:   Tue, 21 Dec 2021 12:30:48 +0800
Labels:       app=aaa
              run=web
Annotations:  <none>
Status:       Running
IP:           10.244.1.8
IPs:
  IP:  10.244.1.8

api-resources

查看所有资源

[root@master ~]# kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationController
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevision
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v1                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1beta1                          true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
endpointslices                                 discovery.k8s.io/v1beta1               true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
ingresses                         ing          extensions/v1beta1                     true         Ingress
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta1   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta1   false        PriorityLevelConfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1beta1                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy/v1beta1                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment

api-versions

API版本

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

version

[root@master ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:59:43Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:51:19Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}

滚动更新、回滚

用Dockerfile制作两个版本镜像

[root@master httpd]# cd
[root@master httpd]# vim Dockerfile
FROM busybox

RUN mkdir  /data && \
    echo "test page on jjyy" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]


[root@master ~]# docker build -t httpd:v0.1 httpd/
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
latest: Pulling from library/busybox
3cb635b06aa2: Pull complete 
Digest: sha256:b5cfd4befc119a590ca1a81d6bb0fa1fb19f1fbebd0397f25fae164abe1e8a6a
Status: Downloaded newer image for busybox:latest
 ---> ffe9d497c324
Step 2/3 : RUN mkdir  /data &&     echo "test page on jjyy" > /data/index.html
 ---> Running in a2570ee76392
Removing intermediate container a2570ee76392
 ---> b3a39a7c5523
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in b45bae5f1bcb
Removing intermediate container b45bae5f1bcb
 ---> e550687cd0fa
Successfully built e550687cd0fa
Successfully tagged httpd:v0.1


[root@master ~]# cat httpd/Dockerfile 
FROM busybox

RUN mkdir  /data && \
    echo "test page on tom" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]

[root@master ~]# docker build -t httpd:v0.2 httpd/
Sending build context to Docker daemon  2.048kB
Error response from daemon: dockerfile parse error line 1: unknown instruction: M
[root@master ~]# vim httpd/Dockerfile 
[root@master ~]# docker build -t httpd:v0.2 httpd/
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> ffe9d497c324
Step 2/3 : RUN mkdir  /data &&     echo "test page on tom" > /data/index.html
 ---> Running in 5f4a401c28da
Removing intermediate container 5f4a401c28da
 ---> 3e594480ee7a
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in 74294b76b72c
Removing intermediate container 74294b76b72c
 ---> 69bceebf8f0c
Successfully built 69bceebf8f0c
Successfully tagged httpd:v0.2

滚动更新、回滚

//用k8s运行镜像
[root@master ~]# kubectl create deploy httpd --image 1968046xux/httpd:v0.1 --replicas 3
deployment.apps/httpd created

[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
httpd-7fd5bf7f4f-bkz94    1/1     Running       0          50s
httpd-7fd5bf7f4f-dqz28    1/1     Running       0          50s
httpd-7fd5bf7f4f-wgsgn    1/1     Running       0          50s

#暴露端口号
[root@master ~]# kubectl expose deploy httpd --port 80 --type NodePort 
service/httpd exposed

#访问
[root@master ~]# curl 10.103.211.67
test page on jjyy



//更新
[root@master ~]# kubectl set image deploy/httpd httpd=1968046xux/httpd:v0.2
deployment.apps/httpd image updated

[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
httpd-8cu7ft6w7-awdnd    1/1     ContainerCreating             0          3s
httpd-9b8f648df-4fl48    1/1     Running             0          6m59s
httpd-9b8f648df-j85cp    1/1     Running             0          6m59s
httpd-9b8f648df-nftfn    1/1     Running             0          6m59s

#已经更新了
[root@master ~]# kubectl get pod
NAME                     READY   STATUS        RESTARTS   AGE
httpd-8cu7ft6w7-awdnd    1/1     Running             0          6m59s
httpd-8cu7ft6w7-3b33b    1/1     Running             0          6m59s
httpd-8cu7ft6w7-nx38v    1/1     Running             0          6m59s
#访问
[root@master ~]# curl 10.103.211.67
test page on tom




//回滚(来回滚)
[root@master ~]# kubectl rollout undo deploy/httpd 
deployment.apps/httpd rolled back

[root@master ~]# kubectl get pod
NAME                     READY   STATUS        RESTARTS   AGE
httpd-9b8f648df-wx4wr    1/1     Running       0          30s
httpd-9b8f648df-v55by    1/1     Running       0          27s
httpd-9b8f648df-fc3c4    1/1     Running       0          60s

[root@master ~]# curl 10.103.211.67
test page on jjyy

//回滚到上一个版本
[root@master ~]# kubectl rollout undo deploy/httpd 
deployment.apps/httpd rolled back
[root@master ~]# curl 10.103.211.67
test page on tom
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值