kubernetes入门_Kubernetes入门:一个kubectl速查表_cukw6666的博客-程序员秘密

技术标签: kubernetes  python  java  linux  docker  

kubernetes入门

介绍 (Introduction)

Kubectl is a command-line tool designed to manage Kubernetes objects and clusters. It provides a command-line interface for performing common operations like creating and scaling Deployments, switching contexts, and accessing a shell in a running container.

Kubectl是旨在管理Kubernetes对象和集群的命令行工具。 它提供了一个命令行界面,用于执行常见的操作,例如创建和扩展部署,切换上下文以及访问正在运行的容器中的Shell。

How to Use This Guide:

如何使用本指南:

  • This guide is in cheat sheet format with self-contained command-line snippets.

    本指南采用备忘单格式,包含独立的命令行摘要。
  • It is not an exhaustive list of kubectl commands, but contains many common operations and use cases. For a more thorough reference, consult the Kubectl Reference Docs

    它不是kubectl命令的详尽列表,但包含许多常见的操作和用例。 有关更全面的参考,请查阅Kubectl参考文档

  • Jump to any section that is relevant to the task you are trying to complete.

    跳至与您要完成的任务有关的任何部分。

先决条件 (Prerequisites)

样本部署 (Sample Deployment)

To demonstrate some of the operations and commands in this cheat sheet, we’ll use a sample Deployment that runs 2 replicas of Nginx:

为了演示该备忘单中的某些操作和命令,我们将使用运行两个Nginx副本的示例Deployment:

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

Copy and paste this manifest into a file called nginx-deployment.yaml.

将此清单复制并粘贴到名为nginx-deployment.yaml的文件中。

安装kubectl (Installing kubectl)

Note: These commands have only been tested on an Ubuntu 18.04 machine. To learn how to install kubectl on other operating systems, consult Install and Set Up kubectl from the Kubernetes docs.

注意:这些命令仅在Ubuntu 18.04计算机上经过测试。 要了解如何在其他操作系统上安装kubectl,请参阅Kubernetes文档中的“ 安装并设置kubectl ”。

First, update your local package index and install required dependencies:

首先,更新本地软件包索引并安装所需的依赖项:

  • sudo apt-get update && sudo apt-get install -y apt-transport-https

    sudo apt-get更新&& sudo apt-get安装-y apt-transport-https

Then add the Google Cloud GPG key to APT and make the kubectl package available to your system:

然后将Google Cloud GPG密钥添加到APT,并使kubectl软件包可用于您的系统:

  • curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

    curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt键添加-
  • echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list

    回声“ deb https://apt.kubernetes.io/ kubernetes-xenial main” | sudo tee -a /etc/apt/sources.list.d/kubernetes.list
  • sudo apt-get update

    sudo apt-get更新

Finally, install kubectl:

最后,安装kubectl:

  • sudo apt-get install -y kubectl

    须藤apt-get install -y kubectl

Test that the installation succeeded using version:

使用version测试安装是否成功:

  • kubectl version

    kubectl版本

设置Shell自动补全 (Setting Up Shell Autocompletion)

Note: These commands have only been tested on an Ubuntu 18.04 machine. To learn how to set up autocompletion on other operating systems, consult Install and Set Up kubectl from the Kubernetes docs.

注意:这些命令仅在Ubuntu 18.04计算机上经过测试。 要了解如何在其他操作系统上设置自动完成功能,请参阅Kubernetes文档中的Install and Set up kubectl

kubectl includes a shell autocompletion script that you can make available to your system’s existing shell autocompletion software.

kubectl包含一个shell自动完成脚本,您可以将其提供给系统现有的shell自动完成软件。

安装kubectl自动完成 (Installing kubectl Autocompletion)

First, check if you have bash-completion installed:

首先,检查您是否安装了bash-completion

  • type _init_completion

    输入_init_completion

You should see some script output.

您应该看到一些脚本输出。

Next, source the kubectl autocompletion script in your ~/.bashrc file:

接下来, source的kubectl自动完成脚本在你~/.bashrc文件:

  • echo 'source <(kubectl completion bash)' >>~/.bashrc

    回声'源<(kubectl完成bash)'>>〜/ .bashrc
  • . ~/.bashrc

    。 〜/ .bashrc

Alternatively, you can add the completion script to the /etc/bash_completion.d directory:

或者 ,您可以将完成脚本添加到/etc/bash_completion.d目录:

  • kubectl completion bash >/etc/bash_completion.d/kubectl

    kubectl完成bash> /etc/bash_completion.d/kubectl

用法 (Usage)

To use the autocompletion feature, press the TAB key to display available kubectl commands:

要使用自动完成功能,请按TAB键以显示可用的kubectl命令:

  • kubectl TAB TAB

    kubectl标签

   
    
Output
annotate apply autoscale completion cordon delete drain explain kustomize options port-forward rollout set uncordon api-resources attach certificate config cp describe . . .

You can also display available commands after partially typing a command:

您还可以在部分键入命令后显示可用命令:

  • kubectl d TAB

    标签库

   
    
Output
delete describe diff drain

连接,配置和使用上下文 (Connecting, Configuring and Using Contexts)

连接中 (Connecting)

To test that kubectl can authenticate with and access your Kubernetes cluster, use cluster-info:

要测试kubectl可以通过身份验证并访问您的Kubernetes集群,请使用cluster-info

  • kubectl cluster-info

    kubectl集群信息

If kubectl can successfully authenticate with your cluster, you should see the following output:

如果kubectl可以成功地对集群进行身份验证,则应该看到以下输出:


   
    
Output
Kubernetes master is running at https://kubernetes_master_endpoint CoreDNS is running at https://coredns_endpoint To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

kubectl is configured using kubeconfig configuration files. By default, kubectl will look for a file called config in the $HOME/.kube directory. To change this, you can set the $KUBECONFIG environment variable to a custom kubeconfig file, or pass in the custom file at execution time using the --kubeconfig flag:

使用kubeconfig配置文件配置kubectl 。 默认情况下,kubectl将在$HOME/.kube目录中查找名为config的文件。 要更改此设置,可以将$KUBECONFIG环境变量设置为自定义kubeconfig文件,或者在执行时使用--kubeconfig标志传入自定义文件:

  • kubectl cluster-info --kubeconfig=path_to_your_kubeconfig_file

    kubectl群集信息--kubeconfig = path_to_your_kubeconfig_file

Note: If you’re using a managed Kubernetes cluster, your cloud provider should have made its kubeconfig file available to you.

注意:如果您使用的是托管Kubernetes集群,则您的云提供商应已将其kubeconfig文件提供给您。

If you don’t want to use the --kubeconfig flag with every command, and there is no existing ~/.kube/config file, create a directory called ~/.kube in your home directory if it doesn’t already exist, and copy in the kubeconfig file, renaming it to config:

如果您不想在每个命令中都使用--kubeconfig标志, 并且不存在~/.kube/config文件~/.kube在主目录中创建一个名为~/.kube的目录(如果尚不存在),并复制到kubeconfig文件中,将其重命名为config

  • mkdir ~/.kube

    mkdir〜/ .kube
  • cp your_kubeconfig_file ~/.kube/config

    cp your_kubeconfig_file〜 / .kube / config

Now, run cluster-info once again to test your connection.

现在,再次运行cluster-info以测试您的连接。

修改您的kubectl配置 (Modifying your kubectl Configuration)

You can also modify your config using the kubectl config set of commands.

您还可以使用kubectl config命令集来修改配置。

To view your kubectl configuration, use the view subcommand:

要查看您的kubectl配置,请使用view子命令:

  • kubectl config view

    kubectl配置视图

   
    
Output
apiVersion: v1 clusters: - cluster: certificate-authority-data: DATA+OMITTED . . .

Modifying Clusters

修改集群

To fetch a list of clusters defined in your kubeconfig, use get-clusters:

要获取在kubeconfig中定义的集群列表,请使用get-clusters

  • kubectl config get-clusters

    kubectl配置get-clusters

   
    
Output
NAME do-nyc1-sammy

To add a cluster to your config, use the set-cluster subcommand:

要将集群添加到配置中,请使用set-cluster子命令:

  • kubectl config set-cluster new_cluster --server=server_address --certificate-authority=path_to_certificate_authority

    kubectl config set-cluster new_cluster --server = server_address --certificate-authority = path_to_certificate_authority

To delete a cluster from your config, use delete-cluster:

要从配置中删除集群,请使用delete-cluster

Note: This only deletes the cluster from your config and does not delete the actual Kubernetes cluster.

注意:这只会从您的配置中删除集群,而不会删除实际的Kubernetes集群。

  • kubectl config delete-cluster

    kubectl配置删除集群

Modifying Users

修改用户

You can perform similar operations for users using set-credentials:

您可以使用set-credentials为用户执行类似的操作:

  • kubectl config set-credentials username --client-certificate=/path/to/cert/file --client-key=/path/to/key/file

    kubectl配置设置凭据用户名 --client-certificate = / path / to / cert / file --client-key = / path / to / key / file

To delete a user from your config, you can run unset:

要从配置中删除用户,可以运行unset

  • kubectl config unset users.username

    kubectl config取消设置用户。 用户名

Contexts

语境

A context in Kubernetes is an object that contains a set of access parameters for your cluster. It consists of a cluster, namespace, and user triple. Contexts allow you to quickly switch between different sets of cluster configuration.

Kubernetes中的上下文是一个对象,其中包含集群的一组访问参数。 它由一个clusternamespaceuser Triple组成。 上下文使您可以在不同的集群配置集之间快速切换。

To see your current context, you can use current-context:

要查看当前上下文,可以使用current-context

  • kubectl config current-context

    Kubectl配置当前上下文

   
    
Output
do-nyc1-sammy

To see a list of all configured contexts, run get-contexts:

要查看所有已配置上下文的列表,请运行get-contexts

  • kubectl config get-contexts

    kubectl配置获取上下文

   
    
Output
CURRENT NAME CLUSTER AUTHINFO NAMESPACE * do-nyc1-sammy do-nyc1-sammy do-nyc1-sammy-admin

To set a context, use set-context:

要设置上下文,请使用set-context

  • kubectl config set-context context_name --cluster=cluster_name --user=user_name --namespace=namespace

    kubectl config set-context context_name --cluster = cluster_name --user = user_name --namespace = 名称空间

You can switch between contexts with use-context:

您可以use-context在上下文之间切换:

  • kubectl config use-context context_name

    kubectl配置使用上下文context_name


   
    
Output
Switched to context "do-nyc1-sammy"

And you can delete a context with delete-context:

您可以使用delete-context

  • kubectl config delete-context context_name

    kubectl配置删除上下文context_name

使用命名空间 (Using Namespaces)

A Namespace in Kubernetes is an abstraction that allows you to subdivide your cluster into multiple virtual clusters. By using Namespaces you can divide cluster resources among multiple teams and scope objects appropriately. For example, you can have a prod Namespace for production workloads, and a dev Namespace for development and test workloads.

Kubernetes中的命名空间是一种抽象,它允许您将集群细分为多个虚拟集群 。 通过使用命名空间,您可以在多个团队和范围对象之间适当地分配群集资源。 例如,您可以具有用于生产工作负载的prod命名空间,以及用于开发和测试工作负载的dev命名空间。

To fetch and print a list of all the Namespaces in your cluster, use get namespace:

要获取并打印集群中所有命名空间的列表,请使用get namespace

  • kubectl get namespace

    kubectl获取名称空间

   
    
Output
NAME STATUS AGE default Active 2d21h kube-node-lease Active 2d21h kube-public Active 2d21h kube-system Active 2d21h

To set a Namespace for your current context, use set-context --current:

要为您的当前上下文设置命名空间,请使用set-context --current

  • kubectl config set-context --current --namespace=namespace_name

    kubectl config set-context --current --namespace = namespace_name

To create a Namespace, use create namespace:

要创建名称空间,请使用create namespace

  • kubectl create namespace namespace_name

    kubectl创建名称空间namespace_name


   
    
Output
namespace/sammy created

Similarly, to delete a Namespace, use delete namespace:

同样,要删除命名空间,请使用delete namespace

Warning: Deleting a Namespace will delete everything in the Namespace, including running Deployments, Pods, and other workloads. Only run this command if you’re sure you’d like to kill whatever’s running in the Namespace or if you’re deleting an empty Namespace.

警告:删除名称空间将删除名称空间中的所有内容 ,包括正在运行的Deployment,Pod和其他工作负载。 仅在确定要杀死名称空间中正在运行的内容或要删除空的名称空间时,才运行此命令。

  • kubectl delete namespace namespace_name

    kubectl删除命名空间namespace_name

To fetch all Pods in a given Namespace or to perform other operations on resources in a given Namespace, make sure to include the --namespace flag:

要获取给定命名空间中的所有Pod或对给定命名空间中的资源执行其他操作,请确保包括--namespace标志:

  • kubectl get pods --namespace=namespace_name

    kubectl获取容器--namespace = namespace_name

管理Kubernetes资源 (Managing Kubernetes Resources)

一般语法 (General Syntax)

The general syntax for most kubectl management commands is:

大多数kubectl管理命令的通用语法为:

  • kubectl command type name flags

    kubectl命令类型名称标志

Where

哪里

  • command is an operation you’d like to perform, like create

    command是您要执行的操作,例如create

  • type is the Kubernetes resource type, like deployment

    type是Kubernetes资源类型,例如deployment

  • name is the resource’s name, like app_frontend

    name是资源的名称,例如app_frontend

  • flags are any optional flags you’d like to include

    flags是您要包含的任何可选标志

For example the following command retrieves information about a Deployment named app_frontend:

例如,以下命令检索有关名为app_frontend的部署的信息:

  • kubectl get deployment app_frontend

    kubectl获取部署app_frontend

声明式管理和kubectl apply (Declarative Management and kubectl apply)

The recommended approach to managing workloads on Kubernetes is to rely on the cluster’s declarative design as much as possible. This means that instead of running a series of commands to create, update, delete, and restart running Pods, you should define the workloads, services, and systems you’d like to run in YAML manifest files, and provide these files to Kubernetes, which will handle the rest.

在Kubernetes上管理工作负载的推荐方法是尽可能多地依赖集群的声明性设计。 这意味着,您应该在YAML清单文件中定义要运行的工作负载,服务和系统,而不是运行一系列命令来创建,更新,删除和重新启动运行中的Pod,然后将这些文件提供给Kubernetes,这将处理其余的。

In practice, this means using the kubectl apply command, which applies a particular configuration to a given resource. If the target resource doesn’t exist, then Kubernetes will create the resource. If the resource already exists, then Kubernetes will save the current revision, and update the resource according to the new configuration. This declarative approach exists in contrast to the imperative approach of running the kubectl create , kubectl edit, and the kubectl scale set of commands to manage resources. To learn more about the different ways of managing Kubernetes resources, consult Kubernetes Object Management from the Kubernetes docs.

实际上,这意味着使用kubectl apply命令,该命令将特定配置应用于给定资源。 如果目标资源不存在,那么Kubernetes将创建该资源。 如果资源已经存在,那么Kubernetes将保存当前修订,并根据新配置更新资源。 与运行kubectl createkubectl editkubectl scale的命令集以管理资源的命令方法相比,存在这种声明性方法。 要了解有关管理Kubernetes资源的不同方式的更多信息,请参阅Kubernetes文档中的Kubernetes对象管理

Rolling out a Deployment

展开部署

For example, to deploy the sample Nginx Deployment to your cluster, use apply and provide the path to the nginx-deployment.yaml manifest file:

例如,要将示例Nginx部署部署到您的集群,请使用apply并提供nginx-deployment.yaml清单文件的路径:

  • kubectl apply -f nginx-deployment.yaml

    kubectl套用-f nginx-deployment.yaml

   
    
Output
deployment.apps/nginx-deployment created

The -f flag is used to specify a filename or URL containing a valid configuration. If you’d like to apply all manifests from a directory, you can use the -k flag:

-f标志用于指定包含有效配置的文件名或URL。 如果要apply目录中的所有清单,可以使用-k标志:

  • kubectl apply -k manifests_dir

    kubectl套用-k manifests_dir

You can track the rollout status using rollout status:

您可以使用rollout status来跟踪rollout status

  • kubectl rollout status deployment/nginx-deployment

    kubectl推出状态部署/ nginx部署

   
    
Output
Waiting for deployment "nginx-deployment" rollout to finish: 1 of 2 updated replicas are available... deployment "nginx-deployment" successfully rolled out

An alternative to rollout status is the kubectl get command, along with the -w (watch) flag:

rollout status的替代方法是kubectl get命令以及-w (监视)标志:

  • kubectl get deployment -w

    kubectl进行部署-w

   
    
Output
NAME READY UP-TO-DATE AVAILABLE AGE nginx-deployment 0/2 2 0 3s nginx-deployment 1/2 2 1 3s nginx-deployment 2/2 2 2 3s

Using rollout pause and rollout resume, you can pause and resume the rollout of a Deployment:

使用rollout pauserollout resume ,您可以暂停和恢复部署的推出:

  • kubectl rollout pause deployment/nginx-deployment

    kubectl推出暂停部署/ nginx部署

   
    
Output
deployment.extensions/nginx-deployment paused
  • kubectl rollout resume deployment/nginx-deployment

    kubectl推出恢复部署/ nginx部署

   
    
Output
deployment.extensions/nginx-deployment resumed

Modifying a Running Deployment

修改正在运行的部署

If you’d like to modify a running Deployment, you can make changes to its manifest file and then run kubectl apply again to apply the update. For example, we’ll modify the nginx-deployment.yaml file to change the number of replicas from 2 to 3:

如果要修改正在运行的Deployment,可以对其清单文件进行更改,然后再次运行kubectl apply以应用更新。 例如,我们将修改nginx-deployment.yaml文件,以将副本数从2更改为3

nginx-deployment.yaml
nginx-deployment.yaml
. . .
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
. . .

The kubectl diff command allows you to see a diff between currently running resources, and the changes proposed in the supplied configuration file:

kubectl diff命令使您可以查看当前正在运行的资源与提供的配置文件中建议的更改之间的区别:

  • kubectl diff -f nginx-deployment.yaml

    kubectl diff -f nginx-deployment.yaml

Now allow Kubernetes to perform the update using apply:

现在允许Kubernetes使用apply执行更新:

  • kubectl apply -f nginx-deployment.yaml

    kubectl套用-f nginx-deployment.yaml

Running another get deployment should confirm the addition of a third replica.

运行另一个get deployment应确认添加了第三个副本。

If you run apply again without modifying the manifest file, Kubernetes will detect that no changes were made and won’t perform any action.

如果再次运行apply而未修改清单文件,Kubernetes将检测到未进行任何更改,并且将不执行任何操作。

Using rollout history you can see a list of the Deployment’s previous revisions:

使用rollout history您可以看到部署的先前版本的列表:

  • kubectl rollout history deployment/nginx-deployment

    kubectl推出历史记录部署/ nginx部署

   
    
Output
deployment.extensions/nginx-deployment REVISION CHANGE-CAUSE 1 <none>

With rollout undo, you can revert a Deployment to any of its previous revisions:

使用rollout undo ,您可以将Deployment还原到其以前的任何版本:

  • kubectl rollout undo deployment/nginx-deployment --to-revision=1

    kubectl部署撤消部署/ nginx部署--to-revision = 1

Deleting a Deployment

删除部署

To delete a running Deployment, use kubectl delete:

要删除正在运行的Deployment,请使用kubectl delete

  • kubectl delete -f nginx-deployment.yaml

    kubectl删除-f nginx-deployment.yaml

   
    
Output
deployment.apps "nginx-deployment" deleted

当务之急 (Imperative Management)

You can also use a set of imperative commands to directly manipulate and manage Kubernetes resources.

您还可以使用一组命令性命令直接操作和管理Kubernetes资源。

Creating a Deployment

创建部署

Use create to create an object from a file, URL, or STDIN. Note that unlike apply, if an object with the same name already exists, the operation will fail. The --dry-run flag allows you to preview the result of the operation without actually performing it:

使用create从文件,URL或STDIN创建对象。 请注意,与apply不同,如果已经存在相同名称的对象,则该操作将失败。 --dry-run标志使您可以预览操作结果,而无需实际执行:

  • kubectl create -f nginx-deployment.yaml --dry-run

    kubectl创建-f nginx-deployment.yaml --dry-run

   
    
Output
deployment.apps/nginx-deployment created (dry-run)

We can now create the object:

现在我们可以创建对象:

  • kubectl create -f nginx-deployment.yaml

    kubectl创建-f nginx-deployment.yaml

   
    
Output
deployment.apps/nginx-deployment created

Modifying a Running Deployment

修改运行中的部署

Use scale to scale the number of replicas for the Deployment from 2 to 4:

使用scale将Deployment的副本数量从2缩放到4:

  • kubectl scale --replicas=4 deployment/nginx-deployment

    kubectl规模--replicas = 4部署/ nginx部署

   
    
Output
deployment.extensions/nginx-deployment scaled

You can edit any object in-place using kubectl edit. This will open up the object’s manifest in your default editor:

您可以使用kubectl edit就地编辑任何对象。 这将在默认编辑器中打开对象的清单:

  • kubectl edit deployment/nginx-deployment

    kubectl编辑部署/ nginx部署

You should see the following manifest file in your editor:

您应该在编辑器中看到以下清单文件:

nginx-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: extensions/v1beta1
kind: Deployment
. . . 
spec:
  progressDeadlineSeconds: 600
  replicas: 4
  revisionHistoryLimit: 10
  selector:
    matchLabels:
. . .

Change the replicas value from 4 to 2, then save and close the file.

replicas值从4更改为2 ,然后保存并关闭文件。

Now run a get to inspect the changes:

现在运行get检查更改:

  • kubectl get deployment/nginx-deployment

    kubectl进行部署/ nginx部署

   
    
Output
NAME READY UP-TO-DATE AVAILABLE AGE nginx-deployment 2/2 2 2 6m40s

We’ve successfully scaled the Deployment back down to 2 replicas on-the-fly. You can update most of a Kubernetes’ object’s fields in a similar manner.

我们已经成功地将“部署”即时缩减为2个副本。 您可以用类似的方式更新Kubernetes对象的大多数字段。

Another useful command for modifying objects in-place is kubectl patch. Using patch, you can update an object’s fields on-the-fly without having to open up your editor. patch also allows for more complex updates with various merging and patching strategies. To learn more about these, consult Update API Objects in Place Using kubectl patch.

另一个用于就地修改对象的有用命令是kubectl patch 。 使用patch ,您可以即时更新对象的字段,而无需打开编辑器。 patch还允许使用各种合并和修补策略进行更复杂的更新。 要了解有关这些内容的更多信息,请参阅使用kubectl补丁就地更新API对象

The following command will patch the nginx-deployment object to update the replicas field from 2 to 4; deploy is shorthand for the deployment object.

以下命令将修补nginx-deployment对象,以将replicas字段从2更新为4deploydeployment对象的简写。

  • kubectl patch deploy nginx-deployment -p '{"spec": {"replicas": 4}}'

    kubectl补丁部署nginx-deployment -p'{“ spec”:{“ replicas”:4}}'

   
    
Output
deployment.extensions/nginx-deployment patched

We can now inspect the changes:

现在,我们可以检查更改:

  • kubectl get deployment/nginx-deployment

    kubectl进行部署/ nginx部署

   
    
Output
NAME READY UP-TO-DATE AVAILABLE AGE nginx-deployment 4/4 4 4 18m

You can also create a Deployment imperatively using the run command. run will create a Deployment using an image provided as a parameter:

您也可以使用run命令命令性地创建Deployment。 run将使用作为参数提供的映像创建一个Deployment:

  • kubectl run nginx-deployment --image=nginx --port=80 --replicas=2

    kubectl运行nginx部署--image = nginx --port = 80 --replicas = 2

The expose command lets you quickly expose a running Deployment with a Kubernetes Service, allowing connections from outside your Kubernetes cluster:

expose的命令可以让你快速暴露正在运行的部署与Kubernetes服务,让您Kubernetes群集外部连接:

  • kubectl expose deploy nginx-deployment --type=LoadBalancer --port=80 --name=nginx-svc

    kubectl公开部署nginx-deployment --type = LoadBalancer --port = 80 --name = nginx-svc

   
    
Output
service/nginx-svc exposed

Here we’ve exposed the nginx-deployment Deployment as a LoadBalancer Service, opening up port 80 to external traffic and directing it to container port 80. We name the service nginx-svc. Using the LoadBalancer Service type, a cloud load balancer is automatically provisioned and configured by Kubernetes. To get the Service’s external IP address, use get:

在这里,我们将nginx-deployment部署作为LoadBalancer服务公开,将端口80开放给外部流量,并将其定向到容器端口80 。 我们将服务命名为nginx-svc 。 使用LoadBalancer服务类型,Kubernetes会自动设置和配置云负载平衡器。 要获取服务的外部IP地址,请使用get

  • kubectl get svc nginx-svc

    kubectl获取svc nginx-svc

   
    
Output
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-svc LoadBalancer 10.245.26.242 203.0.113.0 80:30153/TCP 22m

You can access the running Nginx containers by navigating to EXTERNAL-IP in your web browser.

您可以通过在Web浏览器中导航到EXTERNAL-IP来访问正在运行的Nginx容器。

检查工作量和调试 (Inspecting Workloads and Debugging)

There are several commands you can use to get more information about workloads running in your cluster.

您可以使用几个命令来获取有关集群中运行的工作负载的更多信息。

Inspecting Kubernetes Resources

检查Kubernetes资源

kubectl get fetches a given Kubernetes resource and displays some basic information associated with it:

kubectl get获取给定的Kubernetes资源并显示与其相关的一些基本信息:

  • kubectl get deployment -o wide

    kubectl进行部署-o宽

   
    
Output
NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR nginx-deployment 4/4 4 4 29m nginx nginx app=nginx

Since we did not provide a Deployment name or Namespace, kubectl fetches all Deployments in the current Namespace. The -o flag provides additional information like CONTAINERS and IMAGES.

由于我们没有提供部署名称或命名空间,因此kubectl会获取当前命名空间中的所有部署。 -o标志提供其他信息,例如CONTAINERSIMAGES

In addition to get, you can use describe to fetch a detailed description of the resource and associated resources:

除了get ,您还可以使用describe来获取资源和相关资源的详细描述:

  • kubectl describe deploy nginx-deployment

    kubectl描述部署nginx部署

   
    
Output
Name: nginx-deployment Namespace: default CreationTimestamp: Wed, 11 Sep 2019 12:53:42 -0400 Labels: run=nginx-deployment Annotations: deployment.kubernetes.io/revision: 1 Selector: run=nginx-deployment . . .

The set of information presented will vary depending on the resource type. You can also use this command without specifying a resource name, in which case information will be provided for all resources of that type in the current Namespace.

呈现的信息集将根据资源类型而有所不同。 您也可以在不指定资源名称的情况下使用此命令,在这种情况下,将为当前命名空间中该类型的所有资源提供信息。

explain allows you to quickly pull configurable fields for a given resource type:

explain使您可以快速提取给定资源类型的可配置字段:

  • kubectl explain deployment.spec

    kubectl解释deploy.spec

By appending additional fields you can dive deeper into the field hierarchy:

通过附加其他字段,您可以更深入地研究字段层次结构:

  • kubectl explain deployment.spec.template.spec

    kubectl解释deployment.spec.template.spec

Gaining Shell Access to a Container

使Shell访问容器

To gain shell access into a running container, use exec. First, find the Pod that contains the running container you’d like access to:

要获得对正在运行的容器的Shell访问,请使用exec 。 首先,找到包含您要访问的运行容器的Pod:

  • kubectl get pod

    kubectl获取广告连播

   
    
Output
nginx-deployment-8859878f8-7gfw9 1/1 Running 0 109m nginx-deployment-8859878f8-z7f9q 1/1 Running 0 109m

Let’s exec into the first Pod. Since this Pod has only one container, we don’t need to use the -c flag to specify which container we’d like to exec into.

让我们exec到第一个Pod。 由于此Pod只有一个容器,因此我们不需要使用-c标志来指定要exec容器。

  • kubectl exec -i -t nginx-deployment-8859878f8-7gfw9 -- /bin/bash

    kubectl exec -i -t nginx-deployment-8859878f8-7gfw9-/ bin / bash

   
    
Output
[email protected]:/#

You now have shell access to the Nginx container. The -i flag passes STDIN to the container, and -t gives you an interactive TTY. The -- double-dash acts as a separator for the kubectl command and the command you’d like to run inside the container. In this case, we are running /bin/bash.

现在,您具有对Nginx容器的shell访问权限。 -i标志将STDIN传递到容器, -t给您交互式TTY。 --双破折号用作kubectl命令和您要在容器内运行的命令的分隔符。 在这种情况下,我们正在运行/bin/bash

To run commands inside the container without opening a full shell, omit the -i and -t flags, and substitute the command you’d like to run instead of /bin/bash:

要在容器中运行命令而不打开完整的外壳,请省略-i-t标志,并用您要运行的命令代替/bin/bash

  • kubectl exec nginx-deployment-8859878f8-7gfw9 ls

    kubectl执行程序nginx-deployment-8859878f8-7gfw9 ls

   
    
Output
bin boot dev etc home lib lib64 media . . .

Fetching Logs

提取日志

Another useful command is logs, which prints logs for Pods and containers, including terminated containers.

另一个有用的命令是logs ,它打印Pod和容器(包括终止的容器)的日志。

To stream logs to your terminal output, you can use the -f flag:

要将日志流传输到终端输出,可以使用-f标志:

  • kubectl logs -f nginx-deployment-8859878f8-7gfw9

    kubectl日志-f nginx-deployment-8859878f8-7gfw9

   
    
Output
10.244.2.1 - - [12/Sep/2019:17:21:33 +0000] "GET / HTTP/1.1" 200 612 "-" "203.0.113.0" "-" 2019/09/16 17:21:34 [error] 6#6: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 10.244.2.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "203.0.113.0", referrer: "http://203.0.113.0" . . .

This command will keep running in your terminal until interrupted with a CTRL+C. You can omit the -f flag if you’d like to print log output and exit immediately.

该命令将一直在您的终端中运行,直到被CTRL+C中断为止。 如果要打印日志输出并立即退出,可以省略-f标志。

You can also use the -p flag to fetch logs for a terminated container. When this option is used within a Pod that had a prior running container instance, logs will print output from the terminated container:

您也可以使用-p标志来获取终止容器的日志。 在具有先前运行的容器实例的Pod中使用此选项时, logs将打印终止的容器的输出:

  • kubectl logs -p nginx-deployment-8859878f8-7gfw9

    kubectl日志-p nginx-deployment-8859878f8-7gfw9

The -c flag allows you to specify the container you’d like to fetch logs from, if the Pod has multiple containers. You can use the --all-containers=true flag to fetch logs from all containers in the Pod.

如果Pod有多个容器,则-c标志允许您指定要从中获取日志的容器。 您可以使用--all-containers=true标志从Pod中的所有容器中获取日志。

Port Forwarding and Proxying

端口转发和代理

To gain network access to a Pod, you can use port-forward:

要获得对Pod的网络访问权限,可以使用port-forward

  • sudo kubectl port-forward pod/nginx-deployment-8859878f8-7gfw9 80:80

    sudo kubectl端口转发pod / nginx-deployment-8859878f8-7gfw9 80:80

   
    
Output
Forwarding from 127.0.0.1:80 -> 80 Forwarding from [::1]:80 -> 80

In this case we use sudo because local port 80 is a protected port. For most other ports you can omit sudo and run the kubectl command as your system user.

在这种情况下,我们使用sudo因为本地端口80是受保护的端口。 对于大多数其他端口,您可以省略sudo并以系统用户身份运行kubectl命令。

Here we forward local port 80 (preceding the colon) to the Pod’s container port 80 (after the colon).

在这里,我们将本地端口80 (在冒号之前)转发到Pod的集装箱端口80 (在冒号之后)。

You can also use deploy/nginx-deployment as the resource type and name to forward to. If you do this, the local port will be forwarded to the Pod selected by the Deployment.

您还可以deploy/nginx-deployment用作转发的资源类型和名称。 如果执行此操作,则本地端口将被转发到部署选择的Pod。

The proxy command can be used to access the Kubernetes API server locally:

proxy命令可用于本地访问Kubernetes API服务器:

  • kubectl proxy --port=8080

    kubectl代理--port = 8080

   
    
Output
Starting to serve on 127.0.0.1:8080

In another shell, use curl to explore the API:

在另一个Shell中,使用curl探索API:

curl http://localhost:8080/api/

   
    
Output
{ "kind": "APIVersions", "versions": [ "v1" ], "serverAddressByClientCIDRs": [ { "clientCIDR": "0.0.0.0/0", "serverAddress": "203.0.113.0:443" } ]

Close the proxy by hitting CTRL-C.

通过按CTRL-C关闭代理。

结论 (Conclusion)

This guide covers some of the more common kubectl commands you may use when managing a Kubernetes cluster and workloads you’ve deployed to it.

本指南介绍了一些在管理Kubernetes集群和部署到其上的工作负载时可能会使用的更常见的kubectl命令。

You can learn more about kubectl by consulting the official Kubernetes reference documentation.

您可以通过参考官方的Kubernetes 参考文档来了解有关kubectl的更多信息。

There are many more commands and variations that you may find useful as part of your work with kubectl. To learn more about all of your available options, you can run:

作为使用kubectl的一部分,您可能会发现更多有用的命令和变体。 要了解有关所有可用选项的更多信息,可以运行:

kubectl --help

翻译自: https://www.digitalocean.com/community/cheatsheets/getting-started-with-kubernetes-a-kubectl-cheat-sheet

kubernetes入门

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cukw6666/article/details/107985443

智能推荐

pycharm在import第三方包时出错/import requests等等出错_苏道丶的博客-程序员资料

我原本已经在cmd里设置在python安装目录下的scripts里运行了pip install requests,也已经安装成功,但是在用pycharm import 时却仍是报错说无此module。主要是使用pycharm新建工程后库不一样了。1/create new project2/选择pure python起任意文件名create3/等待加载完成4/打开lib库发现site-package...

GAMES 202 - 作业 2: Precomputed Radiance Transfer_CCCCCCros____的博客-程序员资料_games202作业2

GAMES 202 - 作业 2作业 2: Precomputed Radiance TransferGAMES 202 - 作业 2作业 2: Precomputed Radiance Transfer总览预计算球谐系数环境光照漫反射传输项Diffuse UnshadowedDiffuse ShadowedDiffuse Inter-reflection(bonus)实时球谐光照计算环境光球谐旋转结果原课程视频链接以及官网b站视频链接: https://www.bilibili.com/video/

xilinx的quick boot(1) ——flash的一些内容_weixin_30636089的博客-程序员资料

xilinx的quick boot(1) ——flash,quick boot配置文件,以及中间的一些联系xilinx 配置模式分为SPI,BPI。用过的spi外挂flash是N25Q。/////////////spi flash N25Q //////////////////////////////////////////////////flash分为区(block),扇区(sector),子扇...

pyqt5 mysql 驱动_PyQt5连接MySQL及QMYSQL driver not loaded错误解决_weixin_34570507的博客-程序员资料

一、连接语句from PyQt5.QtSql import QSqlDatabasedb=QSqlDatabase.addDatabase("QMYSQL")db.setHostName("localhost")db.setDatabaseName("dbwork")db.setUserName("users")db.setPassword("ZDSYS")db.setPort(3306)db.o...

文件上传漏洞解析及简单绕过技巧_秋水sir的博客-程序员资料

文件上传漏洞简介什么是文件上传漏洞?简单来说就是,攻击者向服务器上上传了服务器可以解析的动态脚本文件,这里上传的文件可以是木马,病毒,恶意脚本或者Webshell等这种攻击方式是最为直接和有效的,“文件上传”本身没有问题,有问题的是文件上传后,服务器怎么处理、解释文件。如果服务器的处理逻辑做的不够安全,则会导致严重的后果为什么会产生文件上传漏洞?这是因为,开发人员由于大意...

手把手教你在Linux(Deepin)通过you-get下载网页视频_发呆哥o_o ....的博客-程序员资料_linux 下载视频

you-get简介下载you-get如何使用you-get简介you-get是一款开源的视频网站下载工具(一般都是1080P的)。使用You-Get可以很轻松的下载到网络上的视频、图片及音乐。(算了,直男说不出来花里胡哨的东西,直接下载吧)you-get下载百度搜索会显示需要下载各种环境,配置各种文件,这里在Deepin只需要几个简单的命令更新sudo apt-get update安装 pipsudo apt-get install python3-pip安装 you-get.

随便推点

单文件程序库2_yazhouren的博客-程序员资料

Packageshtmk edited this page 5 days ago · 253 revisions Pages 3HomeExplanation of package.jsonPackagesClone this wiki locally Clone in DesktopLis

Android学习——控件ListView的使用_anjiukonghe77852的博客-程序员资料

一、ListView的简单用法首先新建一个ListViewTest项目,并让Android Studio自动创建好活动。然后修改activity_main.xml中的代码,如下: 1 &lt;?xml version="1.0" encoding="utf-8"?&gt; 2 &lt;LinearLayout xmlns:android="http://schemas.a...

ABAP ALV显示简单例子_土星环的土的博客-程序员资料_abap alv 例子

*&amp;---------------------------------------------------------------------**&amp;ReportZ_210113_02*&amp;---------------------------------------------------------------------**&amp;*&amp;---------------------------------------------------------------..

【数据库】查询和01号学生学习的课程完全相同的其他同学的信息_Angusis的博客-程序员资料_查询和01学生课程完全相同

今天读了几篇博客:https://blog.csdn.net/qq_41080850/article/details/84593860https://www.cnblogs.com/fengyunlishi/archive/2012/10/18/2730051.htmlhttps://blog.csdn.net/qq_41080850/article/details/84648897#co...

K-means(K均值)算法 简单实现 二维/三维结果展示_alphaTao的博客-程序员资料_kmeans三维聚类

1. 简介k-means算法是一种聚类算法,所谓聚类,即根据相似性原则,将具有较高相似度的数据对象划分至同一类簇,将具有较高相异度的数据对象划分至不同类簇。聚类与分类最大的区别在于,聚类过程为无监督过程,即待处理数据对象没有任何先验知识,而分类过程为有监督过程。k-means是最简单的聚类算法之一,应用十分广泛,k代表类簇个数,means代表类簇内数据对象的均值。k-means以距离作为相...

php resultset,PHP oci_get_implicit_resultset 用法 手册 | 示例代码_顾茈陌里的博客-程序员资料

$conn=oci_connect('hr','welcome','localhost/pdborcl');if(!$conn){$e=oci_error();trigger_error(htmlentities($e['message'],ENT_QUOTES),E_USER_ERROR);}$sql='DECLAREc1SYS_REFCURSOR;BEGINOPENc1FORSEL...

推荐文章

热门文章

相关标签