Switch language name 'zh' to 'zh-cn'

This is the first step to rename 'zh' to 'zh-cn'. There are several reasons why we rename the language name.

- The upstream docsy theme changed the language name, leading to many warnings during site build;
  The side-effect is that the i18n strings are no longer working.
- We believe renaming the language is the right thing to do, because this move can make room for other variants of Chinese language, such as 'zh-tw', 'zh-sg' etc.

There would be several follow-ups to this PR, such as fixing the intra-site links, adding redirects etc.

We will lock up changes to zh/zh-cn pages for the moment, until this one gets in.

This PR is based on commit cdad0a7342.
This commit is contained in:
Qiming Teng
2022-06-10 20:25:27 +08:00
parent 3d345b1816
commit c52818c03d
1347 changed files with 8 additions and 6 deletions
@@ -0,0 +1,7 @@
---
title: 使用 Kubernetes 对象
weight: 40
description: >
Kubernetes 对象是 Kubernetes 系统中的持久性实体。Kubernetes 使用这些实体表示你的集群状态。
了解 Kubernetes 对象模型以及如何使用这些对象。
---
@@ -0,0 +1,167 @@
---
title: 注解
content_type: concept
weight: 50
---
<!--
title: Annotations
content_type: concept
weight: 50
-->
<!-- overview -->
<!--
You can use Kubernetes annotations to attach arbitrary non-identifying metadata
to objects. Clients such as tools and libraries can retrieve this metadata.
-->
你可以使用 Kubernetes 注解为对象附加任意的非标识的元数据。客户端程序(例如工具和库)能够获取这些元数据信息。
<!-- body -->
<!--
## Attaching metadata to objects
You can use either labels or annotations to attach metadata to Kubernetes
objects. Labels can be used to select objects and to find
collections of objects that satisfy certain conditions. In contrast, annotations
are not used to identify and select objects. The metadata
in an annotation can be small or large, structured or unstructured, and can
include characters not permitted by labels.
Annotations, like labels, are key/value maps:
-->
## 为对象附加元数据
你可以使用标签或注解将元数据附加到 Kubernetes 对象。
标签可以用来选择对象和查找满足某些条件的对象集合。 相反,注解不用于标识和选择对象。
注解中的元数据,可以很小,也可以很大,可以是结构化的,也可以是非结构化的,能够包含标签不允许的字符。
注解和标签一样,是键/值对:
```json
"metadata": {
"annotations": {
"key1" : "value1",
"key2" : "value2"
}
}
```
{{<note>}}
<!--
The keys and the values in the map must be strings. In other words, you cannot use
numeric, boolean, list or other types for either the keys or the values.
-->
Map 中的键和值必须是字符串。
换句话说,你不能使用数字、布尔值、列表或其他类型的键或值。
{{</note>}}
<!--
Here are some examples of information that could be recorded in annotations:
-->
以下是一些例子,用来说明哪些信息可以使用注解来记录:
<!--
* Fields managed by a declarative configuration layer. Attaching these fields
as annotations distinguishes them from default values set by clients or
servers, and from auto-generated fields and fields set by
auto-sizing or auto-scaling systems.
* Build, release, or image information like timestamps, release IDs, git branch,
PR numbers, image hashes, and registry address.
* Pointers to logging, monitoring, analytics, or audit repositories.
-->
* 由声明性配置所管理的字段。
将这些字段附加为注解,能够将它们与客户端或服务端设置的默认值、
自动生成的字段以及通过自动调整大小或自动伸缩系统设置的字段区分开来。
* 构建、发布或镜像信息(如时间戳、发布 ID、Git 分支、PR 数量、镜像哈希、仓库地址)。
* 指向日志记录、监控、分析或审计仓库的指针。
<!--
* Client library or tool information that can be used for debugging purposes:
for example, name, version, and build information.
* User or tool/system provenance information, such as URLs of related objects
from other ecosystem components.
* Lightweight rollout tool metadata: for example, config or checkpoints.
* Phone or pager numbers of persons responsible, or directory entries that
specify where that information can be found, such as a team web site.
* Directives from the end-user to the implementations to modify behavior or
engage non-standard features.
-->
* 可用于调试目的的客户端库或工具信息:例如,名称、版本和构建信息。
* 用户或者工具/系统的来源信息,例如来自其他生态系统组件的相关对象的 URL。
* 轻量级上线工具的元数据信息:例如,配置或检查点。
* 负责人员的电话或呼机号码,或指定在何处可以找到该信息的目录条目,如团队网站。
* 从用户到最终运行的指令,以修改行为或使用非标准功能。
<!--
Instead of using annotations, you could store this type of information in an
external database or directory, but that would make it much harder to produce
shared client libraries and tools for deployment, management, introspection,
and the like.
-->
你可以将这类信息存储在外部数据库或目录中而不使用注解,
但这样做就使得开发人员很难生成用于部署、管理、自检的客户端共享库和工具。
<!--
## Syntax and character set
_Annotations_ are key/value pairs. Valid annotation keys have two segments: an optional prefix and name, separated by a slash (`/`). The name segment is required and must be 63 characters or less, beginning and ending with an alphanumeric character (`[a-z0-9A-Z]`) with dashes (`-`), underscores (`_`), dots (`.`), and alphanumerics between. The prefix is optional. If specified, the prefix must be a DNS subdomain: a series of DNS labels separated by dots (`.`), not longer than 253 characters in total, followed by a slash (`/`).
If the prefix is omitted, the annotation Key is presumed to be private to the user. Automated system components (e.g. `kube-scheduler`, `kube-controller-manager`, `kube-apiserver`, `kubectl`, or other third-party automation) which add annotations to end-user objects must specify a prefix.
-->
## 语法和字符集
_注解(Annotations_ 存储的形式是键/值对。有效的注解键分为两部分:
可选的前缀和名称,以斜杠(`/`)分隔。
名称段是必需项,并且必须在 63 个字符以内,以字母数字字符(`[a-z0-9A-Z]`)开头和结尾,
并允许使用破折号(`-`),下划线(`_`),点(`.`)和字母数字。
前缀是可选的。如果指定,则前缀必须是 DNS 子域:一系列由点(`.`)分隔的 DNS 标签,
总计不超过 253 个字符,后跟斜杠(`/`)。
如果省略前缀,则假定注解键对用户是私有的。 由系统组件添加的注解
(例如,`kube-scheduler``kube-controller-manager``kube-apiserver``kubectl`
或其他第三方组件),必须为终端用户添加注解前缀。
<!--
The `kubernetes.io/` and `k8s.io/` prefixes are reserved for Kubernetes core components.
For example, here's the configuration file for a Pod that has the annotation `imageregistry: https://hub.docker.com/` :
-->
`kubernetes.io/``k8s.io/` 前缀是为 Kubernetes 核心组件保留的。
例如,下面是一个 Pod 的配置文件,其注解中包含 `imageregistry: https://hub.docker.com/`
```yaml
apiVersion: v1
kind: Pod
metadata:
name: annotations-demo
annotations:
imageregistry: "https://hub.docker.com/"
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
```
## {{% heading "whatsnext" %}}
<!--
* Learn more about [Labels and Selectors](/docs/concepts/overview/working-with-objects/labels/).
-->
* 进一步了解[标签和选择算符](/zh/docs/concepts/overview/working-with-objects/labels/)。
@@ -0,0 +1,263 @@
---
title: 推荐使用的标签
content_type: concept
---
<!--
---
title: Recommended Labels
content_type: concept
---
-->
<!-- overview -->
<!--
You can visualize and manage Kubernetes objects with more tools than kubectl and
the dashboard. A common set of labels allows tools to work interoperably, describing
objects in a common manner that all tools can understand.
-->
除了 kubectl 和 dashboard 之外,你可以使用其他工具来可视化和管理 Kubernetes 对象。
一组通用的标签可以让多个工具之间相互操作,用所有工具都能理解的通用方式描述对象。
<!--
In addition to supporting tooling, the recommended labels describe applications
in a way that can be queried.
-->
除了支持工具外,推荐的标签还以一种可以查询的方式描述了应用程序。
<!-- body -->
<!--
The metadata is organized around the concept of an _application_. Kubernetes is not
a platform as a service (PaaS) and doesn't have or enforce a formal notion of an application.
Instead, applications are informal and described with metadata. The definition of
what an application contains is loose.
-->
元数据围绕 _应用(application_ 的概念进行组织。Kubernetes 不是
平台即服务(PaaS),没有或强制执行正式的应用程序概念。
相反,应用程序是非正式的,并使用元数据进行描述。应用程序包含的定义是松散的。
{{< note >}}
<!--
These are recommended labels. They make it easier to manage applications
but aren't required for any core tooling.
-->
这些是推荐的标签。它们使管理应用程序变得更容易但不是任何核心工具所必需的。
{{< /note >}}
<!--
Shared labels and annotations share a common prefix: `app.kubernetes.io`. Labels
without a prefix are private to users. The shared prefix ensures that shared labels
do not interfere with custom user labels.
-->
共享标签和注解都使用同一个前缀:`app.kubernetes.io`。没有前缀的标签是用户私有的。共享前缀可以确保共享标签不会干扰用户自定义的标签。
<!--
## Labels
In order to take full advantage of using these labels, they should be applied
on every resource object.
-->
## 标签
为了充分利用这些标签,应该在每个资源对象上都使用它们。
<!--
| Key | Description | Example | Type |
| ----------------------------------- | --------------------- | -------- | ---- |
| `app.kubernetes.io/name` | The name of the application | `mysql` | string |
| `app.kubernetes.io/instance` | A unique name identifying the instance of an application | `mysql-abcxzy` | string |
| `app.kubernetes.io/version` | The current version of the application (e.g., a semantic version, revision hash, etc.) | `5.7.21` | string |
| `app.kubernetes.io/component` | The component within the architecture | `database` | string |
| `app.kubernetes.io/part-of` | The name of a higher level application this one is part of | `wordpress` | string |
| `app.kubernetes.io/managed-by` | The tool being used to manage the operation of an application | `helm` | string |
| `app.kubernetes.io/created-by` | The controller/user who created this resource | `controller-manager` | string |
-->
| 键 | 描述 | 示例 | 类型 |
| ----------------------------------- | --------------------- | -------- | ---- |
| `app.kubernetes.io/name` | 应用程序的名称 | `mysql` | 字符串 |
| `app.kubernetes.io/instance` | 用于唯一确定应用实例的名称 | `mysql-abcxzy` | 字符串 |
| `app.kubernetes.io/version` | 应用程序的当前版本(例如,语义版本,修订版哈希等) | `5.7.21` | 字符串 |
| `app.kubernetes.io/component` | 架构中的组件 | `database` | 字符串 |
| `app.kubernetes.io/part-of` | 此级别的更高级别应用程序的名称 | `wordpress` | 字符串 |
| `app.kubernetes.io/managed-by` | 用于管理应用程序的工具 | `helm` | 字符串 |
| `app.kubernetes.io/created-by` | 创建该资源的控制器或者用户 | `controller-manager` | 字符串 |
<!--
To illustrate these labels in action, consider the following {{< glossary_tooltip text="StatefulSet" term_id="statefulset" >}} object:
-->
为说明这些标签的实际使用情况,请看下面的 {{< glossary_tooltip text="StatefulSet" term_id="statefulset" >}} 对象:
```yaml
# 这是一段节选
apiVersion: apps/v1
kind: StatefulSet
metadata:
labels:
app.kubernetes.io/name: mysql
app.kubernetes.io/instance: mysql-abcxzy
app.kubernetes.io/version: "5.7.21"
app.kubernetes.io/component: database
app.kubernetes.io/part-of: wordpress
app.kubernetes.io/managed-by: helm
app.kubernetes.io/created-by: controller-manager
```
<!--
## Applications And Instances Of Applications
An application can be installed one or more times into a Kubernetes cluster and,
in some cases, the same namespace. For example, WordPress can be installed more
than once where different websites are different installations of WordPress.
The name of an application and the instance name are recorded separately. For
example, WordPress has a `app.kubernetes.io/name` of `wordpress` while it has
an instance name, represented as `app.kubernetes.io/instance` with a value of
`wordpress-abcxzy`. This enables the application and instance of the application
to be identifiable. Every instance of an application must have a unique name.
-->
## 应用和应用实例
应用可以在 Kubernetes 集群中安装一次或多次。在某些情况下,可以安装在同一命名空间中。例如,可以不止一次地为不同的站点安装不同的 WordPress。
应用的名称和实例的名称是分别记录的。例如,WordPress 应用的
`app.kubernetes.io/name``wordpress`,而其实例名称
`app.kubernetes.io/instance``wordpress-abcxzy`
这使得应用和应用的实例均可被识别,应用的每个实例都必须具有唯一的名称。
<!--
## Examples
-->
## 示例
<!--
To illustrate different ways to use these labels the following examples have varying complexity.
-->
为了说明使用这些标签的不同方式,以下示例具有不同的复杂性。
<!--
### A Simple Stateless Service
-->
### 一个简单的无状态服务
<!--
Consider the case for a simple stateless service deployed using `Deployment` and `Service` objects. The following two snippets represent how the labels could be used in their simplest form.
-->
考虑使用 `Deployment``Service` 对象部署的简单无状态服务的情况。以下两个代码段表示如何以最简单的形式使用标签。
<!--
The `Deployment` is used to oversee the pods running the application itself.
-->
下面的 `Deployment` 用于监督运行应用本身的 pods。
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app.kubernetes.io/name: myservice
app.kubernetes.io/instance: myservice-abcxzy
...
```
<!--
The `Service` is used to expose the application.
-->
下面的 `Service` 用于暴露应用。
```yaml
apiVersion: v1
kind: Service
metadata:
labels:
app.kubernetes.io/name: myservice
app.kubernetes.io/instance: myservice-abcxzy
...
```
<!--
### Web Application With A Database
-->
### 带有一个数据库的 Web 应用程序
<!--
Consider a slightly more complicated application: a web application (WordPress)
using a database (MySQL), installed using Helm. The following snippets illustrate
the start of objects used to deploy this application.
The start to the following `Deployment` is used for WordPress:
-->
考虑一个稍微复杂的应用:一个使用 Helm 安装的 Web 应用(WordPress),其中
使用了数据库(MySQL)。以下代码片段说明用于部署此应用程序的对象的开始。
以下 `Deployment` 的开头用于 WordPress
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app.kubernetes.io/name: wordpress
app.kubernetes.io/instance: wordpress-abcxzy
app.kubernetes.io/version: "4.9.4"
app.kubernetes.io/managed-by: helm
app.kubernetes.io/component: server
app.kubernetes.io/part-of: wordpress
...
```
<!--
The `Service` is used to expose WordPress:
-->
这个 `Service` 用于暴露 WordPress
```yaml
apiVersion: v1
kind: Service
metadata:
labels:
app.kubernetes.io/name: wordpress
app.kubernetes.io/instance: wordpress-abcxzy
app.kubernetes.io/version: "4.9.4"
app.kubernetes.io/managed-by: helm
app.kubernetes.io/component: server
app.kubernetes.io/part-of: wordpress
...
```
<!--
MySQL is exposed as a `StatefulSet` with metadata for both it and the larger application it belongs to:
-->
MySQL 作为一个 `StatefulSet` 暴露,包含它和它所属的较大应用程序的元数据:
```yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
labels:
app.kubernetes.io/name: mysql
app.kubernetes.io/instance: mysql-abcxzy
app.kubernetes.io/version: "5.7.21"
app.kubernetes.io/managed-by: helm
app.kubernetes.io/component: database
app.kubernetes.io/part-of: wordpress
...
```
<!--
The `Service` is used to expose MySQL as part of WordPress:
-->
`Service` 用于将 MySQL 作为 WordPress 的一部分暴露:
```yaml
apiVersion: v1
kind: Service
metadata:
labels:
app.kubernetes.io/name: mysql
app.kubernetes.io/instance: mysql-abcxzy
app.kubernetes.io/version: "5.7.21"
app.kubernetes.io/managed-by: helm
app.kubernetes.io/component: database
app.kubernetes.io/part-of: wordpress
...
```
<!--
With the MySQL `StatefulSet` and `Service` you'll notice information about both MySQL and Wordpress, the broader application, are included.
-->
使用 MySQL `StatefulSet``Service`,你会注意到有关 MySQL 和 Wordpress 的信息,包括更广泛的应用程序。
@@ -0,0 +1,105 @@
---
title: 字段选择器
weight: 60
---
<!--
title: Field Selectors
weight: 60
-->
<!--
_Field selectors_ let you [select Kubernetes resources](/docs/concepts/overview/working-with-objects/kubernetes-objects) based on the value of one or more resource fields. Here are some example field selector queries:
-->
“字段选择器(Field selectors)”允许你根据一个或多个资源字段的值
[筛选 Kubernetes 资源](/zh/docs/concepts/overview/working-with-objects/kubernetes-objects)。
下面是一些使用字段选择器查询的例子:
* `metadata.name=my-service`
* `metadata.namespace!=default`
* `status.phase=Pending`
<!--
This `kubectl` command selects all Pods for which the value of the [`status.phase`](/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase) field is `Running`:
-->
下面这个 `kubectl` 命令将筛选出 [`status.phase`](/zh/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase)
字段值为 `Running` 的所有 Pod
```shell
kubectl get pods --field-selector status.phase=Running
```
<!--
Field selectors are essentially resource *filters*. By default, no selectors/filters are applied, meaning that all resources of the specified type are selected. This makes the following `kubectl` queries equivalent:
-->
{{< note >}}
字段选择器本质上是资源“过滤器(Filters)”。默认情况下,字段选择器/过滤器是未被应用的,
这意味着指定类型的所有资源都会被筛选出来。
这使得以下的两个 `kubectl` 查询是等价的:
```shell
kubectl get pods
kubectl get pods --field-selector ""
```
{{< /note >}}
<!--
## Supported fields
Supported field selectors vary by Kubernetes resource type. All resource types support the `metadata.name` and `metadata.namespace` fields. Using unsupported field selectors produces an error. For example:
-->
## 支持的字段 {#supported-fields}
不同的 Kubernetes 资源类型支持不同的字段选择器。
所有资源类型都支持 `metadata.name``metadata.namespace` 字段。
使用不被支持的字段选择器会产生错误。例如:
```shell
kubectl get ingress --field-selector foo.bar=baz
```
```
Error from server (BadRequest): Unable to find "ingresses" that match label selector "", field selector "foo.bar=baz": "foo.bar" is not a known field selector: only "metadata.name", "metadata.namespace"
```
<!--
## Supported operators
You can use the `=`, `==`, and `!=` operators with field selectors (`=` and `==` mean the same thing). This `kubectl` command, for example, selects all Kubernetes Services that aren't in the `default` namespace:
-->
## 支持的操作符 {#supported-operators}
你可在字段选择器中使用 `=``==``!=` `=``==` 的意义是相同的)操作符。
例如,下面这个 `kubectl` 命令将筛选所有不属于 `default` 命名空间的 Kubernetes 服务:
```shell
kubectl get services --all-namespaces --field-selector metadata.namespace!=default
```
<!--
## Chained selectors
As with [label](/docs/concepts/overview/working-with-objects/labels) and other selectors, field selectors can be chained together as a comma-separated list. This `kubectl` command selects all Pods for which the `status.phase` does not equal `Running` and the `spec.restartPolicy` field equals `Always`:
-->
## 链式选择器 {#chained-selectors}
同[标签](/zh/docs/concepts/overview/working-with-objects/labels/)和其他选择器一样,
字段选择器可以通过使用逗号分隔的列表组成一个选择链。
下面这个 `kubectl` 命令将筛选 `status.phase` 字段不等于 `Running` 同时
`spec.restartPolicy` 字段等于 `Always` 的所有 Pod
```shell
kubectl get pods --field-selector=status.phase!=Running,spec.restartPolicy=Always
```
<!--
## Multiple resource types
You can use field selectors across multiple resource types. This `kubectl` command selects all Statefulsets and Services that are not in the `default` namespace:
-->
## 多种资源类型 {#multiple-resource-types}
你能够跨多种资源类型来使用字段选择器。
下面这个 `kubectl` 命令将筛选出所有不在 `default` 命名空间中的 StatefulSet 和 Service
```shell
kubectl get statefulsets,services --all-namespaces --field-selector metadata.namespace!=default
```
@@ -0,0 +1,157 @@
---
title: Finalizers
content_type: concept
weight: 60
---
<!-- overview -->
{{<glossary_definition term_id="finalizer" length="long">}}
<!--
You can use finalizers to control {{<glossary_tooltip text="garbage collection" term_id="garbage-collection">}}
of resources by alerting {{<glossary_tooltip text="controllers" term_id="controller">}} to perform specific cleanup tasks before
deleting the target resource.
-->
你可以通过使用 Finalizers 提醒{{<glossary_tooltip text="控制器" term_id="controller">}}
在删除目标资源前执行特定的清理任务,
来控制资源的{{<glossary_tooltip text="垃圾收集" term_id="garbage-collection">}}。
<!--
Finalizers don't usually specify the code to execute. Instead, they are
typically lists of keys on a specific resource similar to annotations.
Kubernetes specifies some finalizers automatically, but you can also specify
your own.
-->
Finalizers 通常不指定要执行的代码。
相反,它们通常是特定资源上的键的列表,类似于注解。
Kubernetes 自动指定了一些 Finalizers,但你也可以指定你自己的。
<!--
## How finalizers work
When you create a resource using a manifest file, you can specify finalizers in
the `metadata.finalizers` field. When you attempt to delete the resource, the
API server handling the delete request notices the values in the `finalizers` field
and does the following:
* Modifies the object to add a `metadata.deletionTimestamp` field with the
time you started the deletion.
* Prevents the object from being removed until its `metadata.finalizers` field is empty.
* Returns a `202` status code (HTTP "Accepted")
-->
## Finalizers 如何工作 {#how-finalizers-work}
当你使用清单文件创建资源时,你可以在 `metadata.finalizers` 字段指定 Finalizers。
当你试图删除该资源时,处理删除请求的 API 服务器会注意到 `finalizers` 字段中的值,
并进行以下操作:
* 修改对象,将你开始执行删除的时间添加到 `metadata.deletionTimestamp` 字段。
* 禁止对象被删除,直到其 `metadata.finalizers` 字段为空。
* 返回 `202` 状态码(HTTP "Accepted")。
<!--
The controller managing that finalizer notices the update to the object setting the
`metadata.deletionTimestamp`, indicating deletion of the object has been requested.
The controller then attempts to satisfy the requirements of the finalizers
specified for that resource. Each time a finalizer condition is satisfied, the
controller removes that key from the resource's `finalizers` field. When the
`finalizers` field is emptied, an object with a `deletionTimestamp` field set
is automatically deleted. You can also use finalizers to prevent deletion of unmanaged resources.
-->
管理 finalizer 的控制器注意到对象上发生的更新操作,对象的 `metadata.deletionTimestamp`
被设置,意味着已经请求删除该对象。然后,控制器会试图满足资源的 Finalizers 的条件。
每当一个 Finalizer 的条件被满足时,控制器就会从资源的 `finalizers` 字段中删除该键。
`finalizers` 字段为空时,`deletionTimestamp` 字段被设置的对象会被自动删除。
你也可以使用 Finalizers 来阻止删除未被管理的资源。
<!--
A common example of a finalizer is `kubernetes.io/pv-protection`, which prevents
accidental deletion of `PersistentVolume` objects. When a `PersistentVolume`
object is in use by a Pod, Kubernetes adds the `pv-protection` finalizer. If you
try to delete the `PersistentVolume`, it enters a `Terminating` status, but the
controller can't delete it because the finalizer exists. When the Pod stops
using the `PersistentVolume`, Kubernetes clears the `pv-protection` finalizer,
and the controller deletes the volume.
-->
一个常见的 Finalizer 的例子是 `kubernetes.io/pv-protection`
它用来防止意外删除 `PersistentVolume` 对象。
当一个 `PersistentVolume` 对象被 Pod 使用时,
Kubernetes 会添加 `pv-protection` Finalizer。
如果你试图删除 `PersistentVolume`,它将进入 `Terminating` 状态,
但是控制器因为该 Finalizer 存在而无法删除该资源。
当 Pod 停止使用 `PersistentVolume` 时,
Kubernetes 清除 `pv-protection` Finalizer,控制器就会删除该卷。
<!--
## Owner references, labels, and finalizers {#owners-labels-finalizers}
Like {{<glossary_tooltip text="labels" term_id="label">}},
[owner references](/concepts/overview/working-with-objects/owners-dependents/)
describe the relationships between objects in Kubernetes, but are used for a
different purpose. When a
{{<glossary_tooltip text="controller" term_id="controller">}} manages objects
like Pods, it uses labels to track changes to groups of related objects. For
example, when a {{<glossary_tooltip text="Job" term_id="job">}} creates one or
more Pods, the Job controller applies labels to those pods and tracks changes to
any Pods in the cluster with the same label.
-->
## 属主引用、标签和 Finalizers {#owners-labels-finalizers}
与{{<glossary_tooltip text="标签" term_id="label">}}类似,
[属主引用](/zh/concepts/overview/working-with-objects/owners-dependents/)
描述了 Kubernetes 中对象之间的关系,但它们作用不同。
当一个{{<glossary_tooltip text="控制器" term_id="controller">}}
管理类似于 Pod 的对象时,它使用标签来跟踪相关对象组的变化。
例如,当 {{<glossary_tooltip text="Job" term_id="job">}} 创建一个或多个 Pod 时,
Job 控制器会给这些 Pod 应用上标签,并跟踪集群中的具有相同标签的 Pod 的变化。
<!--
The Job controller also adds *owner references* to those Pods, pointing at the
Job that created the Pods. If you delete the Job while these Pods are running,
Kubernetes uses the owner references (not labels) to determine which Pods in the
cluster need cleanup.
Kubernetes also processes finalizers when it identifies owner references on a
resource targeted for deletion.
In some situations, finalizers can block the deletion of dependent objects,
which can cause the targeted owner object to remain for
longer than expected without being fully deleted. In these situations, you
should check finalizers and owner references on the target owner and dependent
objects to troubleshoot the cause.
-->
Job 控制器还为这些 Pod 添加了“属主引用”,指向创建 Pod 的 Job。
如果你在这些 Pod 运行的时候删除了 Job,
Kubernetes 会使用属主引用(而不是标签)来确定集群中哪些 Pod 需要清理。
当 Kubernetes 识别到要删除的资源上的属主引用时,它也会处理 Finalizers。
在某些情况下,Finalizers 会阻止依赖对象的删除,
这可能导致目标属主对象被保留的时间比预期的长,而没有被完全删除。
在这些情况下,你应该检查目标属主和附属对象上的 Finalizers 和属主引用,来排查原因。
{{< note >}}
<!--
In cases where objects are stuck in a deleting state, avoid manually
removing finalizers to allow deletion to continue. Finalizers are usually added
to resources for a reason, so forcefully removing them can lead to issues in
your cluster. This should only be done when the purpose of the finalizer is
understood and is accomplished in another way (for example, manually cleaning
up some dependent object).
-->
在对象卡在删除状态的情况下,要避免手动移除 Finalizers,以允许继续删除操作。
Finalizers 通常因为特殊原因被添加到资源上,所以强行删除它们会导致集群出现问题。
只有了解 finalizer 的用途时才能这样做,并且应该通过一些其他方式来完成
(例如,手动清除其余的依赖对象)。
{{< /note >}}
## {{% heading "whatsnext" %}}
<!--
* Read [Using Finalizers to Control Deletion](/blog/2021/05/14/using-finalizers-to-control-deletion/)
on the Kubernetes blog.
-->
* 在 Kubernetes 博客上阅读[使用 Finalizers 控制删除](/blog/2021/05/14/using-finalizers-to-control-deletion/)。
@@ -0,0 +1,216 @@
---
title: 理解 Kubernetes 对象
content_type: concept
weight: 10
card:
name: concepts
weight: 40
---
<!---
title: Understanding Kubernetes Objects
content_type: concept
weight: 10
card:
name: concepts
weight: 40
-->
<!-- overview -->
<!--
This page explains how Kubernetes objects are represented in the Kubernetes API, and how you can express them in `.yaml` format.
-->
本页说明了 Kubernetes 对象在 Kubernetes API 中是如何表示的,以及如何在 `.yaml` 格式的文件中表示。
<!-- body -->
<!--
## Understanding Kubernetes Objects
*Kubernetes Objects* are persistent entities in the Kubernetes system. Kubernetes uses these entities to represent the state of your cluster. Specifically, they can describe:
* What containerized applications are running (and on which nodes)
* The resources available to those applications
* The policies around how those applications behave, such as restart policies, upgrades, and fault-tolerance
-->
## 理解 Kubernetes 对象
在 Kubernetes 系统中,*Kubernetes 对象* 是持久化的实体。
Kubernetes 使用这些实体去表示整个集群的状态。特别地,它们描述了如下信息:
* 哪些容器化应用在运行(以及在哪些节点上)
* 可以被应用使用的资源
* 关于应用运行时表现的策略,比如重启策略、升级策略,以及容错策略
<!--
A Kubernetes object is a "record of intent" - once you create the object, the Kubernetes system will constantly work to ensure that object exists. By creating an object, you're effectively telling the Kubernetes system what you want your cluster's workload to look like; this is your cluster's *desired state*.
To work with Kubernetes objects - whether to create, modify, or delete them - you'll need to use the [Kubernetes API](/docs/concepts/overview/kubernetes-api/). When you use the `kubectl` command-line interface, for example, the CLI makes the necessary Kubernetes API calls for you. You can also use the Kubernetes API directly in your own programs using one of the [Client Libraries](/docs/reference/using-api/client-libraries/).
-->
Kubernetes 对象是 “目标性记录” —— 一旦创建对象,Kubernetes 系统将持续工作以确保对象存在。
通过创建对象,本质上是在告知 Kubernetes 系统,所需要的集群工作负载看起来是什么样子的,
这就是 Kubernetes 集群的 **期望状态(Desired State**
操作 Kubernetes 对象 —— 无论是创建、修改,或者删除 —— 需要使用
[Kubernetes API](/zh/docs/concepts/overview/kubernetes-api)。
比如,当使用 `kubectl` 命令行接口时,CLI 会执行必要的 Kubernetes API 调用,
也可以在程序中使用
[客户端库](/zh/docs/reference/using-api/client-libraries/)直接调用 Kubernetes API。
<!--
### Object Spec and Status
Almost every Kubernetes object includes two nested object fields that govern
the object's configuration: the object *`spec`* and the object *`status`*.
For objects that have a `spec`, you have to set this when you create the object,
providing a description of the characteristics you want the resource to have:
its _desired state_.
-->
### 对象规约(Spec)与状态(Status {#object-spec-and-status}
几乎每个 Kubernetes 对象包含两个嵌套的对象字段,它们负责管理对象的配置:
对象 *`spec`(规约)* 和 对象 *`status`(状态)*
对于具有 `spec` 的对象,你必须在创建对象时设置其内容,描述你希望对象所具有的特征:
*期望状态(Desired State*
<!--
The `status` describes the _current state_ of the object, supplied and updated
by the Kubernetes system and its components. The Kubernetes
{{< glossary_tooltip text="control plane" term_id="control-plane" >}} continually
and actively manages every object's actual state to match the desired state you
supplied.
-->
`status` 描述了对象的 _当前状态(Current State_,它是由 Kubernetes 系统和组件
设置并更新的。在任何时刻,Kubernetes
{{< glossary_tooltip text="控制平面" term_id="control-plane" >}}
都一直积极地管理着对象的实际状态,以使之与期望状态相匹配。
<!--
For example: in Kubernetes, a Deployment is an object that can represent an
application running on your cluster. When you create the Deployment, you
might set the Deployment `spec` to specify that you want three replicas of
the application to be running. The Kubernetes system reads the Deployment
spec and starts three instances of your desired application-updating
the status to match your spec. If any of those instances should fail
(a status change), the Kubernetes system responds to the difference
between spec and status by making a correction-in this case, starting
a replacement instance.
-->
例如,Kubernetes 中的 Deployment 对象能够表示运行在集群中的应用。
当创建 Deployment 时,可能需要设置 Deployment 的 `spec`,以指定该应用需要有 3 个副本运行。
Kubernetes 系统读取 Deployment 规约,并启动我们所期望的应用的 3 个实例
—— 更新状态以与规约相匹配。
如果这些实例中有的失败了(一种状态变更),Kubernetes 系统通过执行修正操作
来响应规约和状态间的不一致 —— 在这里意味着它会启动一个新的实例来替换。
<!--
For more information on the object spec, status, and metadata, see the [Kubernetes API Conventions](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md).
-->
关于对象 spec、status 和 metadata 的更多信息,可参阅
[Kubernetes API 约定](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md)。
<!--
### Describing a Kubernetes Object
When you create an object in Kubernetes, you must provide the object spec that describes its desired state, as well as some basic information about the object (such as a name). When you use the Kubernetes API to create the object (either directly or via `kubectl`), that API request must include that information as JSON in the request body. **Most often, you provide the information to `kubectl` in a .yaml file.** `kubectl` converts the information to JSON when making the API request.
Here's an example `.yaml` file that shows the required fields and object spec for a Kubernetes Deployment:
-->
### 描述 Kubernetes 对象
创建 Kubernetes 对象时,必须提供对象的规约,用来描述该对象的期望状态,
以及关于对象的一些基本信息(例如名称)。
当使用 Kubernetes API 创建对象时(或者直接创建,或者基于 `kubectl`),
API 请求必须在请求体中包含 JSON 格式的信息。
**大多数情况下,需要在 .yaml 文件中为 `kubectl` 提供这些信息**
`kubectl` 在发起 API 请求时,将这些信息转换成 JSON 格式。
这里有一个 `.yaml` 示例文件,展示了 Kubernetes Deployment 的必需字段和对象规约:
{{< codenew file="application/deployment.yaml" >}}
<!--
One way to create a Deployment using a `.yaml` file like the one above is to use the
[`kubectl apply`](/docs/reference/generated/kubectl/kubectl-commands#apply) command
in the `kubectl` command-line interface, passing the `.yaml` file as an argument. Here's an example:
-->
使用类似于上面的 `.yaml` 文件来创建 Deployment 的一种方式是使用 `kubectl` 命令行接口(CLI)中的
[`kubectl apply`](/docs/reference/generated/kubectl/kubectl-commands#apply) 命令,
`.yaml` 文件作为参数。下面是一个示例:
```shell
kubectl apply -f https://k8s.io/examples/application/deployment.yaml
```
<!--
The output is similar to this:
-->
输出类似如下这样:
```
deployment.apps/nginx-deployment created
```
<!--
### Required Fields
In the `.yaml` file for the Kubernetes object you want to create, you'll need to set values for the following fields:
* `apiVersion` - Which version of the Kubernetes API you're using to create this object
* `kind` - What kind of object you want to create
* `metadata` - Data that helps uniquely identify the object, including a `name` string, `UID`, and optional `namespace`
* `spec` - What state you desire for the object
-->
### 必需字段 {#required-fields}
在想要创建的 Kubernetes 对象对应的 `.yaml` 文件中,需要配置如下的字段:
* `apiVersion` - 创建该对象所使用的 Kubernetes API 的版本
* `kind` - 想要创建的对象的类别
* `metadata` - 帮助唯一性标识对象的一些数据,包括一个 `name` 字符串、UID 和可选的 `namespace`
* `spec` - 你所期望的该对象的状态
<!--
The precise format of the object `spec` is different for every Kubernetes object, and contains nested fields specific to that object. The [Kubernetes API Reference](https://kubernetes.io/docs/reference/kubernetes-api/) can help you find the spec format for all of the objects you can create using Kubernetes.
-->
对象 `spec` 的精确格式对每个 Kubernetes 对象来说是不同的,包含了特定于该对象的嵌套字段。
[Kubernetes API 参考](https://kubernetes.io/docs/reference/kubernetes-api/)
能够帮助我们找到任何我们想创建的对象的规约格式。
<!--
For example, see the [`spec` field](/docs/reference/kubernetes-api/workload-resources/pod-v1/#PodSpec)
for the Pod API reference.
For each Pod, the `.spec` field specifies the pod and its desired state (such as the container image name for
each container within that pod).
Another example of an object specification is the
[`spec` field](/docs/reference/kubernetes-api/workload-resources/stateful-set-v1/#StatefulSetSpec)
for the StatefulSet API. For StatefulSet, the `.spec` field specifies the StatefulSet and
its desired state.
Within the `.spec` of a StatefulSet is a [template](/docs/concepts/workloads/pods/#pod-templates)
for Pod objects. That template describes Pods that the StatefulSet controller will create in order to
satisfy the StatefulSet specification.
Different kinds of object can also have different `.status`; again, the API reference pages
detail the structure of that `.status` field, and its content for each different type of object.
-->
例如,参阅 Pod API 参考文档中
[`spec` 字段](/docs/reference/kubernetes-api/workload-resources/pod-v1/#PodSpec)。
对于每个 Pod,其 `.spec` 字段设置了 Pod 及其期望状态(例如 Pod 中每个容器的容器镜像名称)。
另一个对象规约的例子是 StatefulSet API 中的
[`spec` 字段](/docs/reference/kubernetes-api/workload-resources/stateful-set-v1/#StatefulSetSpec)。
对于 StatefulSet 而言,其 `.spec` 字段设置了 StatefulSet 及其期望状态。
在 StatefulSet 的 `.spec` 内,有一个为 Pod 对象提供的[模板](/zh/docs/concepts/workloads/pods/#pod-templates)。该模板描述了 StatefulSet 控制器为了满足 StatefulSet 规约而要创建的 Pod。
不同类型的对象可以由不同的 `.status` 信息。API 参考页面给出了 `.status` 字段的详细结构,
以及针对不同类型 API 对象的具体内容。
## {{% heading "whatsnext" %}}
<!--
* Learn about the most important basic Kubernetes objects, such as [Pod](/docs/concepts/workloads/pods/).
* Learn about [controllers](/docs/concepts/architecture/controller/) in Kubernetes.
* [Using the Kubernetes API](/docs/reference/using-api/) explains some more API concepts.
-->
* 了解最重要的 Kubernetes 基本对象,例如 [Pod](/zh/docs/concepts/workloads/pods/)。
* 了解 Kubernetes 中的[控制器](/zh/docs/concepts/architecture/controller/)。
* [使用 Kubernetes API](/zh/docs/reference/using-api/) 一节解释了一些 API 概念。
@@ -0,0 +1,404 @@
---
title: 标签和选择算符
content_type: concept
weight: 40
---
<!--
reviewers:
- mikedanese
title: Labels and Selectors
content_type: concept
weight: 40
-->
<!-- overview -->
<!--
_Labels_ are key/value pairs that are attached to objects, such as pods.
Labels are intended to be used to specify identifying attributes of objects that are meaningful and relevant to users, but do not directly imply semantics to the core system.
Labels can be used to organize and to select subsets of objects.
Labels can be attached to objects at creation time and subsequently added and modified at any time.
Each object can have a set of key/value labels defined. Each Key must be unique for a given object.
-->
_标签(Labels_ 是附加到 Kubernetes 对象(比如 Pods)上的键值对。
标签旨在用于指定对用户有意义且相关的对象的标识属性,但不直接对核心系统有语义含义。
标签可以用于组织和选择对象的子集。标签可以在创建时附加到对象,随后可以随时添加和修改。
每个对象都可以定义一组键/值标签。每个键对于给定对象必须是唯一的。
```json
"metadata": {
"labels": {
"key1" : "value1",
"key2" : "value2"
}
}
```
<!--
Labels allow for efficient queries and watches and are ideal for use in UIs
and CLIs. Non-identifying information should be recorded using
[annotations](/docs/concepts/overview/working-with-objects/annotations/).
-->
标签能够支持高效的查询和监听操作,对于用户界面和命令行是很理想的。
应使用[注解](/zh/docs/concepts/overview/working-with-objects/annotations/)记录非识别信息。
<!-- body -->
<!--
## Motivation
Labels enable users to map their own organizational structures onto system objects in a loosely coupled fashion, without requiring clients to store these mappings.
-->
## 动机
标签使用户能够以松散耦合的方式将他们自己的组织结构映射到系统对象,而无需客户端存储这些映射。
<!--
Service deployments and batch processing pipelines are often multi-dimensional entities (e.g., multiple partitions or deployments, multiple release tracks, multiple tiers, multiple micro-services per tier). Management often requires cross-cutting operations, which breaks encapsulation of strictly hierarchical representations, especially rigid hierarchies determined by the infrastructure rather than by users.
Example labels:
-->
服务部署和批处理流水线通常是多维实体(例如,多个分区或部署、多个发行序列、多个层,每层多个微服务)。
管理通常需要交叉操作,这打破了严格的层次表示的封装,特别是由基础设施而不是用户确定的严格的层次结构。
示例标签:
* `"release" : "stable"`, `"release" : "canary"`
* `"environment" : "dev"`, `"environment" : "qa"`, `"environment" : "production"`
* `"tier" : "frontend"`, `"tier" : "backend"`, `"tier" : "cache"`
* `"partition" : "customerA"`, `"partition" : "customerB"`
* `"track" : "daily"`, `"track" : "weekly"`
<!--
These are examples of [commonly used labels](/docs/concepts/overview/working-with-objects/common-labels/); you are free to develop your own conventions. Keep in mind that label Key must be unique for a given object.
-->
有一些[常用标签](/zh/docs/concepts/overview/working-with-objects/common-labels/)的例子;你可以任意制定自己的约定。
请记住,标签的 Key 对于给定对象必须是唯一的。
<!--
## Syntax and character set
_Labels_ are key/value pairs. Valid label keys have two segments: an optional prefix and name, separated by a slash (`/`). The name segment is required and must be 63 characters or less, beginning and ending with an alphanumeric character (`[a-z0-9A-Z]`) with dashes (`-`), underscores (`_`), dots (`.`), and alphanumerics between. The prefix is optional. If specified, the prefix must be a DNS subdomain: a series of DNS labels separated by dots (`.`), not longer than 253 characters in total, followed by a slash (`/`).
If the prefix is omitted, the label Key is presumed to be private to the user. Automated system components (e.g. `kube-scheduler`, `kube-controller-manager`, `kube-apiserver`, `kubectl`, or other third-party automation) which add labels to end-user objects must specify a prefix.
The `kubernetes.io/` and `k8s.io/` prefixes are [reserved](/docs/reference/labels-annotations-taints/) for Kubernetes core components.
-->
## 语法和字符集
_标签_ 是键值对。有效的标签键有两个段:可选的前缀和名称,用斜杠(`/`)分隔。
名称段是必需的,必须小于等于 63 个字符,以字母数字字符(`[a-z0-9A-Z]`)开头和结尾,
带有破折号(`-`),下划线(`_`),点( `.`)和之间的字母数字。
前缀是可选的。如果指定,前缀必须是 DNS 子域:由点(`.`)分隔的一系列 DNS 标签,总共不超过 253 个字符,
后跟斜杠(`/`)。
如果省略前缀,则假定标签键对用户是私有的。
向最终用户对象添加标签的自动系统组件(例如 `kube-scheduler``kube-controller-manager`
`kube-apiserver``kubectl` 或其他第三方自动化工具)必须指定前缀。
`kubernetes.io/``k8s.io/` 前缀是为 Kubernetes 核心组件[保留的](/zh/docs/reference/labels-annotations-taints/)。
<!--
Valid label value:
* must be 63 characters or less (can be empty),
* unless empty, must begin and end with an alphanumeric character (`[a-z0-9A-Z]`),
* could contain dashes (`-`), underscores (`_`), dots (`.`), and alphanumerics between.
-->
有效标签值:
* 必须为 63 个字符或更少(可以为空)
* 除非标签值为空,必须以字母数字字符(`[a-z0-9A-Z]`)开头和结尾
* 包含破折号(`-`)、下划线(`_`)、点(`.`)和字母或数字
<!--
## Label selectors
Unlike [names and UIDs](/docs/user-guide/identifiers), labels do not provide uniqueness. In general, we expect many objects to carry the same label(s).
-->
## 标签选择算符 {#label-selectors}
与[名称和 UID](/zh/docs/concepts/overview/working-with-objects/names/) 不同,
标签不支持唯一性。通常,我们希望许多对象携带相同的标签。
<!--
Via a _label selector_, the client/user can identify a set of objects. The label selector is the core grouping primitive in Kubernetes.
-->
通过 _标签选择算符_,客户端/用户可以识别一组对象。标签选择算符是 Kubernetes 中的核心分组原语。
<!--
The API currently supports two types of selectors: _equality-based_ and _set-based_.
A label selector can be made of multiple _requirements_ which are comma-separated. In the case of multiple requirements, all must be satisfied so the comma separator acts as a logical _AND_ (`&&`) operator.
-->
API 目前支持两种类型的选择算符:_基于等值的_ 和 _基于集合的_
标签选择算符可以由逗号分隔的多个 _需求_ 组成。
在多个需求的情况下,必须满足所有要求,因此逗号分隔符充当逻辑 __`&&`)运算符。
<!--
The semantics of empty or non-specified selectors are dependent on the context,
and API types that use selectors should document the validity and meaning of
them.
-->
空标签选择算符或者未指定的选择算符的语义取决于上下文,
支持使用选择算符的 API 类别应该将算符的合法性和含义用文档记录下来。
<!--
For some API types, such as ReplicaSets, the label selectors of two instances must not overlap within a namespace, or the controller can see that as conflicting instructions and fail to determine how many replicas should be present.
-->
{{< note >}}
对于某些 API 类别(例如 ReplicaSet)而言,两个实例的标签选择算符不得在命名空间内重叠,
否则它们的控制器将互相冲突,无法确定应该存在的副本个数。
{{< /note >}}
<!--
For both equality-based and set-based conditions there is no logical _OR_ (`||`) operator. Ensure your filter statements are structured accordingly.
-->
{{< caution >}}
对于基于等值的和基于集合的条件而言,不存在逻辑或(`||`)操作符。
你要确保你的过滤语句按合适的方式组织。
{{< /caution >}}
<!--
### _Equality-based_ requirement
_Equality-_ or _inequality-based_ requirements allow filtering by label keys and values. Matching objects must satisfy all of the specified label constraints, though they may have additional labels as well.
Three kinds of operators are admitted `=`,`==`,`!=`. The first two represent _equality_ (and are simply synonyms), while the latter represents _inequality_. For example:
-->
### _基于等值的_ 需求
_基于等值__基于不等值_ 的需求允许按标签键和值进行过滤。
匹配对象必须满足所有指定的标签约束,尽管它们也可能具有其他标签。
可接受的运算符有 `=``==``!=` 三种。
前两个表示 _相等_(并且只是同义词),而后者表示 _不相等_。例如:
```
environment = production
tier != frontend
```
<!--
The former selects all resources with key equal to `environment` and value equal to `production`.
The latter selects all resources with key equal to `tier` and value distinct from `frontend`, and all resources with no labels with the `tier` key.
One could filter for resources in `production` excluding `frontend` using the comma operator: `environment=production,tier!=frontend`
-->
前者选择所有资源,其键名等于 `environment`,值等于 `production`
后者选择所有资源,其键名等于 `tier`,值不同于 `frontend`,所有资源都没有带有 `tier` 键的标签。
可以使用逗号运算符来过滤 `production` 环境中的非 `frontend` 层资源:`environment=production,tier!=frontend`
<!--
One usage scenario for equality-based label requirement is for Pods to specify
node selection criteria. For example, the sample Pod below selects nodes with
the label "`accelerator=nvidia-tesla-p100`".
-->
基于等值的标签要求的一种使用场景是 Pod 要指定节点选择标准。
例如,下面的示例 Pod 选择带有标签 "`accelerator=nvidia-tesla-p100`"。
```yaml
apiVersion: v1
kind: Pod
metadata:
name: cuda-test
spec:
containers:
- name: cuda-test
image: "k8s.gcr.io/cuda-vector-add:v0.1"
resources:
limits:
nvidia.com/gpu: 1
nodeSelector:
accelerator: nvidia-tesla-p100
```
<!--
### _Set-based_ requirement
_Set-based_ label requirements allow filtering keys according to a set of values. Three kinds of operators are supported: `in`,`notin` and `exists` (only the key identifier). For example:
-->
### _基于集合_ 的需求
_基于集合_ 的标签需求允许你通过一组值来过滤键。
支持三种操作符:`in``notin``exists`(只可以用在键标识符上)。例如:
```
environment in (production, qa)
tier notin (frontend, backend)
partition
!partition
```
<!--
* The first example selects all resources with key equal to `environment` and value equal to `production` or `qa`.
* The second example selects all resources with key equal to `tier` and values other than `frontend` and `backend`, and all resources with no labels with the `tier` key.
* The third example selects all resources including a label with key `partition`; no values are checked.
* The fourth example selects all resources without a label with key `partition`; no values are checked.
Similarly the comma separator acts as an _AND_ operator. So filtering resources with a `partition` key (no matter the value) and with `environment` different than  `qa` can be achieved using `partition,environment notin (qa)`.
-->
* 第一个示例选择了所有键等于 `environment` 并且值等于 `production` 或者 `qa` 的资源。
* 第二个示例选择了所有键等于 `tier` 并且值不等于 `frontend` 或者 `backend` 的资源,以及所有没有 `tier` 键标签的资源。
* 第三个示例选择了所有包含了有 `partition` 标签的资源;没有校验它的值。
* 第四个示例选择了所有没有 `partition` 标签的资源;没有校验它的值。
类似地,逗号分隔符充当 __ 运算符。因此,使用 `partition` 键(无论为何值)和
`environment` 不同于 `qa` 来过滤资源可以使用 `partition, environment notin (qa)` 来实现。
<!--
The _set-based_ label selector is a general form of equality since `environment=production` is equivalent to `environment in (production)`; similarly for `!=` and `notin`.
-->
_基于集合_ 的标签选择算符是相等标签选择算符的一般形式,因为 `environment=production`
等同于 `environment in (production)``!=``notin` 也是类似的。
<!--
_Set-based_ requirements can be mixed with _equality-based_ requirements. For example: `partition in (customerA, customerB),environment!=qa`.
-->
_基于集合_ 的要求可以与基于 _相等_ 的要求混合使用。例如:`partition in (customerA, customerB),environment!=qa`
## API
<!--
### LIST and WATCH filtering
LIST and WATCH operations may specify label selectors to filter the sets of objects returned using a query parameter. Both requirements are permitted (presented here as they would appear in a URL query string):
-->
### LIST 和 WATCH 过滤
LIST 和 WATCH 操作可以使用查询参数指定标签选择算符过滤一组对象。
两种需求都是允许的。(这里显示的是它们出现在 URL 查询字符串中)
<!--
* _equality-based_ requirements: `?labelSelector=environment%3Dproduction,tier%3Dfrontend`
* _set-based_ requirements: `?labelSelector=environment+in+%28production%2Cqa%29%2Ctier+in+%28frontend%29`
-->
* _基于等值_ 的需求:`?labelSelector=environment%3Dproduction,tier%3Dfrontend`
* _基于集合_ 的需求:`?labelSelector=environment+in+%28production%2Cqa%29%2Ctier+in+%28frontend%29`
<!--
Both label selector styles can be used to list or watch resources via a REST client. For example, targeting `apiserver` with `kubectl` and using _equality-based_ one may write:
-->
两种标签选择算符都可以通过 REST 客户端用于 list 或者 watch 资源。
例如,使用 `kubectl` 定位 `apiserver`,可以使用 _基于等值_ 的标签选择算符可以这么写:
```shell
kubectl get pods -l environment=production,tier=frontend
```
<!-- or using _set-based_ requirements: -->
或者使用 _基于集合的_ 需求:
```shell
kubectl get pods -l 'environment in (production),tier in (frontend)'
```
<!--
As already mentioned _set-based_ requirements are more expressive.  For instance, they can implement the _OR_ operator on values:
-->
正如刚才提到的,_基于集合_ 的需求更具有表达力。例如,它们可以实现值的 __ 操作:
```shell
kubectl get pods -l 'environment in (production, qa)'
```
<!-- or restricting negative matching via _exists_ operator: -->
或者通过 _exists_ 运算符限制不匹配:
```shell
kubectl get pods -l 'environment,environment notin (frontend)'
```
<!--
### Set references in API objects
Some Kubernetes objects, such as [`services`](/docs/concepts/services-networking/service/)
and [`replicationcontrollers`](/docs/concepts/workloads/controllers/replicationcontroller/),
also use label selectors to specify sets of other resources, such as
[pods](/docs/concepts/workloads/pods/).
-->
### 在 API 对象中设置引用
一些 Kubernetes 对象,例如 [`services`](/zh/docs/concepts/services-networking/service/)
和 [`replicationcontrollers`](/zh/docs/concepts/workloads/controllers/replicationcontroller/)
也使用了标签选择算符去指定了其他资源的集合,例如
[pods](/zh/docs/concepts/workloads/pods/)。
<!--
#### Service and ReplicationController
The set of pods that a `service` targets is defined with a label selector. Similarly, the population of pods that a `replicationcontroller` should manage is also defined with a label selector.
Labels selectors for both objects are defined in `json` or `yaml` files using maps, and only _equality-based_ requirement selectors are supported:
-->
#### Service 和 ReplicationController
一个 `Service` 指向的一组 Pods 是由标签选择算符定义的。同样,一个 `ReplicationController`
应该管理的 pods 的数量也是由标签选择算符定义的。
两个对象的标签选择算符都是在 `json` 或者 `yaml` 文件中使用映射定义的,并且只支持
_基于等值_ 需求的选择算符:
```json
"selector": {
"component" : "redis",
}
```
<!-- or -->
或者
```yaml
selector:
component: redis
```
<!---
this selector (respectively in `json` or `yaml` format) is equivalent to `component=redis` or `component in (redis)`.
-->
这个选择算符(分别在 `json` 或者 `yaml` 格式中)等价于 `component=redis``component in (redis)`
<!--
#### Resources that support set-based requirements
Newer resources, such as [`Job`](/docs/concepts/jobs/run-to-completion-finite-workloads/), [`Deployment`](/docs/concepts/workloads/controllers/deployment/), [`Replica Set`](/docs/concepts/workloads/controllers/replicaset/), and [`Daemon Set`](/docs/concepts/workloads/controllers/daemonset/), support _set-based_ requirements as well.
-->
#### 支持基于集合需求的资源
比较新的资源,例如 [`Job`](/zh/docs/concepts/workloads/controllers/job/)、
[`Deployment`](/zh/docs/concepts/workloads/controllers/deployment/)、
[`Replica Set`](/zh/docs/concepts/workloads/controllers/replicaset/) 和
[`DaemonSet`](/zh/docs/concepts/workloads/controllers/daemonset/)
也支持 _基于集合的_ 需求。
```yaml
selector:
matchLabels:
component: redis
matchExpressions:
- {key: tier, operator: In, values: [cache]}
- {key: environment, operator: NotIn, values: [dev]}
```
<!--
`matchLabels` is a map of `{key,value}` pairs. A single `{key,value}` in the `matchLabels` map is equivalent to an element of `matchExpressions`, whose `key` field is "key", the `operator` is "In", and the `values` array contains only "value". `matchExpressions` is a list of pod selector requirements. Valid operators include In, NotIn, Exists, and DoesNotExist. The values set must be non-empty in the case of In and NotIn. All of the requirements, from both `matchLabels` and `matchExpressions` are ANDed together - they must all be satisfied in order to match.
-->
`matchLabels` 是由 `{key,value}` 对组成的映射。
`matchLabels` 映射中的单个 `{key,value}` 等同于 `matchExpressions` 的元素,
`key` 字段为 "key"`operator` 为 "In",而 `values` 数组仅包含 "value"。
`matchExpressions` 是 Pod 选择算符需求的列表。
有效的运算符包括 `In``NotIn``Exists``DoesNotExist`
`In``NotIn` 的情况下,设置的值必须是非空的。
来自 `matchLabels``matchExpressions` 的所有要求都按逻辑与的关系组合到一起
-- 它们必须都满足才能匹配。
<!--
#### Selecting sets of nodes
One use case for selecting over labels is to constrain the set of nodes onto which a pod can schedule.
See the documentation on [node selection](/docs/concepts/configuration/assign-pod-node/) for more information.
-->
#### 选择节点集
通过标签进行选择的一个用例是确定节点集,方便 Pod 调度。
有关更多信息,请参阅[选择节点](/zh/docs/concepts/scheduling-eviction/assign-pod-node/)文档。
@@ -0,0 +1,179 @@
---
title: 对象名称和 IDs
content_type: concept
weight: 20
---
<!-- overview -->
<!--
Each object in your cluster has a [_Name_](#names) that is unique for that type of resource.
Every Kubernetes object also has a [_UID_](#uids) that is unique across your whole cluster.
For example, you can only have one Pod named `myapp-1234` within the same [namespace](/docs/concepts/overview/working-with-objects/namespaces/), but you can have one Pod and one Deployment that are each named `myapp-1234`.
-->
集群中的每一个对象都有一个[_名称_](#names)来标识在同类资源中的唯一性。
每个 Kubernetes 对象也有一个 [_UID_](#uids) 来标识在整个集群中的唯一性。
比如,在同一个[名字空间](/zh/docs/concepts/overview/working-with-objects/namespaces/)
中有一个名为 `myapp-1234` 的 Pod,但是可以命名一个 Pod 和一个 Deployment 同为 `myapp-1234`
<!--
For non-unique user-provided attributes, Kubernetes provides [labels](/docs/user-guide/labels) and [annotations](/docs/concepts/overview/working-with-objects/annotations/).
-->
对于用户提供的非唯一性的属性,Kubernetes 提供了
[标签(Labels](/zh/docs/concepts/working-with-objects/labels)和
[注解(Annotation](/zh/docs/concepts/overview/working-with-objects/annotations/)机制。
<!-- body -->
<!--
## Names
-->
## 名称 {#names}
{{< glossary_definition term_id="name" length="all" >}}
{{< note >}}
<!--
In cases when objects represent a physical entity, like a Node representing a physical host, when the host is re-created under the same name without deleting and re-creating the Node, Kubernetes treats the new host as the old one, which may lead to inconsistencies.
-->
当对象所代表的是一个物理实体(例如代表一台物理主机的 Node)时,
如果在 Node 对象未被删除并重建的条件下,重新创建了同名的物理主机,
则 Kubernetes 会将新的主机看作是老的主机,这可能会带来某种不一致性。
{{< /note >}}
<!--
Below are four types of commonly used name constraints for resources.
-->
以下是比较常见的四种资源命名约束。
<!--
### DNS Subdomain Names
Most resource types require a name that can be used as a DNS subdomain name
as defined in [RFC 1123](https://tools.ietf.org/html/rfc1123).
This means the name must:
- contain no more than 253 characters
- contain only lowercase alphanumeric characters, '-' or '.'
- start with an alphanumeric character
- end with an alphanumeric character
-->
### DNS 子域名 {#dns-subdomain-names}
很多资源类型需要可以用作 DNS 子域名的名称。
DNS 子域名的定义可参见 [RFC 1123](https://tools.ietf.org/html/rfc1123)。
这一要求意味着名称必须满足如下规则:
- 不能超过 253 个字符
- 只能包含小写字母、数字,以及 '-' 和 '.'
- 必须以字母数字开头
- 必须以字母数字结尾
<!--
### DNS Label Names
Some resource types require their names to follow the DNS
label standard as defined in [RFC 1123](https://tools.ietf.org/html/rfc1123).
This means the name must:
- contain at most 63 characters
- contain only lowercase alphanumeric characters or '-'
- start with an alphanumeric character
- end with an alphanumeric character
-->
### RFC 1123 标签名 {#dns-label-names}
某些资源类型需要其名称遵循 [RFC 1123](https://tools.ietf.org/html/rfc1123)
所定义的 DNS 标签标准。也就是命名必须满足如下规则:
- 最多 63 个字符
- 只能包含小写字母、数字,以及 '-'
- 必须以字母数字开头
- 必须以字母数字结尾
<!--
### RFC 1035 Label Names
Some resource types require their names to follow the DNS
label standard as defined in [RFC 1035](https://tools.ietf.org/html/rfc1035).
This means the name must:
- contain at most 63 characters
- contain only lowercase alphanumeric characters or '-'
- start with an alphabetic character
- end with an alphanumeric character
-->
### RFC 1035 标签名 {#rfc-1035-label-names}
某些资源类型需要其名称遵循 [RFC 1035](https://tools.ietf.org/html/rfc1035)
所定义的 DNS 标签标准。也就是命名必须满足如下规则:
- 最多 63 个字符
- 只能包含小写字母、数字,以及 '-'
- 必须以字母开头
- 必须以字母数字结尾
<!--
### Path Segment Names
Some resource types require their names to be able to be safely encoded as a
path segment. In other words, the name may not be "." or ".." and the name may
not contain "/" or "%".
-->
### 路径分段名称 {#path-segment-names}
某些资源类型要求名称能被安全地用作路径中的片段。
换句话说,其名称不能是 `.``..`,也不可以包含 `/``%` 这些字符。
<!--
Heres an example manifest for a Pod named `nginx-demo`.
-->
下面是一个名为 `nginx-demo` 的 Pod 的配置清单:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-demo
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
```
<!--
Some resource types have additional restrictions on their names.
-->
{{< note >}}
某些资源类型可能具有额外的命名约束。
{{< /note >}}
## UIDs
{{< glossary_definition term_id="uid" length="all" >}}
<!--
Kubernetes UIDs are universally unique identifiers (also known as UUIDs).
UUIDs are standardized as ISO/IEC 9834-8 and as ITU-T X.667.
-->
Kubernetes UIDs 是全局唯一标识符(也叫 UUIDs)。
UUIDs 是标准化的,见 ISO/IEC 9834-8 和 ITU-T X.667。
## {{% heading "whatsnext" %}}
<!--
* Read about [labels](/docs/concepts/overview/working-with-objects/labels/) in Kubernetes.
* See the [Identifiers and Names in Kubernetes](https://git.k8s.io/community/contributors/design-proposals/architecture/identifiers.md) design document.
-->
* 进一步了解 Kubernetes [标签](/zh/docs/concepts/overview/working-with-objects/labels/)
* 参阅 [Kubernetes 标识符和名称](https://git.k8s.io/community/contributors/design-proposals/architecture/identifiers.md)的设计文档
@@ -0,0 +1,268 @@
---
title: 名字空间
content_type: concept
weight: 30
---
<!--
reviewers:
- derekwaynecarr
- mikedanese
- thockin
title: Namespaces
content_type: concept
weight: 30
-->
<!-- overview -->
<!--
In Kubernetes, _namespaces_ provides a mechanism for isolating groups of resources within a single cluster. Names of resources need to be unique within a namespace, but not across namespaces. Namespace-based scoping is applicable only for namespaced objects _(e.g. Deployments, Services, etc)_ and not for cluster-wide objects _(e.g. StorageClass, Nodes, PersistentVolumes, etc)_.
-->
在 Kubernetes 中,“名字空间(Namespace)”提供一种机制,将同一集群中的资源划分为相互隔离的组。
同一名字空间内的资源名称要唯一,但跨名字空间时没有这个要求。
名字空间作用域仅针对带有名字空间的对象,例如 Deployment、Service 等,
这种作用域对集群访问的对象不适用,例如 StorageClass、Node、PersistentVolume 等。
<!-- body -->
<!--
## When to Use Multiple Namespaces
-->
## 何时使用多个名字空间
<!--
Namespaces are intended for use in environments with many users spread across multiple
teams, or projects. For clusters with a few to tens of users, you should not
need to create or think about namespaces at all. Start using namespaces when you
need the features they provide.
-->
名字空间适用于存在很多跨多个团队或项目的用户的场景。对于只有几到几十个用户的集群,根本不需要创建或考虑名字空间。当需要名称空间提供的功能时,请开始使用它们。
<!--
Namespaces provide a scope for names. Names of resources need to be unique within a namespace,
but not across namespaces. Namespaces can not be nested inside one another and each Kubernetes
resource can only be in one namespace.
-->
名字空间为名称提供了一个范围。资源的名称需要在名字空间内是唯一的,但不能跨名字空间。
名字空间不能相互嵌套,每个 Kubernetes 资源只能在一个名字空间中。
<!--
Namespaces are a way to divide cluster resources between multiple users (via [resource quota](/docs/concepts/policy/resource-quotas/)).
-->
名字空间是在多个用户之间划分集群资源的一种方法(通过[资源配额](/zh/docs/concepts/policy/resource-quotas/))。
<!--
It is not necessary to use multiple namespaces to separate slightly different
resources, such as different versions of the same software: use
{{< glossary_tooltip text="labels" term_id="label" >}} to distinguish
resources within the same namespace.
-->
不必使用多个名字空间来分隔仅仅轻微不同的资源,例如同一软件的不同版本:
应该使用{{< glossary_tooltip text="标签" term_id="label" >}}
来区分同一名字空间中的不同资源。
<!--
## Working with Namespaces
Creation and deletion of namespaces are described in the [Admin Guide documentation
for namespaces](/docs/tasks/administer-cluster/namespaces/).
-->
## 使用名字空间
名字空间的创建和删除在[名字空间的管理指南文档](/zh/docs/tasks/administer-cluster/namespaces/)描述。
<!--
Avoid creating namespaces with the prefix `kube-`, since it is reserved for Kubernetes system namespaces.
-->
{{< note >}}
避免使用前缀 `kube-` 创建名字空间,因为它是为 Kubernetes 系统名字空间保留的。
{{< /note >}}
<!--
### Viewing namespaces
You can list the current namespaces in a cluster using:
-->
### 查看名字空间
你可以使用以下命令列出集群中现存的名字空间:
```shell
kubectl get namespace
```
```
NAME STATUS AGE
default Active 1d
kube-node-lease Active 1d
kube-system Active 1d
kube-public Active 1d
```
<!--
Kubernetes starts with four initial namespaces:
* `default` The default namespace for objects with no other namespace
* `kube-system` The namespace for objects created by the Kubernetes system
* `kube-public` This namespace is created automatically and is readable by all users (including those not authenticated). This namespace is mostly reserved for cluster usage, in case that some resources should be visible and readable publicly throughout the whole cluster. The public aspect of this namespace is only a convention, not a requirement.
* `kube-node-lease` This namespace holds [Lease](/docs/reference/kubernetes-api/cluster-resources/lease-v1/)
objects associated with each node. Node leases allow the kubelet to send
[heartbeats](/docs/concepts/architecture/nodes/#heartbeats) so that the control plane
can detect node failure.
-->
Kubernetes 会创建四个初始名字空间:
* `default` 没有指明使用其它名字空间的对象所使用的默认名字空间
* `kube-system` Kubernetes 系统创建对象所使用的名字空间
* `kube-public` 这个名字空间是自动创建的,所有用户(包括未经过身份验证的用户)都可以读取它。
这个名字空间主要用于集群使用,以防某些资源在整个集群中应该是可见和可读的。
这个名字空间的公共方面只是一种约定,而不是要求。
* `kube-node-lease` 此名字空间用于与各个节点相关的
[租约(Lease](/docs/reference/kubernetes-api/cluster-resources/lease-v1/)对象。
节点租期允许 kubelet 发送[心跳](/zh/docs/concepts/architecture/nodes/#heartbeats),由此控制面能够检测到节点故障。
<!--
### Setting the namespace for a request
To set the namespace for a current request, use the `-namespace` flag.
For example:
-->
### 为请求设置名字空间
要为当前请求设置名字空间,请使用 `--namespace` 参数。
例如:
```shell
kubectl run nginx --image=nginx --namespace=<名字空间名称>
kubectl get pods --namespace=<名字空间名称>
```
<!--
### Setting the namespace preference
You can permanently save the namespace for all subsequent kubectl commands in that
context.
-->
### 设置名字空间偏好
你可以永久保存名字空间,以用于对应上下文中所有后续 kubectl 命令。
```shell
kubectl config set-context --current --namespace=<名字空间名称>
# 验证
kubectl config view | grep namespace:
```
<!--
## Namespaces and DNS
When you create a [Service](/docs/user-guide/services), it creates a corresponding [DNS entry](/docs/concepts/services-networking/dns-pod-service/).
-->
## 名字空间和 DNS
当你创建一个[服务](/zh/docs/concepts/services-networking/service/)时,
Kubernetes 会创建一个相应的 [DNS 条目](/zh/docs/concepts/services-networking/dns-pod-service/)。
<!--
This entry is of the form `<service-name>.<namespace-name>.svc.cluster.local`, which means
that if a container only uses `<service-name>`, it will resolve to the service which
is local to a namespace. This is useful for using the same configuration across
multiple namespaces such as Development, Staging and Production. If you want to reach
across namespaces, you need to use the fully qualified domain name (FQDN).
-->
该条目的形式是 `<服务名称>.<名字空间名称>.svc.cluster.local`,这意味着如果容器只使用
`<服务名称>`,它将被解析到本地名字空间的服务。这对于跨多个名字空间(如开发、分级和生产)
使用相同的配置非常有用。如果你希望跨名字空间访问,则需要使用完全限定域名(FQDN)。
<!--
As a result, all namespace names must be valid
[RFC 1123 DNS labels](/docs/concepts/overview/working-with-objects/names/#dns-label-names).
-->
因此,所有的名字空间名称都必须是合法的
[RFC 1123 DNS 标签](/zh/docs/concepts/overview/working-with-objects/names/#dns-label-names)。
{{< warning >}}
<!--
By creating namespaces with the same name as [public top-level
domains](https://data.iana.org/TLD/tlds-alpha-by-domain.txt), Services in these
namespaces can have short DNS names that overlap with public DNS records.
Workloads from any namespace performing a DNS lookup without a [trailing dot](https://datatracker.ietf.org/doc/html/rfc1034#page-8) will
be redirected to those services, taking precedence over public DNS.
-->
通过创建与[公共顶级域名](https://data.iana.org/TLD/tlds-alpha-by-domain.txt)
同名的名字空间,这些名字空间中的服务可以拥有与公共 DNS 记录重叠的、较短的 DNS 名称。
所有名字空间中的负载在执行 DNS 查找时,如果查找的名称没有
[尾部句点](https://datatracker.ietf.org/doc/html/rfc1034#page-8)
就会被重定向到这些服务上,因此呈现出比公共 DNS 更高的优先序。
<!--
To mitigate this, limit privileges for creating namespaces to trusted users. If
required, you could additionally configure third-party security controls, such
as [admission
webhooks](/docs/reference/access-authn-authz/extensible-admission-controllers/),
to block creating any namespace with the name of [public
TLDs](https://data.iana.org/TLD/tlds-alpha-by-domain.txt).
-->
为了缓解这类问题,需要将创建名字空间的权限授予可信的用户。
如果需要,你可以额外部署第三方的安全控制机制,例如以
[准入 Webhook](/zh/docs/reference/access-authn-authz/extensible-admission-controllers/)
的形式,阻止用户创建与公共 [TLD](https://data.iana.org/TLD/tlds-alpha-by-domain.txt)
同名的名字空间。
{{< /warning >}}
<!--
## Not All Objects are in a Namespace
-->
## 并非所有对象都在名字空间中
<!--
Most Kubernetes resources (e.g. pods, services, replication controllers, and others) are
in some namespaces. However namespace resources are not themselves in a namespace.
And low-level resources, such as [nodes](/docs/concepts/architecture/nodes/) and
persistentVolumes, are not in any namespace.
-->
大多数 kubernetes 资源(例如 Pod、Service、副本控制器等)都位于某些名字空间中。
但是名字空间资源本身并不在名字空间中。而且底层资源,例如
[节点](/zh/docs/concepts/architecture/nodes/)和持久化卷不属于任何名字空间。
<!--
To see which Kubernetes resources are and aren't in a namespace:
-->
查看哪些 Kubernetes 资源在名字空间中,哪些不在名字空间中:
```shell
# 位于名字空间中的资源
kubectl api-resources --namespaced=true
# 不在名字空间中的资源
kubectl api-resources --namespaced=false
```
<!--
## Automatic labelling
-->
## 自动打标签 {#automatic-labelling}
{{< feature-state state="beta" for_k8s_version="1.21" >}}
<!--
The Kubernetes control plane sets an immutable {{< glossary_tooltip text="label" term_id="label" >}}
`kubernetes.io/metadata.name` on all namespaces, provided that the `NamespaceDefaultLabelName`
[feature gate](/docs/reference/command-line-tools-reference/feature-gates/) is enabled.
The value of the label is the namespace name.
-->
Kubernetes 控制面会为所有名字空间设置一个不可变更的
{{< glossary_tooltip text="标签" term_id="label" >}}
`kubernetes.io/metadata.name`,只要 `NamespaceDefaultLabelName` 这一
[特性门控](/zh/docs/reference/command-line-tools-reference/feature-gates/)
被启用。标签的值是名字空间的名称。
## {{% heading "whatsnext" %}}
<!--
* Learn more about [creating a new namespace](/docs/tasks/administer-cluster/namespaces/#creating-a-new-namespace).
* Learn more about [deleting a namespace](/docs/tasks/administer-cluster/namespaces/#deleting-a-namespace).
-->
* 进一步了解[建立新的名字空间](/zh/docs/tasks/administer-cluster/namespaces/#creating-a-new-namespace)。
* 进一步了解[删除名字空间](/zh/docs/tasks/administer-cluster/namespaces/#deleting-a-namespace)。
@@ -0,0 +1,335 @@
---
title: Kubernetes 对象管理
content_type: concept
weight: 15
---
<!-- overview -->
<!--
The `kubectl` command-line tool supports several different ways to create and manage
Kubernetes objects. This document provides an overview of the different
approaches. Read the [Kubectl book](https://kubectl.docs.kubernetes.io) for
details of managing objects by Kubectl.
-->
`kubectl` 命令行工具支持多种不同的方式来创建和管理 Kubernetes 对象。
本文档概述了不同的方法。
阅读 [Kubectl book](https://kubectl.docs.kubernetes.io) 来了解 kubectl
管理对象的详细信息。
<!-- body -->
<!--
## Management techniques
-->
## 管理技巧
{{< warning >}}
<!--
A Kubernetes object should be managed using only one technique. Mixing
and matching techniques for the same object results in undefined behavior.
-->
应该只使用一种技术来管理 Kubernetes 对象。混合和匹配技术作用在同一对象上将导致未定义行为。
{{< /warning >}}
<!--
| Management technique | Operates on |Recommended environment | Supported writers | Learning curve |
|----------------------------------|----------------------|------------------------|--------------------|----------------|
| Imperative commands | Live objects | Development projects | 1+ | Lowest |
| Imperative object configuration | Individual files | Production projects | 1 | Moderate |
| Declarative object configuration | Directories of files | Production projects | 1+ | Highest |
-->
| 管理技术 | 作用于 | 建议的环境 | 支持的写者 | 学习难度 |
|----------------|----------|------------|------------|----------|
| 指令式命令 | 活跃对象 | 开发项目 | 1+ | 最低 |
| 指令式对象配置 | 单个文件 | 生产项目 | 1 | 中等 |
| 声明式对象配置 | 文件目录 | 生产项目 | 1+ | 最高 |
<!--
## Imperative commands
-->
## 指令式命令
<!--
When using imperative commands, a user operates directly on live objects
in a cluster. The user provides operations to
the `kubectl` command as arguments or flags.
-->
使用指令式命令时,用户可以在集群中的活动对象上进行操作。用户将操作传给
`kubectl` 命令作为参数或标志。
<!--
This is the recommended way to get started or to run a one-off task in
a cluster. Because this technique operates directly on live
objects, it provides no history of previous configurations.
-->
这是开始或者在集群中运行一次性任务的推荐方法。因为这个技术直接在活跃对象
上操作,所以它不提供以前配置的历史记录。
<!--
### Examples
-->
### 例子
<!--
Run an instance of the nginx container by creating a Deployment object:
-->
通过创建 Deployment 对象来运行 nginx 容器的实例:
```sh
kubectl create deployment nginx --image nginx
```
<!--
### Trade-offs
-->
### 权衡
<!--
Advantages compared to object configuration:
- Commands are simple, easy to learn and easy to remember.
- Commands require only a single step to make changes to the cluster.
-->
与对象配置相比的优点:
- 命令简单,易学且易于记忆。
- 命令仅需一步即可对集群进行更改。
<!--
Disadvantages compared to object configuration:
- Commands do not integrate with change review processes.
- Commands do not provide an audit trail associated with changes.
- Commands do not provide a source of records except for what is live.
- Commands do not provide a template for creating new objects.
-->
与对象配置相比的缺点:
- 命令不与变更审查流程集成。
- 命令不提供与更改关联的审核跟踪。
- 除了实时内容外,命令不提供记录源。
- 命令不提供用于创建新对象的模板。
<!--
## Imperative object configuration
-->
## 指令式对象配置
<!--
In imperative object configuration, the kubectl command specifies the
operation (create, replace, etc.), optional flags and at least one file
name. The file specified must contain a full definition of the object
in YAML or JSON format.
-->
在指令式对象配置中,kubectl 命令指定操作(创建,替换等),可选标志和
至少一个文件名。指定的文件必须包含 YAML 或 JSON 格式的对象的完整定义。
<!--
See the [API reference](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/)
for more details on object definitions.
-->
有关对象定义的详细信息,请查看
[API 参考](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/)。
{{< warning >}}
<!--
The imperative `replace` command replaces the existing
spec with the newly provided one, dropping all changes to the object missing from
the configuration file. This approach should not be used with resource
types whose specs are updated independently of the configuration file.
Services of type `LoadBalancer`, for example, have their `externalIPs` field updated
independently from the configuration by the cluster.
-->
`replace` 指令式命令将现有规范替换为新提供的规范,并放弃对配置文件中
缺少的对象的所有更改。此方法不应与对象规约被独立于配置文件进行更新的
资源类型一起使用。比如类型为 `LoadBalancer` 的服务,它的 `externalIPs`
字段就是独立于集群配置进行更新。
{{< /warning >}}
<!--
### Examples
Create the objects defined in a configuration file:
-->
### 例子
创建配置文件中定义的对象:
```sh
kubectl create -f nginx.yaml
```
<!--
Delete the objects defined in two configuration files:
-->
删除两个配置文件中定义的对象:
```sh
kubectl delete -f nginx.yaml -f redis.yaml
```
<!--
Update the objects defined in a configuration file by overwriting
the live configuration:
-->
通过覆盖活动配置来更新配置文件中定义的对象:
```sh
kubectl replace -f nginx.yaml
```
<!--
### Trade-offs
-->
### 权衡
<!--
Advantages compared to imperative commands:
- Object configuration can be stored in a source control system such as Git.
- Object configuration can integrate with processes such as reviewing changes before push and audit trails.
- Object configuration provides a template for creating new objects.
-->
与指令式命令相比的优点:
- 对象配置可以存储在源控制系统中,比如 Git。
- 对象配置可以与流程集成,例如在推送和审计之前检查更新。
- 对象配置提供了用于创建新对象的模板。
<!--
Disadvantages compared to imperative commands:
- Object configuration requires basic understanding of the object schema.
- Object configuration requires the additional step of writing a YAML file.
-->
与指令式命令相比的缺点:
- 对象配置需要对对象架构有基本的了解。
- 对象配置需要额外的步骤来编写 YAML 文件。
<!--
Advantages compared to declarative object configuration:
- Imperative object configuration behavior is simpler and easier to understand.
- As of Kubernetes version 1.5, imperative object configuration is more mature.
-->
与声明式对象配置相比的优点:
- 指令式对象配置行为更加简单易懂。
- 从 Kubernetes 1.5 版本开始,指令对象配置更加成熟。
<!--
Disadvantages compared to declarative object configuration:
- Imperative object configuration works best on files, not directories.
- Updates to live objects must be reflected in configuration files, or they will be lost during the next replacement.
-->
与声明式对象配置相比的缺点:
- 指令式对象配置更适合文件,而非目录。
- 对活动对象的更新必须反映在配置文件中,否则会在下一次替换时丢失。
<!--
## Declarative object configuration
-->
## 声明式对象配置
<!--
When using declarative object configuration, a user operates on object
configuration files stored locally, however the user does not define the
operations to be taken on the files. Create, update, and delete operations
are automatically detected per-object by `kubectl`. This enables working on
directories, where different operations might be needed for different objects.
-->
使用声明式对象配置时,用户对本地存储的对象配置文件进行操作,但是用户
未定义要对该文件执行的操作。
`kubectl` 会自动检测每个文件的创建、更新和删除操作。
这使得配置可以在目录上工作,根据目录中配置文件对不同的对象执行不同的操作。
{{< note >}}
<!--
Declarative object configuration retains changes made by other
writers, even if the changes are not merged back to the object configuration file.
This is possible by using the `patch` API operation to write only
observed differences, instead of using the `replace`
API operation to replace the entire object configuration.
-->
声明式对象配置保留其他编写者所做的修改,即使这些更改并未合并到对象配置文件中。
可以通过使用 `patch` API 操作仅写入观察到的差异,而不是使用 `replace` API
操作来替换整个对象配置来实现。
{{< /note >}}
<!--
### Examples
-->
### 例子
<!--
Process all object configuration files in the `configs` directory, and create or
patch the live objects. You can first `diff` to see what changes are going to be
made, and then apply:
-->
处理 `configs` 目录中的所有对象配置文件,创建并更新活跃对象。
可以首先使用 `diff` 子命令查看将要进行的更改,然后在进行应用:
```sh
kubectl diff -f configs/
kubectl apply -f configs/
```
<!--
Recursively process directories:
-->
递归处理目录:
```sh
kubectl diff -R -f configs/
kubectl apply -R -f configs/
```
<!--
### Trade-offs
Advantages compared to imperative object configuration:
- Changes made directly to live objects are retained, even if they are not merged back into the configuration files.
- Declarative object configuration has better support for operating on directories and automatically detecting operation types (create, patch, delete) per-object.
-->
### 权衡
与指令式对象配置相比的优点:
- 对活动对象所做的更改即使未合并到配置文件中,也会被保留下来。
- 声明性对象配置更好地支持对目录进行操作并自动检测每个文件的操作类型(创建,修补,删除)。
<!--
Disadvantages compared to imperative object configuration:
- Declarative object configuration is harder to debug and understand results when they are unexpected.
- Partial updates using diffs create complex merge and patch operations.
-->
与指令式对象配置相比的缺点:
- 声明式对象配置难于调试并且出现异常时结果难以理解。
- 使用 diff 产生的部分更新会创建复杂的合并和补丁操作。
## {{% heading "whatsnext" %}}
<!--
- [Managing Kubernetes Objects Using Imperative Commands](/docs/tasks/manage-kubernetes-objects/imperative-command/)
- [Managing Kubernetes Objects Using Object Configuration (Imperative)](/docs/tasks/manage-kubernetes-objects/imperative-config/)
- [Managing Kubernetes Objects Using Object Configuration (Declarative)](/docs/tasks/manage-kubernetes-objects/declarative-config/)
- [Managing Kubernetes Objects Using Kustomize (Declarative)](/docs/tasks/manage-kubernetes-objects/kustomization/)
- [Kubectl Command Reference](/docs/reference/generated/kubectl/kubectl-commands/)
- [Kubectl Book](https://kubectl.docs.kubernetes.io)
- [Kubernetes API Reference](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/)
-->
- [使用指令式命令管理 Kubernetes 对象](/zh/docs/tasks/manage-kubernetes-objects/imperative-command/)
- [使用对象配置管理 Kubernetes 对象(指令式)](/zh/docs/tasks/manage-kubernetes-objects/imperative-config/)
- [使用对象配置管理 Kubernetes 对象(声明式)](/zh/docs/tasks/manage-kubernetes-objects/declarative-config/)
- [使用 Kustomize(声明式)管理 Kubernetes 对象](/zh/docs/tasks/manage-kubernetes-objects/kustomization/)
- [Kubectl 命令参考](/docs/reference/generated/kubectl/kubectl-commands/)
- [Kubectl Book](https://kubectl.docs.kubernetes.io)
- [Kubernetes API 参考](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/)
@@ -0,0 +1,169 @@
---
title: 属主与附属
content_type: concept
weight: 60
---
<!--
title: Owners and Dependents
content_type: concept
weight: 60
-->
<!-- overview -->
<!--
In Kubernetes, some objects are *owners* of other objects. For example, a
{{<glossary_tooltip text="ReplicaSet" term_id="replica-set">}} is the owner of a set of Pods. These owned objects are *dependents*
of their owner.
-->
在 Kubernetes 中,一些对象是其他对象的“属主(Owner)”。
例如,{{<glossary_tooltip text="ReplicaSet" term_id="replica-set">}} 是一组 Pod 的属主。
具有属主的对象是属主的“附属(Dependent)”。
<!--
Ownership is different from the [labels and selectors](/docs/concepts/overview/working-with-objects/labels/)
mechanism that some resources also use. For example, consider a Service that
creates `EndpointSlice` objects. The Service uses labels to allow the control plane to
determine which `EndpointSlice` objects are used for that Service. In addition
to the labels, each `EndpointSlice` that is managed on behalf of a Service has
an owner reference. Owner references help different parts of Kubernetes avoid
interfering with objects they dont control.
-->
属主关系不同于一些资源使用的[标签和选择算符](/zh/docs/concepts/overview/working-with-objects/labels/)机制。
例如,有一个创建 `EndpointSlice` 对象的 Service
该 Service 使用标签来让控制平面确定,哪些 `EndpointSlice` 对象属于该 Service。
除开标签,每个代表 Service 所管理的 `EndpointSlice` 都有一个属主引用。
属主引用避免 Kubernetes 的不同部分干扰到不受它们控制的对象。
<!--
## Owner references in object specifications
Dependent objects have a `metadata.ownerReferences` field that references their
owner object. A valid owner reference consists of the object name and a UID
within the same namespace as the dependent object. Kubernetes sets the value of
this field automatically for objects that are dependents of other objects like
ReplicaSets, DaemonSets, Deployments, Jobs and CronJobs, and ReplicationControllers.
You can also configure these relationships manually by changing the value of
this field. However, you usually don't need to and can allow Kubernetes to
automatically manage the relationships.
-->
## 对象规约中的属主引用 {#owner-references-in-object-specifications}
附属对象有一个 `metadata.ownerReferences` 字段,用于引用其属主对象。
一个有效的属主引用,包含与附属对象同在一个命名空间下的对象名称和一个 UID。
Kubernetes 自动为一些对象的附属资源设置属主引用的值,
这些对象包含 ReplicaSet、DaemonSet、Deployment、Job、CronJob、ReplicationController 等。
你也可以通过改变这个字段的值,来手动配置这些关系。
然而,通常不需要这么做,你可以让 Kubernetes 自动管理附属关系。
<!--
Dependent objects also have an `ownerReferences.blockOwnerDeletion` field that
takes a boolean value and controls whether specific dependents can block garbage
collection from deleting their owner object. Kubernetes automatically sets this
field to `true` if a {{<glossary_tooltip text="controller" term_id="controller">}}
(for example, the Deployment controller) sets the value of the
`metadata.ownerReferences` field. You can also set the value of the
`blockOwnerDeletion` field manually to control which dependents block garbage
collection.
A Kubernetes admission controller controls user access to change this field for
dependent resources, based on the delete permissions of the owner. This control
prevents unauthorized users from delaying owner object deletion.
-->
附属对象还有一个 `ownerReferences.blockOwnerDeletion` 字段,该字段使用布尔值,
用于控制特定的附属对象是否可以阻止垃圾收集删除其属主对象。
如果{{<glossary_tooltip text="控制器" term_id="controller">}}(例如 Deployment 控制器)
设置了 `metadata.ownerReferences` 字段的值,Kubernetes 会自动设置
`blockOwnerDeletion` 的值为 `true`
你也可以手动设置 `blockOwnerDeletion` 字段的值,以控制哪些附属对象会阻止垃圾收集。
{{< note >}}
<!--
Cross-namespace owner references are disallowed by design.
Namespaced dependents can specify cluster-scoped or namespaced owners.
A namespaced owner **must** exist in the same namespace as the dependent.
If it does not, the owner reference is treated as absent, and the dependent
is subject to deletion once all owners are verified absent.
Cluster-scoped dependents can only specify cluster-scoped owners.
In v1.20+, if a cluster-scoped dependent specifies a namespaced kind as an owner,
it is treated as having an unresolvable owner reference, and is not able to be garbage collected.
In v1.20+, if the garbage collector detects an invalid cross-namespace `ownerReference`,
or a cluster-scoped dependent with an `ownerReference` referencing a namespaced kind, a warning Event
with a reason of `OwnerRefInvalidNamespace` and an `involvedObject` of the invalid dependent is reported.
You can check for that kind of Event by running
`kubectl get events -A --field-selector=reason=OwnerRefInvalidNamespace`.
-->
根据设计,kubernetes 不允许跨名字空间指定属主。
名字空间范围的附属可以指定集群范围的或者名字空间范围的属主。
名字空间范围的属主**必须**和该附属处于相同的名字空间。
如果名字空间范围的属主和附属不在相同的名字空间,那么该属主引用就会被认为是缺失的,
并且当附属的所有属主引用都被确认不再存在之后,该附属就会被删除。
集群范围的附属只能指定集群范围的属主。
在 v1.20+ 版本,如果一个集群范围的附属指定了一个名字空间范围类型的属主,
那么该附属就会被认为是拥有一个不可解析的属主引用,并且它不能够被垃圾回收。
在 v1.20+ 版本,如果垃圾收集器检测到无效的跨名字空间的属主引用,
或者一个集群范围的附属指定了一个名字空间范围类型的属主,
那么它就会报告一个警告事件。该事件的原因是 `OwnerRefInvalidNamespace`
`involvedObject` 属性中包含无效的附属。
你可以运行 `kubectl get events -A --field-selector=reason=OwnerRefInvalidNamespace`
来获取该类型的事件。
{{< /note >}}
<!--
## Ownership and finalizers
When you tell Kubernetes to delete a resource, the API server allows the
managing controller to process any [finalizer rules](/docs/concepts/overview/working-with-objects/finalizers/)
for the resource. {{<glossary_tooltip text="Finalizers" term_id="finalizer">}}
prevent accidental deletion of resources your cluster may still need to function
correctly. For example, if you try to delete a `PersistentVolume` that is still
in use by a Pod, the deletion does not happen immediately because the
`PersistentVolume` has the `kubernetes.io/pv-protection` finalizer on it.
Instead, the volume remains in the `Terminating` status until Kubernetes clears
the finalizer, which only happens after the `PersistentVolume` is no longer
bound to a Pod.
-->
## 属主关系与 Finalizer {#ownership-and-finalizers}
当你告诉 Kubernetes 删除一个资源,API 服务器允许管理控制器处理该资源的任何
[Finalizer 规则](/zh/docs/concepts/overview/working-with-objects/finalizers/)。
{{<glossary_tooltip text="Finalizer" term_id="finalizer">}}
防止意外删除你的集群所依赖的、用于正常运作的资源。
例如,如果你试图删除一个仍被 Pod 使用的 `PersistentVolume`,该资源不会被立即删除,
因为 `PersistentVolume``kubernetes.io/pv-protection` Finalizer。
相反,它将进入 `Terminating` 状态,直到 Kubernetes 清除这个 Finalizer
而这种情况只会发生在 `PersistentVolume` 不再被挂载到 Pod 上时。
<!--
Kubernetes also adds finalizers to an owner resource when you use either
[foreground or orphan cascading deletion](/docs/concepts/architecture/garbage-collection/#cascading-deletion).
In foreground deletion, it adds the `foreground` finalizer so that the
controller must delete dependent resources that also have
`ownerReferences.blockOwnerDeletion=true` before it deletes the owner. If you
specify an orphan deletion policy, Kubernetes adds the `orphan` finalizer so
that the controller ignores dependent resources after it deletes the owner
object.
-->
当你使用[前台或孤立级联删除](/zh/docs/concepts/architecture/garbage-collection/#cascading-deletion)时,
Kubernetes 也会向属主资源添加 Finalizer。
在前台删除中,会添加 `foreground` Finalizer,这样控制器必须在删除了拥有
`ownerReferences.blockOwnerDeletion=true` 的附属资源后,才能删除属主对象。
如果你指定了孤立删除策略,Kubernetes 会添加 `orphan` Finalizer
这样控制器在删除属主对象后,会忽略附属资源。
## {{% heading "whatsnext" %}}
<!--
* Learn more about [Kubernetes finalizers](/docs/concepts/overview/working-with-objects/finalizers/).
* Learn about [garbage collection](/docs/concepts/architecture/garbage-collection).
* Read the API reference for [object metadata](/docs/reference/kubernetes-api/common-definitions/object-meta/#System).
-->
* 了解更多关于 [Kubernetes Finalizer](/zh/docs/concepts/overview/working-with-objects/finalizers/)。
* 了解关于[垃圾收集](/zh/docs/concepts/architecture/garbage-collection)。
* 阅读[对象元数据](/docs/reference/kubernetes-api/common-definitions/object-meta/#System)的 API 参考文档。