{"_id":"q-en-website-00aa66da7bd6e747d4783005f15f5f1a75641b841a0fa7651cd77fc665499846","text":"It's possible to configure `kubeadm join` with a configuration file instead of command line flags, and some more advanced features may only be available as configuration file options. This file is passed using the `--config` flag and it must contain a `JoinConfiguration` structure. contain a `JoinConfiguration` structure. Mixing `--config` with others flags may not be allowed in some cases. To print the default values of `JoinConfiguration` run the following command: The default configuration can be printed out using the [kubeadm config print](/docs/reference/setup-tools/kubeadm/kubeadm-config/) command. ```shell kubeadm config print join-defaults ``` If your configuration is not using the latest version it is **recommended** that you migrate using the [kubeadm config migrate](/docs/reference/setup-tools/kubeadm/kubeadm-config/) command. For details on individual fields in `JoinConfiguration` see [the godoc](https://godoc.org/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm#JoinConfiguration). For more information on the fields and usage of the configuration you can navigate to our API reference page and pick a version from [the list](https://godoc.org/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm#pkg-subdirectories). ## {{% heading \"whatsnext\" %}}"} {"_id":"q-en-website-0172be1c623b76bf04c131f1e366428d29a621b0db743fd3161c8939c6a177f6","text":" --- layout: blog title: '在 Ingress-NGINX v1.2.0 中提高安全标准' date: 2022-04-28 slug: ingress-nginx-1-2-0 --- **作者:** Ricardo Katz (VMware), James Strong (Chainguard) [Ingress](/zh-cn/docs/concepts/services-networking/ingress/) 可能是 Kubernetes 最容易受攻击的组件之一。 Ingress 通常定义一个 HTTP 反向代理,暴露在互联网上,包含多个网站,并具有对 Kubernetes API 的一些特权访问(例如读取与 TLS 证书及其私钥相关的 Secret)。 虽然它是架构中的一个风险组件,但它仍然是正常公开服务的最流行方式。 Ingress-NGINX 一直是安全评估的重头戏,这类评估会发现我们有着很大的问题: 在将配置转换为 `nginx.conf` 文件之前,我们没有进行所有适当的清理,这可能会导致信息泄露风险。 虽然我们了解此风险以及解决此问题的真正需求,但这并不是一个容易的过程, 因此我们在当前(v1.2.0)版本中采取了另一种方法来减少(但不是消除!)这种风险。 ## 了解 Ingress NGINX v1.2.0 和 chrooted NGINX 进程 主要挑战之一是 Ingress-NGINX 运行着 Web 代理服务器(NGINX),并与 Ingress 控制器一起运行 (后者是一个可以访问 Kubernetes API 并创建 `nginx.conf` 的组件)。 因此,NGINX 对控制器的文件系统(和 Kubernetes 服务帐户令牌,以及容器中的其他配置)具有相同的访问权限。 虽然拆分这些组件是我们的最终目标,但该项目需要快速响应;这让我们想到了使用 `chroot()`。 让我们看一下 Ingress-NGINX 容器在此更改之前的样子: ![Ingress NGINX pre chroot](ingress-pre-chroot.png) 正如我们所见,用来提供 HTTP Proxy 的容器(不是 Pod,是容器!)也是是监视 Ingress 对象并将数据写入容器卷的容器。 现在,见识一下新架构: ![Ingress NGINX post chroot](ingress-post-chroot.png) 这一切意味着什么?一个基本的总结是:我们将 NGINX 服务隔离为控制器容器内的容器。 虽然这并不完全正确,但要了解这里所做的事情,最好了解 Linux 容器(以及内核命名空间等底层机制)是如何工作的。 你可以在 Kubernetes 词汇表中阅读有关 cgroup 的信息:[`cgroup`](/zh-cn/docs/reference/glossary/?fundamental=true#term-cgroup), 并在 NGINX 项目文章[什么是命名空间和 cgroup,以及它们如何工作?](https://www.nginx.com/blog/what-are-namespaces-cgroups-how-do-they-work/) 中了解有关 cgroup 与命名空间交互的更多信息。(当你阅读时,请记住 Linux 内核命名空间与 [Kubernetes 命名空间](/zh-cn/docs/concepts/overview/working-with-objects/namespaces/)不同)。 ## 跳过谈话,我需要什么才能使用这种新方法? 虽然这增加了安全性,但我们在这个版本中把这个功能作为一个选项,这样你就可以有时间在你的环境中做出正确的调整。 此新功能仅在 Ingress-NGINX 控制器的 v1.2.0 版本中可用。 要使用这个功能,在你的部署中有两个必要的改变: * 将后缀 \"-chroot\" 添加到容器镜像名称中。例如:`gcr.io/k8s-staging-ingress-nginx/controller-chroot:v1.2.0` * 在你的 Ingress 控制器的 Pod 模板中,找到添加 `NET_BIND_SERVICE` 权能的位置并添加 `SYS_CHROOT` 权能。 编辑清单后,你将看到如下代码段: ```yaml capabilities: drop: - ALL add: - NET_BIND_SERVICE - SYS_CHROOT ``` 如果你使用官方 Helm Chart 部署控制器,则在 `values.yaml` 中更改以下设置: ```yaml controller: image: chroot: true ``` Ingress 控制器通常部署在集群作用域(IngressClass API 是集群作用域的)。 如果你管理 Ingress-NGINX 控制器但你不是整个集群的操作员, 请在部署中启用它**之前**与集群管理员确认你是否可以使用 `SYS_CHROOT` 功能。 ## 好吧,但这如何能提高我的 Ingress 控制器的安全性呢? 以下面的配置片段为例,想象一下,由于某种原因,它被添加到你的 `nginx.conf` 中: ``` location /randomthing/ { alias /; autoindex on; } ``` 如果你部署了这种配置,有人可以调用 `http://website.example/randomthing` 并获取对 Ingress 控制器的整个文件系统的一些列表(和访问权限)。 现在,你能在下面的列表中发现 chroot 处理过和未经 chroot 处理过的 Nginx 之间的区别吗? | 不额外调用 `chroot()` | 额外调用 `chroot()` | |----------------------------|--------| | `bin` | `bin` | | `dev` | `dev` | | `etc` | `etc` | | `home` | | | `lib` | `lib` | | `media` | | | `mnt` | | | `opt` | `opt` | | `proc` | `proc` | | `root` | | | `run` | `run` | | `sbin` | | | `srv` | | | `sys` | | | `tmp` | `tmp` | | `usr` | `usr` | | `var` | `var` | | `dbg` | | | `nginx-ingress-controller` | | | `wait-shutdown` | | 左侧的那个没有 chroot 处理。所以 NGINX 可以完全访问文件系统。右侧的那个经过 chroot 处理, 因此创建了一个新文件系统,其中只有使 NGINX 工作所需的文件。 ## 此版本中的其他安全改进如何? 我们知道新的 `chroot()` 机制有助于解决部分风险,但仍然有人可以尝试注入命令来读取,例如 `nginx.conf` 文件并提取敏感信息。 所以,这个版本的另一个变化(可选择取消)是 **深度探测(Deep Inspector)**。 我们知道某些指令或正则表达式可能对 NGINX 造成危险,因此深度探测器会检查 Ingress 对象中的所有字段 (在其协调期间,并且还使用[验证准入 webhook](/zh-cn/docs/reference/access-authn-authz/admission-controllers/#validatingadmissionwebhook)) 验证是否有任何字段包含这些危险指令。 Ingress 控制器已经通过注解做了这个工作,我们的目标是把现有的验证转移到深度探测中,作为未来版本的一部分。 你可以在 [https://github.com/kubernetes/ingress-nginx/blob/main/internal/ingress/inspector/rules.go](https://github.com/kubernetes/ingress-nginx/blob/main/internal/ingress/inspector/rules.go) 中查看现有规则。 由于检查和匹配相关 Ingress 对象中的所有字符串的性质,此新功能可能会消耗更多 CPU。 你可以通过使用命令行参数 `--deep-inspect=false` 运行 Ingress 控制器来禁用它。 ## 下一步是什么? 这不是我们的最终目标。我们的最终目标是拆分控制平面和数据平面进程。 事实上,这样做也将帮助我们实现 [Gateway](https://gateway-api.sigs.k8s.io/) API 实现, 因为一旦它“知道”要提供什么,我们可能会有不同的控制器 数据平面(我们需要一些帮助!!) Kubernetes 中的其他一些项目已经采用了这种方法(如 [KPNG](https://github.com/kubernetes-sigs/kpng), 建议替换 `kube-proxy`),我们计划与他们保持一致,并为 Ingress-NGINX 获得相同的体验。 ## 延伸阅读 如果你想了解如何在 Ingress NGINX 中完成 chrooting,请查看 [https://github.com/kubernetes/ingress-nginx/pull/8337](https://github.com/kubernetes/ingress-nginx/pull/8337)。 包含所有更改的版本 v1.2.0 可以在以下位置找到 [https://github.com/kubernetes/ingress-nginx/releases/tag/controller-v1.2.0](https://github.com/kubernetes/ingress-nginx/releases/tag/controller-v1.2.0) "} {"_id":"q-en-website-03515a45f4d729b6a0d27d16dc85afbfb16c8dc2423af140926a779e71f6d634","text":"cpu: 100m memory: 100Mi ports: - containerPort: 80 No newline at end of file - containerPort: 80 "} {"_id":"q-en-website-03c097add1f30333daf53bf1525f2d8aaea5f0a3d2f3a840beda205df055d7c1","text":" --- title: Tutorials main_menu: true weight: 60 content_template: templates/concept --- {{% capture overview %}} Questa sezione della documentazione di Kubernetes contiene i tutorials. Un tutorial mostra come raggiungere un obiettivo più complesso di un singolo [task](/docs/tasks/). Solitamente un tutorial ha diverse sezioni, ognuna delle quali consiste in una sequenza di più task. Prima di procedere con vari tutorial, raccomandiamo di aggiungere il [Glossario](/docs/reference/glossary/) ai tuoi bookmark per riferimenti successivi. {{% /capture %}} {{% capture body %}} ## Per cominciare * [Kubernetes Basics](/docs/tutorials/kubernetes-basics/) è un approfondito tutorial che aiuta a capire cosa è Kubernetes e che permette di testare in modo interattivo alcune semplici funzionalità di Kubernetes. * [Introduction to Kubernetes (edX)](https://www.edx.org/course/introduction-kubernetes-linuxfoundationx-lfs158x#) * [Hello Minikube](/docs/tutorials/hello-minikube/) ## Configurazione * [Configurare Redis utilizzando una ConfigMap](/docs/tutorials/configuration/configure-redis-using-configmap/) ## Stateless Applications * [Esporre un External IP Address per permettere l'accesso alle applicazioni nel Cluster](/docs/tutorials/stateless-application/expose-external-ip-address/) * [Esempio: Rilasciare l'applicazione PHP Guestbook con Redis](/docs/tutorials/stateless-application/guestbook/) ## Stateful Applications * [StatefulSet Basics](/docs/tutorials/stateful-application/basic-stateful-set/) * [Esempio: WordPress e MySQL con i PersistentVolumes](/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/) * [Esempio: Rilasciare Cassandra con i StatefulSets](/docs/tutorials/stateful-application/cassandra/) * [Eseguire ZooKeeper, un sistema distribuito CP](/docs/tutorials/stateful-application/zookeeper/) ## CI/CD Pipelines * [Set Up a CI/CD Pipeline with Kubernetes Part 1: Overview](https://www.linux.com/blog/learn/chapter/Intro-to-Kubernetes/2017/5/set-cicd-pipeline-kubernetes-part-1-overview) * [Set Up a CI/CD Pipeline with a Jenkins Pod in Kubernetes (Part 2)](https://www.linux.com/blog/learn/chapter/Intro-to-Kubernetes/2017/6/set-cicd-pipeline-jenkins-pod-kubernetes-part-2) * [Run and Scale a Distributed Crossword Puzzle App with CI/CD on Kubernetes (Part 3)](https://www.linux.com/blog/learn/chapter/intro-to-kubernetes/2017/6/run-and-scale-distributed-crossword-puzzle-app-cicd-kubernetes-part-3) * [Set Up CI/CD for a Distributed Crossword Puzzle App on Kubernetes (Part 4)](https://www.linux.com/blog/learn/chapter/intro-to-kubernetes/2017/6/set-cicd-distributed-crossword-puzzle-app-kubernetes-part-4) ## Clusters * [AppArmor](/docs/tutorials/clusters/apparmor/) ## Servizi * [Utilizzare Source IP](/docs/tutorials/services/source-ip/) {{% /capture %}} {{% capture whatsnext %}} Se sei interessato a scrivere un tutorial, vedi [Utilizzare i Page Templates](/docs/home/contribute/page-templates/) per informazioni su come creare una tutorial page e sul tutorial template. {{% /capture %}} "} {"_id":"q-en-website-04433fb9bae1f41c518added475eefd885382cd4aecc88b2f23abadf392d70ff","text":" apiVersion: apps/v1 kind: Deployment metadata: name: patch-demo spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: patch-demo-ctr image: nginx tolerations: - effect: NoSchedule key: dedicated value: test-team "} {"_id":"q-en-website-05eaacf5bf7def6d5845726477825eca99ac205b455d47905018485d6ff153eb","text":"* One or more machines running one of: - Ubuntu 16.04+ - Debian 9+ - CentOS 7 - Red Hat Enterprise Linux (RHEL) 7 - CentOS 7+ - Red Hat Enterprise Linux (RHEL) 7+ - Fedora 25+ - HypriotOS v1.0.1+ - Flatcar Container Linux (tested with 2512.3.0)"} {"_id":"q-en-website-0609a90b1c8bd92e9229dcc1db7f485e1ffad7a11d3a10e5471336b5a39c699f","text":" --- title: Actualiza Objetos del API en su sitio (in Place) usando kubectl patch description: Usa kubectl patch para actualizar objetos del API de kubernetes sin reemplazarlos. Usa strategic merge patch o JSON merge patch. content_type: task weight: 50 --- Esta tarea muestra cómo utilizar `kubectl patch` para actualizar un objeto del API sin reemplazarlo. Los ejercicios de esta tarea demuestran el uso de \"strategic merge patch\" y \"JSON merge patch\" ## {{% heading \"prerequisites\" %}} {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} ## Usa strategic merge patch para actualizar un Deployment Aquí está el archivo de configuración para un Deployment con dos réplicas. Cada réplica es un Pod que tiene un contenedor: {{% code_sample file=\"application/deployment-patch.yaml\" %}} Crea el Deployment: ```shell kubectl apply -f https://k8s.io/examples/application/deployment-patch.yaml ``` Revisa los Pods asociados con tu Deployment: ```shell kubectl get pods ``` El resultado muestra que el Deployment tiene dos Pods. El `1/1` indica que cada Pod tiene un contenedor: ``` NAME READY STATUS RESTARTS AGE patch-demo-28633765-670qr 1/1 Running 0 23s patch-demo-28633765-j5qs3 1/1 Running 0 23s ``` Toma nota de los nombres de los Pods que se están ejecutando. Verás que estos Pods son terminados y reemplazados posteriormente. En este punto cada Pod tiene un contenedor que ejecuta una imagen de nginx. Ahora supón que quieres que cada Pod tenga dos contenedores: uno que ejecute nginx y otro que ejecute redis. Crea un archivo llamado `patch-file.yaml` con el siguiente contenido: ```yaml spec: template: spec: containers: - name: patch-demo-ctr-2 image: redis ``` Modifica tu Deployment usando Patch: ```shell kubectl patch deployment patch-demo --patch-file patch-file.yaml ``` Revisa el Deployment modificado: ```shell kubectl get deployment patch-demo --output yaml ``` El resultado muestra que el PodSpec del Deployment tiene dos contenedores: ```yaml containers: - image: redis imagePullPolicy: Always name: patch-demo-ctr-2 ... - image: nginx imagePullPolicy: Always name: patch-demo-ctr ... ``` Revisa los Pods asociados con tu Deployment modificado: ```shell kubectl get pods ``` El resultado muestra que los Pods tienen un nombre distinto a los que se estaban ejecutando anteriormente. El Deployment terminó los Pods viejos y creo dos nuevos que cumplen con la especificación actualizada del Deployment. El `2/2` indica que cada Pod tiene dos contenedores: ``` NAME READY STATUS RESTARTS AGE patch-demo-1081991389-2wrn5 2/2 Running 0 1m patch-demo-1081991389-jmg7b 2/2 Running 0 1m ``` Un vistazo más de cerca a uno de los Pods del patch-demo: ```shell kubectl get pod --output yaml ``` El resultado muestra que el Pod tienen dos contenedores: uno ejecutando nginx y otro redis: ``` containers: - image: redis ... - image: nginx ... ``` ### Notas acerca de strategic merge patch El patch que hiciste en el ejercicio anterior se llama *strategic merge patch*. Toma en cuenta que el path no reemplazó la lista `containers`. Sino que agregó un contenedor nuevo a la lista. En otras palabras, la lista en el patch fue agregada a la lista ya existente. Esto no es lo que pasa siempre que se utiliza strategic merge patch en una lista. En algunos casos la lista existente podría ser reemplazada en lugar de unir ambas. Con strategic merge patch, la lista existente puede ser reemplazada o unida con la nueva dependiendo de la estrategia de patch. La estrategia de patch se especifica en el valor de la clave `patchStrategy`en un campo tag del código fuente de Kubernetes. Por ejemplo el campo `Containers` de la struct `PodSpec` tiene un valor de `merge` en su clave `patchStrategy`: ```go type PodSpec struct { ... Containers []Container `json:\"containers\" patchStrategy:\"merge\" patchMergeKey:\"name\" ...` ... } ``` También puedes consultar la estrategia de patch en [OpenApi spec](https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json): ```yaml \"io.k8s.api.core.v1.PodSpec\": { ..., \"containers\": { \"description\": \"List of containers belonging to the pod. ....\" }, \"x-kubernetes-patch-merge-key\": \"name\", \"x-kubernetes-patch-strategy\": \"merge\" } ``` Y puedes consultar la estrategia de patch en la [Documentación del API Kubernetes](/docs/reference/generated/kubernetes-api/{{< param \"version\" >}}/#podspec-v1-core). Crea un archivo llamado `patch-file-tolerations.yaml` que tenga el siguiente contenido: ```yaml spec: template: spec: tolerations: - effect: NoSchedule key: disktype value: ssd ``` Modifica tu Deployment utilizando Patch: ```shell kubectl patch deployment patch-demo --patch-file patch-file-tolerations.yaml ``` Revisa el Deployment modificado: ```shell kubectl get deployment patch-demo --output yaml ``` El resultado muestra que el PodsSpec del Deployment tiene solo un Toleration: ```yaml tolerations: - effect: NoSchedule key: disktype value: ssd ``` Toma en cuenta que la lista de `tolerations` en el PodSpec fue reemplazada, no unida. Esto es porque el campo de Tolerations del PodSpec no tiene una clave `patchStrategy` en su campo de tag. por lo tanto strategic merge patch utiliza la estrategia de patch por defecto, la cual es `replace`. ```go type PodSpec struct { ... Tolerations []Toleration `json:\"tolerations,omitempty\" protobuf:\"bytes,22,opt,name=tolerations\"` ... } ``` ## Usa JSON merge patch para actualizar un Deployment Un strategic merge patch es distinto a un [JSON merge patch](https://tools.ietf.org/html/rfc7386). Con JSON merge patch, si quieres actualizar una lista tienes que especificar la lista nueva en su totalidad y reemplazar la lista existente con la lista nueva. El comando `kubectl patch` tiene un parámetro `type` que acepta los siguientes valores:
Valor del parámetrotipo de unión
jsonJSON Patch, RFC 6902
mergeJSON Merge Patch, RFC 7386
strategicStrategic merge patch
Para una comparación entre JSON patch y JSON merge patch, revisa [JSON Patch y JSON Merge Patch](https://erosb.github.io/post/json-patch-vs-merge-patch/). El valor predeterminado para el parámetro `type` es `strategic`. Entonces en el ejercicio anterior hiciste un strategic merge patch. A continuación haz un JSON merge path en el mismo Deployment. Crea un archivo llamado `patch-file-2.yaml` que tenga el siguiente contenido: ```yaml spec: template: spec: containers: - name: patch-demo-ctr-3 image: gcr.io/google-samples/node-hello:1.0 ``` En el comando patch configura el valor de `type` como `merge` ```shell kubectl patch deployment patch-demo --type merge --patch-file patch-file-2.yaml ``` Revisa el Deployment modificado: ```shell kubectl get deployment patch-demo --output yaml ``` La lista `containers` que especificaste en el patch solo tiene un contenedor. el resultado muestra que tu lista con un contenedor reemplazó a la lista `containers` preexistente. ```yaml spec: containers: - image: gcr.io/google-samples/node-hello:1.0 ... name: patch-demo-ctr-3 ``` Revisa los Pods en ejecución: ```shell kubectl get pods ``` En el resultado se puede ver que los Pods existentes fueron terminados y se crearon Pods nuevos. El `1/1` indica que cada Pod nuevo esta ejecutando un solo contenedor. ```shell NAME READY STATUS RESTARTS AGE patch-demo-1307768864-69308 1/1 Running 0 1m patch-demo-1307768864-c86dc 1/1 Running 0 1m ``` ## Usa strategic merge patch para actualizar un Deployment utilizando la estrategia retainKeys Aquí esta el archivo de configuración para un Deployment que usa la estrategia `RollingUpdate`: {{% code_sample file=\"application/deployment-retainkeys.yaml\" %}} Crea el Deployment: ```shell kubectl apply -f https://k8s.io/examples/application/deployment-retainkeys.yaml ``` En este punto, el Deployment es creado y está usando la estrategia `RollingUpdate`. Crea un archivo llamado `patch-file-no-retainkeys.yaml` con el siguiente contenido: ```yaml spec: strategy: type: Recreate ``` Modifica tu Deployment: ```shell kubectl patch deployment retainkeys-demo --type strategic --patch-file patch-file-no-retainkeys.yaml ``` En el resultado se puede ver que no es posible definir el `type` como `Recreate` cuando hay un value definido para `spec.strategy.rollingUpdate`: ``` The Deployment \"retainkeys-demo\" is invalid: spec.strategy.rollingUpdate: Forbidden: may not be specified when strategy `type` is 'Recreate' ``` La forma para quitar el valor para `spec.strategy.rollingUpdate` al momento de cambiar el valor `type` es usar la estrategia `retainKeys` para el strategic merge. Crea otro archivo llamado `patch-file-retainkeys.yaml` con el siguiente contenido: ```yaml spec: strategy: $retainKeys: - type type: Recreate ``` Con este Patch definimos que solo queremos conservar la clave `type` del objeto `strategy`. Por lo tanto la clave `rollingUpdate` será eliminada durante la operación de modificación. Modifica tu Deployment de nuevo con este nuevo Patch: ```shell kubectl patch deployment retainkeys-demo --type strategic --patch-file patch-file-retainkeys.yaml ``` Revisa el contenido del Deployment: ```shell kubectl get deployment retainkeys-demo --output yaml ``` El resultado muestra que el objeto `strategy` en el Deployment ya no contiene la clave `rollingUpdate`: ```yaml spec: strategy: type: Recreate template: ``` ### Notas acerca de strategic merge patch utilizando la estrategia retainKeys La modificación realizada en el ejercicio anterior tiene el nombre de *strategic merge patch con estrategia retainKeys*. Este método introduce una nueva directiva `$retainKeys` que tiene las siguientes estrategias: - Contiene una lista de strings. - Todos los campos que necesiten ser preservados deben estar presentes en la lista `$retainKeys`. - Todos los campos que estén presentes serán combinados con el objeto existente. - Todos los campos faltantes serán removidos o vaciados al momento de la modificación. - Todos los campos en la lista `$retainKeys` deberán ser un superconjunto o idéntico a los campos presentes en el Patch. La estrategia `retainKeys` no funciona para todos los objetos. Solo funciona cuando el valor de la key `patchStrategy`en el campo tag de el código fuente de Kubernetes contenga `retainKeys`. Por ejemplo, el campo `Strategy` del struct `DeploymentSpec` tiene un valor de `retainKeys` en su tag `patchStrategy` ```go type DeploymentSpec struct { ... // +patchStrategy=retainKeys Strategy DeploymentStrategy `json:\"strategy,omitempty\" patchStrategy:\"retainKeys\" ...` ... } ``` También puedes revisar la estrategia `retainKeys` en la especificación de [OpenApi](https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json): ```yaml \"io.k8s.api.apps.v1.DeploymentSpec\": { ..., \"strategy\": { \"$ref\": \"#/definitions/io.k8s.api.apps.v1.DeploymentStrategy\", \"description\": \"The deployment strategy to use to replace existing pods with new ones.\", \"x-kubernetes-patch-strategy\": \"retainKeys\" }, .... } ``` Además puedes revisar la estrategia `retainKeys` en la [documentación del API de k8s](/docs/reference/generated/kubernetes-api/{{< param \"version\" >}}/#deploymentspec-v1-apps). ### Formas alternativas del comando kubectl patch El comando `kubectl patch` toma como entrada un archivo en formato YAML o JSON desde el sistema de archivos o la línea de comandos. Crea un archivo llamado `patch-file.json` que contenga lo siguiente: ```json { \"spec\": { \"template\": { \"spec\": { \"containers\": [ { \"name\": \"patch-demo-ctr-2\", \"image\": \"redis\" } ] } } } } ``` Los siguientes comandos son equivalentes: ```shell kubectl patch deployment patch-demo --patch-file patch-file.yaml kubectl patch deployment patch-demo --patch 'spec:n template:n spec:n containers:n - name: patch-demo-ctr-2n image: redis' kubectl patch deployment patch-demo --patch-file patch-file.json kubectl patch deployment patch-demo --patch '{\"spec\": {\"template\": {\"spec\": {\"containers\": [{\"name\": \"patch-demo-ctr-2\",\"image\": \"redis\"}]}}}}' ``` ### Actualiza la cantidad de réplicas de un objeto utilizando `kubectl patch` con `--subresource` {#scale-kubectl-patch} {{< feature-state for_k8s_version=\"v1.24\" state=\"alpha\" >}} La bandera `--subresource=[subresource-name]` es utilizada con comandos de kubectl como get, patch y replace para obtener y actualizar los subrecursos `status` y `scale` de los recursos (aplicable para las versiones de kubectl de v1.24 en adelante). Esta bandera se utiliza con todos los recursos del API (incluidos en k8s o CRs) que tengan los subrecursos `status` o `scale`. Deployment es un ejemplo de un objeto con estos subrecursos. A continuación se muestra un ejemplo de un Deployment con dos réplicas: {{% code_sample file=\"application/deployment.yaml\" %}} Crea el Deployment: ```shell kubectl apply -f https://k8s.io/examples/application/deployment.yaml ``` Revisa los Pods asociados al Deployment ```shell kubectl get pods -l app=nginx ``` En el resultado se puede observar que el Deployment tiene dos Pods: ``` NAME READY STATUS RESTARTS AGE nginx-deployment-7fb96c846b-22567 1/1 Running 0 47s nginx-deployment-7fb96c846b-mlgns 1/1 Running 0 47s ``` Ahora modifica el Deployment utilizando Patch con la bandera `--subresource=[subresource-name]`: ```shell kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{\"spec\":{\"replicas\":3}}' ``` El resultado es : ```shell scale.autoscaling/nginx-deployment patched ``` Revisa los Pods asociados al Deployment modificado: ```shell kubectl get pods -l app=nginx ``` En el resultado se puede apreciar que se ha creado un Pod nuevo. Ahora tienes 3 Pods en ejecución. ``` NAME READY STATUS RESTARTS AGE nginx-deployment-7fb96c846b-22567 1/1 Running 0 107s nginx-deployment-7fb96c846b-lxfr2 1/1 Running 0 14s nginx-deployment-7fb96c846b-mlgns 1/1 Running 0 107s ``` Revisa el Deployment modificado ```shell kubectl get deployment nginx-deployment -o yaml ``` ```yaml ... spec: replicas: 3 ... status: ... availableReplicas: 3 readyReplicas: 3 replicas: 3 ``` {{< note >}} Si ejecutas `kubectl patch` y especificas la bandera `--subresource` para un recurso que no soporte un subrecurso en particular, el servidor del API regresará un error 404 Not Found. {{< /note >}} ## Resumen En este ejercicio utilizaste `kubectl patch` para cambiar la configuración en ejecución de un objeto de tipo Deployment. No hubo cambios al archivo de configuración que se utilizó originalmente para crear el Deployment. Otros comandos utilizados para actualizar objetos del API incluyen: [kubectl annotate](/docs/reference/generated/kubectl/kubectl-commands/#annotate), [kubectl edit](/docs/reference/generated/kubectl/kubectl-commands/#edit), [kubectl replace](/docs/reference/generated/kubectl/kubectl-commands/#replace), [kubectl scale](/docs/reference/generated/kubectl/kubectl-commands/#scale), y [kubectl apply](/docs/reference/generated/kubectl/kubectl-commands/#apply). {{< note >}} Strategic merge patch no tiene soporte para Custom Resources (CRs). {{< /note >}} ## {{% heading \"whatsnext\" %}} * [Manejo de Objetos de Kubernetes](/docs/concepts/overview/working-with-objects/object-management/) * [Manejo de Objetos de Kubernetes usando comandos imperativos](/docs/tasks/manage-kubernetes-objects/imperative-command/) * [Manejo Imperativo de Objetos de Kubernetes usando archivos de configuración](/docs/tasks/manage-kubernetes-objects/imperative-config/) * [Manejo Declarativo de Objetos de Kubernetes usando archivos de configuración](/docs/tasks/manage-kubernetes-objects/declarative-config/)
"} {"_id":"q-en-website-061c7b738049556fd9f34973f3f4c673eb160928323706dd03a3017c80b57354","text":"title: \"Your Title Here\" date: YYYY-MM-DD slug: text-for-URL-link-here-no-spaces author: > Author-1 (Affiliation), Author-2 (Affiliation), Author-3 (Affiliation) --- ```"} {"_id":"q-en-website-079bff64e5d9a5a5db0397ef6ee27fa1c64f4c027b215fa0ee687bcebb4dc38e","text":"## 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 owner object. A valid owner reference consists of the object name and a {{}} within the same {{}} 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"} {"_id":"q-en-website-07aaa88a5eec8e87f7c39c3d2f1caf66033a85d5ae9b72ce9cbd91c370837654","text":"persistentvolumeclaim/my-pvc created ``` The `--recursive` flag works with any operation that accepts the `--filename,-f` flag such as: `kubectl {create,get,delete,describe,rollout} etc.` The `--recursive` flag works with any operation that accepts the `--filename,-f` flag such as: `kubectl {create,get,delete,describe,rollout}` etc. The `--recursive` flag also works when multiple `-f` arguments are provided:"} {"_id":"q-en-website-080836b1d2be4247940278f0a24204bd4f234ff5d822ee2a418e91d382206083","text":"flag `--service-account-extend-token-expiration=false`. Check [Bound Service Account Tokens](https://github.com/kubernetes/enhancements/blob/master/keps/sig-auth/1205-bound-service-account-tokens/README.md) for more details. - `CheckpointContainer`: Enables the kubelet `checkpoint` API. - `ContainerCheckpoint`: Enables the kubelet `checkpoint` API. See [Kubelet Checkpoint API](/docs/reference/node/kubelet-checkpoint-api/) for more details. - `ControllerManagerLeaderMigration`: Enables Leader Migration for [kube-controller-manager](/docs/tasks/administer-cluster/controller-manager-leader-migration/#initial-leader-migration-configuration) and"} {"_id":"q-en-website-0986cda58c2cac4ef1d17af9f14b9b5f1d8757b287ea33a0b336884549917e18","text":"{{ $valid_states := \"alpha, beta, deprecated, stable\" }} {{ $state := .Get \"state\" }} {{ $for_k8s_version := .Get \"for_k8s_version\" | default (.Page.Param \"version\")}} {{ $for_k8s_version := .Get \"for_k8s_version\" | default (.Page.Param \"version\") }} {{ $is_valid := strings.Contains $valid_states $state }} {{ $feature_gate_name := .Get \"feature_gate_name\" }} {{ if not $feature_gate_name }} {{ if not $is_valid }} {{ errorf \"%q is not a valid feature-state, use one of %q\" $state $valid_states }} {{ else }}
{{ T \"feature_state\" }} {{T \"feature_state_kubernetes_label\" }} {{ $for_k8s_version }} [{{ $state }}]
{{ T \"feature_state\" }} {{ T \"feature_state_kubernetes_label\" }} {{ $for_k8s_version }} [{{ $state }}]
{{ end }} {{- else -}} {{ else }} {{- $featureGateDescriptionFilesPath := \"/docs/reference/command-line-tools-reference/feature-gates\" -}} {{- with index (where .Site.Sites \"Language.Lang\" \"eq\" \"en\") 0 -}} {{- with .GetPage $featureGateDescriptionFilesPath -}} {{- $sortedFeatureGates := sort (.Resources.ByType \"page\") -}} {{- $featureGateFound := false -}} {{- range $featureGateFile := $sortedFeatureGates -}} {{- $featureGateNameFromFile := $featureGateFile.Params.Title -}} {{- if eq $featureGateNameFromFile $feature_gate_name -}} {{- $currentStage := index $featureGateFile.Params.stages (sub (len $featureGateFile.Params.stages) 1) -}} {{- with $currentStage -}}
{{ T \"feature_state\" }} {{T \"feature_state_kubernetes_label\" }} v{{ .fromVersion }} [{{ .stage }}]
{{ T \"feature_state\" }} {{ T \"feature_state_kubernetes_label\" }} v{{ .fromVersion }} [{{ .stage }}]
{{- $featureGateFound = true -}} {{- end -}} {{- end -}} {{- end -}} {{- if not $featureGateFound -}} {{- errorf \"Invalid feature gate: '%s' is not recognized or lacks a matching description file in '%s'\" $feature_gate_name (print \"en\" $featureGateDescriptionFilesPath) -}} {{- errorf \"Invalid feature gate: '%s' is not recognized or lacks a matching description file in '%s'\" $feature_gate_name (print \"en\" $featureGateDescriptionFilesPath) -}} {{- end -}} {{- end -}}"} {"_id":"q-en-website-09fb4e08e48b83d49a2399d2a090dd08d4a2d7a5ae15a24437058312d6f513a4","text":"background-repeat: no-repeat, repeat; background-size: auto 100%, cover; color: #fff; width: 100vw; /* fallback in case calc() fails */ padding: 5vw; padding-bottom: 1em;"} {"_id":"q-en-website-0a865a8e69f9e82dfbdaf304cdaeb552f8e13ddc46a7465bb6af30997cbd1174","text":"

A Kubernetes cluster consists of two types of resources:

"} {"_id":"q-en-website-0b4a24ec8a93bb3c29a8c82b248b7ff33dbcf1a6cc42a3f6d4536641f99316c3","text":" このページでは、クラスター内のノードが使用している[コンテナランタイム](/docs/setup/production-environment/container-runtimes/)を確認する手順を概説しています。 このページでは、クラスター内のノードが使用している[コンテナランタイム](/ja/docs/setup/production-environment/container-runtimes/)を確認する手順を概説しています。 クラスターの実行方法によっては、ノード用のコンテナランタイムが事前に設定されている場合と、設定する必要がある場合があります。 マネージドKubernetesサービスを使用している場合、ノードに設定されているコンテナランタイムを確認するためのベンダー固有の方法があるかもしれません。"} {"_id":"q-en-website-0bf34baa13313a1935490a84731abb5ffc3056a49400cf6baa352034fba36f51","text":" --- title: Instalación de Complementos (AddOns) content_type: concept weight: 120 --- {{% thirdparty-content %}} Los complementos amplían las funcionalidades de Kubernetes. En esta página se listan algunos de los complementos disponibles con sus respectivos enlaces de instrucciones para su instalación y uso. La lista no pretende ser exhaustiva. ## Redes y Política de Redes * [ACI](https://www.github.com/noironetworks/aci-containers) (Cisco ACI) proporciona redes de contenedores integradas y seguridad de red. * [Antrea](https://antrea.io/) proporciona servicios de red y seguridad para Kubernetes, aprovechando Open vSwitch como plano de datos de red, opera en la capa 3/4. Antrea es un [proyecto de la CNCF de nivel Sandbox](https://www.cncf.io/projects/antrea/). * [Calico](https://www.tigera.io/project-calico/) es un proveedor de redes y políticas de red. Calico admite un conjunto flexible de opciones de red, para poder elegir la opción más eficiente para su situación, incluidas las redes superpuestas y no superpuestas, con o sin BGP (Border Gateway Protocol). Calico utiliza el mismo motor para aplicar las políticas de red para hosts, Pods, y (si se usa Istio y Envoy) aplicaciones en la capa de la malla de servicios. * [Canal](https://projectcalico.docs.tigera.io/getting-started/kubernetes/flannel/flannel) Es la unión de Flannel y Calico, proporciona redes y políticas de redes. * [Cilium](https://github.com/cilium/cilium) es una solución de red, observabilidad y seguridad con un plano de datos basado en eBPF. Cilium proporciona una red sencilla y plana en capa 3 con la capacidad de abarcar varios clústeres en un modo de enrutamiento nativo o de superposición/encapsulación, y puede aplicar políticas de red en L3-L7 utilizando un modelo de seguridad basado en identidad que está desacoplado del direccionamiento de red. Cilium puede actuar como sustituto de kube-proxy, también ofrece características adicionales de observabilidad y seguridad de manera opcional. Cilium es un [proyecto de la CNCF de nivel Incubación](https://www.cncf.io/projects/cilium/). * [CNI-Genie](https://github.com/cni-genie/CNI-Genie) permite a Kubernetes conectarse sin problemas a una selección de complementos de CNI, como Calico, Canal, Flannel o Weave. CNI-Genie es un [proyecto de la CNCF de nivel Sandbox](https://www.cncf.io/projects/cni-genie/). * [Contiv](https://contivpp.io/) proporciona redes configurables (L3 nativo mediante BGP, con superposición mediante vxlan, L2 clásica y Cisco-SDN/ACI) para diversos casos de uso y un vasto marco de políticas. El proyecto Contiv es de [código abierto](https://github.com/contiv). El [instalador](https://github.com/contiv/install) ofrece opciones de instalación basadas en kubeadm y no basadas en kubeadm. * [Contrail](https://www.juniper.net/us/en/products-services/sdn/contrail/contrail-networking/), basada en [Tungsten Fabric](https://tungsten.io), es una plataforma de gestión de políticas y virtualización de redes multicloud de código abierto. Contrail y Tungsten Fabric se integran con sistemas de orquestación como Kubernetes, OpenShift, OpenStack y Mesos, y proporcionan modos de aislamiento para máquinas virtuales, contenedores/Pods y cargas de trabajo para bare metal. * [Flannel](https://github.com/flannel-io/flannel#deploying-flannel-manually) es un proveedor de red superpuesta que se puede usar con Kubernetes. * [Knitter](https://github.com/ZTE/Knitter/) es un complemento que soportar múltiples interfaces de red en un Pod de Kubernetes. * [Multus](https://github.com/k8snetworkplumbingwg/multus-cni) es un multicomplemento para soporte de múltiple redes en Kubernetes, que admite todos los complementos de CNI (ej. Calico, Cilium, Contiv, Flannel), además de SRIOV, DPDK, OVS-DPDK y cargas de trabajo basadas en VPP en Kubernetes. * [OVN-Kubernetes](https://github.com/ovn-org/ovn-kubernetes/) es un proveedor de red para Kubernetes basado en [OVN (Open Virtual Network)](https://github.com/ovn-org/ovn/), es una implementación de red virtual que surgió del proyecto Open vSwitch (OVS). OVN-Kubernetes proporciona una implementación de red basada en la superposición para Kubernetes, incluyendo una implementación basada en OVS de balanceo de carga y política de red. * [Nodus](https://github.com/akraino-edge-stack/icn-nodus) es un complemento de controlador CNI basado en OVN para proveer Service function chaining(SFC) con base nativa para la nube. * [NSX-T](https://docs.vmware.com/en/VMware-NSX-T-Data-Center/index.html) Container Plug-in (NCP) proporciona integración entre VMware NSX-T y orquestadores de contenedores como Kubernetes, así como integración entre NSX-T y plataformas CaaS/PaaS basadas en contenedores como Pivotal Container Service (PKS) y OpenShift. * [Nuage](https://github.com/nuagenetworks/nuage-kubernetes/blob/v5.1.1-1/docs/kubernetes-1-installation.rst) es una plataforma SDN que proporciona redes basadas en políticas entre Kubernetes Pods y entornos no Kubernetes con visibilidad y supervisión de la seguridad. * [Romana](https://github.com/romana) es una solución de red de capa 3 para las redes de Pods que también son compatibles con la API de [NetworkPolicy](/docs/concepts/services-networking/network-policies/). * [Weave Net](https://www.weave.works/docs/net/latest/kubernetes/kube-addon/) proporciona redes y políticas de red, funciona en ambos lados de una partición de red y no requiere una base de datos externa. ## Detección de Servicios * [CoreDNS](https://coredns.io) es un servidor de DNS flexible y extensible que puede [instalarse](https://github.com/coredns/deployment/tree/master/kubernetes) como DNS dentro del clúster para los Pods. ## Visualización y Control * [Dashboard](https://github.com/kubernetes/dashboard#kubernetes-dashboard) es un panel de control con una interfaz web para Kubernetes. * [Weave Scope](https://www.weave.works/documentation/scope-latest-installing/#k8s) es una herramienta para visualizar gráficamente tus contenedores, Pods, Services, etc. Utilícela junto con una [cuenta de Weave Cloud](https://cloud.weave.works/) o aloje la interfaz de usuario usted mismo. ## Infraestructura * [KubeVirt](https://kubevirt.io/user-guide/#/installation/installation) es un complemento para ejecutar máquinas virtuales en Kubernetes. Suele ejecutarse en clústeres de Bare metal. * El [detector de problemas de nodo](https://github.com/kubernetes/node-problem-detector) se ejecuta en nodos Linux e informa de los problemas del sistema como [Eventos](/docs/reference/kubernetes-api/cluster-resources/event-v1/) o [Condiciones de nodo](/docs/concepts/architecture/nodes/#condition). ## Complementos Antiguos Hay otros complementos documentados como obsoletos en el directorio [cluster/addons](https://git.k8s.io/kubernetes/cluster/addons). Los que mejor mantenimiento tienen deben estar vinculados aquí. !PRs son bienvenidos! No newline at end of file"} {"_id":"q-en-website-0c666b927c1d8cd596de5216327b0de0075b95ecc498cfb7977a2b93ed268628","text":"{{< comment >}} TODO: Add more information about return codes once CRI implementation have checkpoint/restore. This TODO cannot be fixed before the release, because the CRI implementation need the Kubernetes changes to be merged to implement the new CheckpointContainer CRI API the Kubernetes changes to be merged to implement the new ContainerCheckpoint CRI API call. We need to wait after the 1.25 release to fix this. {{< /comment >}}"} {"_id":"q-en-website-0ccaf86d7949e685192df38c04da1078eeeb3913f59b3be2d63180a44df9329f","text":"Atualmente, se algum sistema externo executou a rotação, apenas o conteúdo do arquivo de log mais recente estará disponível através de `kubectl logs`. Por exemplo, se houver um arquivo de 10MB, o `logrotate` executa a rotação e existem dois arquivos, um com 10MB de tamanho e um vazio, o `kubectl logs` retornará uma resposta vazia. {{< /note >}} [cosConfigureHelper]: https://github.com/kubernetes/kubernetes/blob/{{< param \"githubbranch\" >}}/cluster/gce/gci/configure-helper.sh [cosConfigureHelper]: https://github.com/kubernetes/kubernetes/blob/master/cluster/gce/gci/configure-helper.sh ### Logs de componentes do sistema"} {"_id":"q-en-website-0cfd0f9c1f9af656768849f2130cf58ae06a83c5ab51f2b0b109d8b675f98214","text":"[options_heading] other = \"Opcje\" [outdated_blog__message] other = \"Ten artykuł jest starszy niż rok, więc część informacji może być już nieaktualnych. Upewnij się, że zawartość tej strony ciągle jest poprawna.\" [patch_release] other = \"Patch Release\" [post_create_issue] other = \"Zgłoś problem\""} {"_id":"q-en-website-0d873fdd81ef355ac4ff1db02d5466e5f5eab210d62f5cc1400b130d6b61b4a2","text":" --- title: 启用拓扑感知提示 content_type: task min-kubernetes-server-version: 1.21 --- {{< feature-state for_k8s_version=\"v1.21\" state=\"alpha\" >}} _拓扑感知提示_ 启用具有拓扑感知能力的路由,其中拓扑感知信息包含在 {{< glossary_tooltip text=\"EndpointSlices\" term_id=\"endpoint-slice\" >}} 中。 此功能尽量将流量限制在它的发起区域附近; 可以降低成本,或者提高网络性能。 ## {{% heading \"prerequisites\" %}} {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} 为了启用拓扑感知提示,先要满足以下先决条件: * 配置 {{< glossary_tooltip text=\"kube-proxy\" term_id=\"kube-proxy\" >}} 以 iptables 或 IPVS 模式运行 * 确保未禁用 EndpointSlices ## 启动拓扑感知提示 {#enable-topology-aware-hints} 要启用服务拓扑感知,请启用 kube-apiserver、kube-controller-manager、和 kube-proxy 的 [特性门控](/zh/docs/reference/command-line-tools-reference/feature-gates/) `TopologyAwareHints`。 ``` --feature-gates=\"TopologyAwareHints=true\" ``` ## {{% heading \"whatsnext\" %}} * 参阅面向服务的[拓扑感知提示](/zh/docs/concepts/services-networking/topology-aware-hints) * 参阅[用服务连通应用](/zh/docs/concepts/services-networking/connect-applications-service/) "} {"_id":"q-en-website-10d2879ccb8fff3df3251121afae8caa9dc075e6cc8f8eb2627043ebf7871c2c","text":" "} {"_id":"q-en-website-1290560c3a355202128fbc7be1fadbc46cd3e25d2170119956d2c4c0a0f3227e","text":"## Logs and auditing - [ ] Audit logs, if enabled, are protected from general access. - [ ] The `/logs` API is disabled (you are running kube-apiserver with `--enable-logs-handler=false`). Kubernetes includes a `/logs` API endpoint, enabled by default, that lets users request the contents of the API server's `/var/log` directory over HTTP. Accessing that endpoint requires authentication. Allowing broad access to Kubernetes logs can make security information available to a potential attacker. As a good practice, set up a separate means to collect and aggregate control plane logs, and do not use the `/logs` API endpoint. Alternatively, if you run your control plane with the `/logs` API endpoint and limit the content of `/var/log` (within the host or container where the API server is running) to Kubernetes API server logs only. ## Pod placement"} {"_id":"q-en-website-12eb2a9f8c06e34aacab434505f57495a4a66920a6f1c113ee1315f5c2b8682d","text":"body.cid-community .community-section#events { width: 100vw; width: 100%; max-width: initial; margin-bottom: 0;"} {"_id":"q-en-website-145902464143038cf15687a3486317013cf5e440267139d3eb68f81297246dda","text":"- \"`Default`\": The Pod inherits the name resolution configuration from the node that the pods run on. See [related discussion](/docs/tasks/administer-cluster/dns-custom-nameservers/#inheriting-dns-from-the-node) See [related discussion](/docs/tasks/administer-cluster/dns-custom-nameservers) for more details. - \"`ClusterFirst`\": Any DNS query that does not match the configured cluster domain suffix, such as \"`www.kubernetes.io`\", is forwarded to the upstream nameserver inherited from the node. Cluster administrators may have extra stub-domain and upstream DNS servers configured. See [related discussion](/docs/tasks/administer-cluster/dns-custom-nameservers/#effects-on-pods) See [related discussion](/docs/tasks/administer-cluster/dns-custom-nameservers) for details on how DNS queries are handled in those cases. - \"`ClusterFirstWithHostNet`\": For Pods running with hostNetwork, you should explicitly set its DNS policy \"`ClusterFirstWithHostNet`\"."} {"_id":"q-en-website-14714522090872de0b8e2d3bda05904011941848f3d280137ca940d20d90c6bc","text":"

If you haven't worked through the earlier sections, start from Using minikube to create a cluster.

Scaling is accomplished by changing the number of replicas in a Deployment

NOTE If you are trying this after the previous section , you may need to start from creating a cluster as the services may have been deleted

"} {"_id":"q-en-website-153c124c2071068c0698cf5e9f0085ed1d1b2fc4164bcfb2b2e297087b0a5295","text":" apiVersion: v1 kind: Pod metadata: name: nginx spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: disktype operator: In values: - ssd containers: - name: nginx image: nginx imagePullPolicy: IfNotPresent "} {"_id":"q-en-website-15532887ad9d30f612ef6bd1f3eeb2176820956c7b7ddfca8bb0447a707dff7c","text":" --- title: \"Linux 系统中的 bash 自动补全功能\" description: \"Linux 系统中 bash 自动补全功能的一些可选配置。\" headless: true --- ### 简介 {#introduction} kubectl 的 Bash 补全脚本可以用命令 `kubectl completion bash` 生成。 在 shell 中导入(Sourcing)补全脚本,将启用 kubectl 自动补全功能。 然而,补全脚本依赖于工具 [**bash-completion**](https://github.com/scop/bash-completion), 所以要先安装它(可以用命令 `type _init_completion` 检查 bash-completion 是否已安装)。 ### 安装 bash-completion {#install-bash-comletion} 很多包管理工具均支持 bash-completion(参见[这里](https://github.com/scop/bash-completion#installation))。 可以通过 `apt-get install bash-completion` 或 `yum install bash-completion` 等命令来安装它。 上述命令将创建文件 `/usr/share/bash-completion/bash_completion`,它是 bash-completion 的主脚本。 依据包管理工具的实际情况,你需要在 `~/.bashrc` 文件中手工导入此文件。 要查看结果,请重新加载你的 shell,并运行命令 `type _init_completion`。 如果命令执行成功,则设置完成,否则将下面内容添加到文件 `~/.bashrc` 中: ```bash source /usr/share/bash-completion/bash_completion ``` 重新加载 shell,再输入命令 `type _init_completion` 来验证 bash-completion 的安装状态。 ### 启动 kubectl 自动补全功能 {#enable-kubectl-autocompletion} 你现在需要确保一点:kubectl 补全脚本已经导入(sourced)到 shell 会话中。 这里有两种验证方法: - 在文件 `~/.bashrc` 中导入(source)补全脚本: ```bash echo 'source <(kubectl completion bash)' >>~/.bashrc ``` - 将补全脚本添加到目录 `/etc/bash_completion.d` 中: ```bash kubectl completion bash >/etc/bash_completion.d/kubectl ``` 如果 kubectl 有关联的别名,你可以扩展 shell 补全来适配此别名: ```bash echo 'alias k=kubectl' >>~/.bashrc echo 'complete -F __start_kubectl k' >>~/.bashrc ``` {{< note >}} bash-completion 负责导入 `/etc/bash_completion.d` 目录中的所有补全脚本。 {{< /note >}} 两种方式的效果相同。重新加载 shell 后,kubectl 自动补全功能即可生效。 "} {"_id":"q-en-website-178df86120eae6559fae0c7840482e2f7db415b8c83ff991d09dd4ffb3862555","text":"## 논 그레이스풀 노드 셧다운 {#non-graceful-node-shutdown} {{< feature-state state=\"alpha\" for_k8s_version=\"v1.24\" >}} {{< feature-state state=\"beta\" for_k8s_version=\"v1.26\" >}} 전달한 명령이 kubelet에서 사용하는 금지 잠금 메커니즘(inhibitor locks mechanism)을 트리거하지 않거나, 또는 사용자 오류(예: ShutdownGracePeriod 및 ShutdownGracePeriodCriticalPods가 제대로 설정되지 않음)로 인해"} {"_id":"q-en-website-18290ded0340ba07beb68b70eb256633af9f3d25574abc823fef7ed71e7a9b69","text":" --- layout: blog title: \"Kubernetes 1.24: 节点非体面关闭特性进入 Alpha 阶段\" date: 2022-05-20 slug: kubernetes-1-24-non-graceful-node-shutdown-alpha --- **作者**:Xing Yang 和 Yassine Tijani (VMware) Kubernetes v1.24 引入了对[节点非体面关闭](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/2268-non-graceful-shutdown) (Non-Graceful Node Shutdown)的 Alpha 支持。 此特性允许有状态工作负载在原节点关闭或处于不可恢复状态(如硬件故障或操作系统损坏)后,故障转移到不同的节点。 ## 这与节点体面关闭有何不同 你可能听说过 Kubernetes 的[节点体面关闭](/zh-cn/docs/concepts/architecture/nodes/#graceful-node-shutdown)特性, 并且想知道节点非体面关闭特性与之有何不同。节点体面关闭允许 Kubernetes 检测节点何时完全关闭,并适当地处理这种情况。 只有当 kubelet 在实际关闭之前检测到节点关闭动作时,节点关闭才是“体面(graceful)”的。 但是,在某些情况下,kubelet 可能检测不到节点关闭操作。 这可能是因为 shutdown 命令没有触发 kubelet 所依赖的 systemd 抑制锁机制, 或者是因为配置错误(`ShutdownGracePeriod` 和 `ShutdownGracePeriodCriticalPods` 配置不正确)。 节点体面关闭依赖于特定 Linux 的支持。 kubelet 不监视 Windows 节点上即将关闭的情况(这可能在未来的 Kubernetes 版本中会有所改变)。 当一个节点被关闭但 kubelet 没有检测到时,该节点上的 Pod 也会非体面地关闭。 对于无状态应用程序,这通常不是问题(一旦集群检测到受影响的节点或 Pod 出现故障,ReplicaSet 就会添加一个新的 Pod)。 对于有状态的应用程序,情况要复杂得多。如果你使用一个 StatefulSet, 并且该 StatefulSet 中的一个 Pod 在某个节点上发生了不干净故障,则该受影响的 Pod 将被标记为终止(Terminating); StatefulSet 无法创建替换 Pod,因为该 Pod 仍存在于集群中。 因此,在 StatefulSet 上运行的应用程序可能会降级甚至离线。 如果已关闭的原节点再次出现,该节点上的 kubelet 会执行报到操作,删除现有的 Pod, 并且控制平面会在不同的运行节点上为该 StatefulSet 生成一个替换 Pod。 如果原节点出现故障并且没有恢复,这些有状态的 Pod 将处于终止状态且无限期地停留在该故障节点上。 ``` $ kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES web-0 1/1 Running 0 100m 10.244.2.4 k8s-node-876-1639279816 web-1 1/1 Terminating 0 100m 10.244.1.3 k8s-node-433-1639279804 ``` ## 尝试新的非体面关闭处理 要使用节点非体面关闭处理,你必须为 `kube-controller-manager` 组件启用 `NodeOutOfServiceVolumeDetach` [特性门控](/zh-cn/docs/reference/command-line-tools-reference/feature-gates/)。 在节点关闭的情况下,你可以手动为该节点标记污点,标示其已停止服务。 在添加污点之前,你应该确保节点确实关闭了(不是在重启过程中)。 你可以在发生了节点关闭事件,且该事件没有被 kubelet 提前检测和处理的情况下,在节点关闭之后添加污点; 你可以使用该污点的另一种情况是当节点由于硬件故障或操作系统损坏而处于不可恢复状态时。 你可以为该污点设置的值是 `node.kubernetes.io/out-of-service=nodeshutdown: \"NoExecute\"` 或 `node.kubernetes.io/out-of-service=nodeshutdown: \"NoSchedule\"`。 如果你已经启用了前面提到的特性门控,在节点上设置 out-of-service 污点意味着节点上的 Pod 将被删除, 除非 Pod 上设置有与之匹配的容忍度。原来挂接到已关闭节点的持久卷(Persistent volume)将被解除挂接, 对于 StatefulSet,系统将在不同的运行节点上成功创建替换 Pod。 ``` $ kubectl taint nodes node.kubernetes.io/out-of-service=nodeshutdown:NoExecute $ kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES web-0 1/1 Running 0 150m 10.244.2.4 k8s-node-876-1639279816 web-1 1/1 Running 0 10m 10.244.1.7 k8s-node-433-1639279804 ``` 注意:在应用 out-of-service 污点之前,你**必须**确认节点是否已经处于关闭或断电状态(不是在重新启动过程中), 节点关闭的原因可能是用户有意将其关闭,也可能是节点由于硬件故障、操作系统问题等而关闭。 一旦关联到无法提供服务的节点的所有工作负载 Pod 都被移动到新的运行中的节点,并且关闭了的节点也已恢复, 你应该在节点恢复后删除受影响节点上的污点。如果你知道该节点不会恢复服务,则可以改为从集群中删除该节点。 ## 下一步是什么? 根据反馈和采用情况,Kubernetes 团队计划在 1.25 或 1.26 版本中将节点非体面关闭实现推送到 Beta 阶段。 此功能需要用户手动向节点添加污点以触发工作负载故障转移,并要求用户在节点恢复后移除污点。 未来,我们计划寻找方法来自动检测和隔离已关闭的或已失败的节点,并自动将工作负载故障转移到另一个节点。 ## 怎样才能了解更多? 查看节点非体面关闭相关[文档](/zh-cn/docs/concepts/architecture/nodes/#non-graceful-node-shutdown)。 ## 如何参与? 此功能特性由来已久。Yassine Tijani([yastij](https://github.com/yastij))在两年多前启动了这个 KEP。 Xing Yang([xing-yang](https://github.com/xing-yang))继续推动这项工作。 SIG-Storage、SIG-Node 和 API 评审人员们进行了多次讨论,以确定设计细节。 Ashutosh Kumar([sonasingh46](https://github.com/sonasingh46)) 完成了大部分实现并在 Kubernetes 1.24 版本中将其引进到 Alpha 阶段。 我们要感谢以下人员的评审:Tim Hockin([thockin](https://github.com/thockin))对设计的指导; 来自 SIG-Storage 的 Jing Xu([jingxu97](https://github.com/jingxu97))、 Hemant Kumar([gnufied](https://github.com/gnufied)) 和 Michelle Au([msau42](https://github.com/msau42))的评论; 以及 Mrunal Patel([mrunalp](https://github.com/mrunalp))、 David Porter([bobbypage](https://github.com/bobbypage))、 Derek Carr([derekwaynecarr](https://github.com/derekwaynecarr)) 和 Danielle Endocrimes([endocrimes](https://github.com/endocrimes))来自 SIG-Node 方面的评论。 在此过程中,有很多人帮助审查了设计和实现。我们要感谢所有为此做出贡献的人, 包括在过去几年中审核 [KEP](https://github.com/kubernetes/enhancements/pull/1116) 和实现的大约 30 人。 此特性是 SIG-Storage 和 SIG-Node 之间的协作。 对于那些有兴趣参与 Kubernetes Storage 系统任何部分的设计和开发的人, 请加入 [Kubernetes 存储特别兴趣小组](https://github.com/kubernetes/community/tree/master/sig-storage)(SIG-Storage)。 对于那些有兴趣参与支持 Pod 和主机资源之间受控交互的组件的设计和开发的人, 请加入 [Kubernetes Node SIG](https://github.com/kubernetes/community/tree/master/sig-node)。 "} {"_id":"q-en-website-186f16d60a9b5b64b1bbe8e0d6abf1bdde8d6bac268d8647e3731274151fd76f","text":"• [VirtualBox](https://www.virtualbox.org/wiki/Downloads) {{< note >}} minikubeは、VMではなくホストでKubernetesコンポーネントを実行する`--vm-driver=none`オプションもサポートしています。 Minikubeは、VMではなくホストでKubernetesコンポーネントを実行する`--vm-driver=none`オプションもサポートしています。 このドライバーを使用するには、[Docker](https://www.docker.com/products/docker-desktop)とLinux環境が必要ですが、ハイパーバイザーは不要です。 noneドライバーを使用する場合は、[Docker](https://www.docker.com/products/docker-desktop)からdockerのaptインストールを使用することをおすすめします。 dockerのsnapインストールは、minikubeでは機能しません。 {{< /note >}} Debian系のLinuxで`none`ドライバーを使用する場合は、snapパッケージではなく`.deb`パッケージを使用してDockerをインストールしてください。snapパッケージはMinikubeでは機能しません。 [Docker](https://www.docker.com/products/docker-desktop)から`.deb`パッケージをダウンロードできます。 {{< caution >}} `none` VMドライバーは、セキュリティとデータ損失の問題を引き起こす可能性があります。 `--vm-driver=none`を使用する前に、詳細について[このドキュメント](https://minikube.sigs.k8s.io/docs/reference/drivers/none/) を参照してください。 {{< /caution >}} MinikubeはDockerドライバーと似たような`vm-driver=podman`もサポートしています。Podmanを特権ユーザー権限(root user)で実行することは、コンテナがシステム上の利用可能な機能へ完全にアクセスするための最もよい方法です。 {{< caution >}} `podman` ドライバーは、rootでコンテナを実行する必要があります。これは、通常のユーザーアカウントが、コンテナの実行に必要とされるすべてのOS機能への完全なアクセスを持っていないためです。 {{< /caution >}} ### パッケージを利用したMinikubeのインストール"} {"_id":"q-en-website-18712e4ca6ef21a9bed8a433fe20ae2095800a50ccba3a219dfacd16a3796d72","text":"message: | 5 days of incredible opportunites to collaborate, learn + share with the entire community!
May 16 - 20, 2022. - name: Kubecon 2022 NA startTime: 2022-10-17T00:00:00 # Added in https://github.com/kubernetes/website/pull/36107 endTime: 2022-10-29T00:00:00 style: >- background: linear-gradient(135deg,rgb(2,3,129) 0%,rgb(114,114,255) 100%); color: #fff; title: | KubeCon + CloudNativeCon NA 2022 Detroit, Michigan + Virtual. message: | 5 days of incredible opportunites to collaborate, learn + share with the entire community!
October 24 - 28, 2022.
"} {"_id":"q-en-website-1a44d8768cf461d970f38ae0f5458459667b63fc173bb535681c61cb929e6408","text":"sudo apt-get update sudo apt-get install -y kubectl ``` {{< note >}} In releases older than Debian 12 and Ubuntu 22.04, `/etc/apt/keyrings` does not exist by default. You can create this directory if you need to, making it world-readable but writeable only by admins. {{< /note >}} {{% /tab %}}"} {"_id":"q-en-website-1b88a1202162aae6ab3e9ba48910109ce1f284d43f475716d3e64af928ccca1d","text":"- [cgroups](https://man7.org/linux/man-pages/man7/cgroups.7.html)についてもっと学習しましょう。 - [コンテナランタイム](/ja/docs/concepts/architecture/cri)についてもっと学習しましょう。 - [cgroupドライバー](/docs/setup/production-environment/container-runtimes#cgroup-drivers)についてもっと学習しましょう。 - [cgroupドライバー](/ja/docs/setup/production-environment/container-runtimes#cgroup-drivers)についてもっと学習しましょう。 "} {"_id":"q-en-website-1c1c8061dcbb7ebfca0b898f3f6e5647e2519f93a084df76e680fe799b198493","text":"communicates with). 1. (Recommended) If you have plans to upgrade this single control-plane `kubeadm` cluster to high availability you should specify the `--control-plane-endpoint` to set the shared endpoint for all control-plane nodes. Such an endpoint can be either a DNS name or an IP address of a load-balancer. to [high availability](/docs/setup/production-environment/tools/kubeadm/high-availability/) you should specify the `--control-plane-endpoint` to set the shared endpoint for all control-plane nodes. Such an endpoint can be either a DNS name or an IP address of a load-balancer. 1. Choose a Pod network add-on, and verify whether it requires any arguments to be passed to `kubeadm init`. Depending on which third-party provider you choose, you might need to set the `--pod-network-cidr` to"} {"_id":"q-en-website-1c1e62c57e4d248c89b51df858fa735d7b7fdfbdab858f0002cab9353f5a719a","text":"} body.cid-community .community-section#meetups { width: 100vw; width: 100%; max-width: initial; margin-top: 0;"} {"_id":"q-en-website-1dbb74f857207ef6636edbe2e9ddeeae529907b573b445c52766611641014322","text":"sudo apt-get install -y kubelet kubeadm kubectl sudo apt-mark hold kubelet kubeadm kubectl ``` {{< note >}} In releases older than Debian 12 and Ubuntu 22.04, `/etc/apt/keyrings` does not exist by default. You can create this directory if you need to, making it world-readable but writeable only by admins. {{< /note >}} {{% /tab %}} {{% tab name=\"Red Hat-based distributions\" %}}"} {"_id":"q-en-website-206f1042a323492811f9ff51056f11992663c29f77ef3c16daab6a69db36e4fb","text":"[permalinks] blog = \"/:section/:year/:month/:day/:slug/\" [sitemap] filename = \"sitemap.xml\" priority = 0.75 # Be explicit about the output formats. We (currently) only want an RSS feed for the home page. [outputs] home = [ \"HTML\", \"RSS\", \"HEADERS\" ]"} {"_id":"q-en-website-216140bb6beb2c2c86f9424a243766315ef86b5071fc131a43c07137e5a0fde9","text":"performed periodically by the [kubelet](/docs/admin/kubelet/) on a Container. To perform a diagnostic, the kubelet calls a [Handler](https://godoc.org/k8s.io/kubernetes/pkg/api/v1#Handler) implemented by [Handler](/docs/reference/generated/kubernetes-api/{{< param \"version\" >}}/#handler-v1-core) implemented by the Container. There are three types of handlers: * [ExecAction](/docs/reference/generated/kubernetes-api/{{< param \"version\" >}}/#execaction-v1-core):"} {"_id":"q-en-website-2225859540e0795d7f775ebcddd68150258983a9224072bba4e1e2f18c435818","text":"

쿠버네티스는 CNCF의 행동 강령을 따르고 있습니다. 커밋 71b12a2 커밋 fff715fb0 에 따라 CNCF 행동 강령의 내용이 아래에 복제됩니다. 만약 최신 버전이 아닌 경우에는 이슈를 제기해 주세요."} {"_id":"q-en-website-22caefc0ae2b927337d72d084731736585077431aac3e02bdcc24d24cd3d9abd","text":"nc 127.0.0.1 6443 ``` The pod network plugin you use (see below) may also require certain ports to be The pod network plugin you use may also require certain ports to be open. Since this differs with each pod network plugin, please see the documentation for the plugins about what port(s) those need."} {"_id":"q-en-website-23c6edf2a2882b40b7c02a78a3eeada2c5a7d7da0540219f8e81118b4d11b530","text":"other = \"否\" [feedback_question] other = \"此页是否对您有帮助?\" other = \"此页是否对你有帮助?\" [feedback_yes] other = \"是\""} {"_id":"q-en-website-241cfa024a9dd851e8ee48bb236ee26d84b27419fcf7c62eb0c4245b08586ede","text":" In Kubernetes, some objects are *owners* of other objects. For example, a {{}} is the owner of a set of Pods. These owned objects are *dependents* In Kubernetes, some {{< glossary_tooltip text=\"objects\" term_id=\"Object\" >}} are *owners* of other objects. For example, a {{}} is the owner of a set of {{}}. These owned objects are *dependents* of their owner. 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 creates `EndpointSlice` objects. The Service uses {{}} 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"} {"_id":"q-en-website-241ddd6e74b6b2c54a0452efff3fbb069ace3545585191984cd4d368694b17a4","text":"Issues should be sorted into different buckets of work using the following labels and definitions. If an issue doesn't have enough information to identify a problem that can be researched, reviewed, or worked on (i.e. the issue doesn't fit into any of the categories below) you should close the issue with a comment explaining why it is being closed. ### Needs Clarification * Issues that need more information from the original submitter to make them actionable. Issues with this label that aren't followed up within a week may be closed. * Issues that need more information from the original submitter to make them actionable. Issues with this label that aren't followed up within a week may be closed. ### Actionable * Issues that can be worked on with current information (or may need a comment to explain what needs to be done to make it more clear)"} {"_id":"q-en-website-25e5d5c98fd082fba5184203d63054acac97bbf976ec0277547b62780b074326","text":"response for the `/api` and `/apis` endpoint is an unaggregated discovery document. The [discovery document](https://github.com/kubernetes/kubernetes/blob/release-{{< skew currentVersion >}}/api/discovery/aggregated_v2.json) The [discovery document](https://github.com/kubernetes/kubernetes/blob/release-{{< skew currentVersion >}}/api/discovery/aggregated_v2beta1.json) for the built-in resources can be found in the Kubernetes GitHub repository. This Github document can be used as a reference of the base set of the available resources if a Kubernetes cluster is not available to query."} {"_id":"q-en-website-26612dfca3f1393a3115df5da85058c2de3b7d1b36960608a6b045e506415203","text":"sudo install minikube /usr/local/bin/ ``` ### Homebrewを利用したMinikubeのインストール 別の選択肢として、Linux [Homebrew](https://docs.brew.sh/Homebrew-on-Linux)を利用してインストールできます。 ```shell brew install minikube ``` {{% /tab %}} {{% tab name=\"macOS\" %}} ### kubectlのインストール"} {"_id":"q-en-website-27c16931576501f4395a97d060bb8e2660f6653de43b9757c292dd724afbcf16","text":"# List Names of Pods that belong to Particular RC # \"jq\" command useful for transformations that are too complex for jsonpath $ sel=$(./kubectl get rc --output=json | jq -j '.spec.selector | to_entries | .[] | \"(.key)=(.value),\"') $ sel=$(kubectl get rc --output=json | jq -j '.spec.selector | to_entries | .[] | \"(.key)=(.value),\"') $ sel=${sel%?} # Remove trailing comma $ pods=$(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})` $ pods=$(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name}) $ echo $pods # Check which nodes are ready $ kubectl get nodes -o jsonpath='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}'| tr ';' \"n\" | grep \"Ready=True\" $ kubectl get nodes -o jsonpath='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}'| tr ';' \"n\" | grep \"Ready=True\" ``` ## Modifying and Deleting Resources"} {"_id":"q-en-website-27f7786987d463a66584fe9a1175999ee75fa1bf5bd58e747f05b8af00257937","text":"

{{< note >}}

If you are trying this after the previous section, you may have deleted the Service exposing the Deployment. In that case, please expose the Deployment again using the following command:

kubectl expose deployment/kubernetes-bootcamp --type=\"NodePort\" --port 8080

If you are trying this after the previous section , then you may have deleted the service you created, or have created a Service of type: NodePort. In this section, it is assumed that a service with type: LoadBalancer is created for the kubernetes-bootcamp Deployment.

If you have not deleted the Service created in the previous section, first delete that Service and then run the following command to create a new Service with its type set to LoadBalancer:

kubectl expose deployment/kubernetes-bootcamp --type=\"LoadBalancer\" --port 8080

{{< /note >}}
"} {"_id":"q-en-website-2808cb17b50a39d3a55faee0151b1d458f94b49bc31f704d889115029e37d94b","text":"尽管 Daemon Pods 遵循[污点和容忍度](/zh/docs/concepts/scheduling-eviction/taint-and-toleration) 规则,根据相关特性,控制器会自动将以下容忍度添加到 DaemonSet Pod: | 容忍度键名 | 效果 | 版本 | 描述 | | 容忍度键名 | 效果 | 版本 | 描述 | | ---------------------------------------- | ---------- | ------- | ------------------------------------------------------------ | | `node.kubernetes.io/not-ready` | NoExecute | 1.13+ | 当出现类似网络断开的情况导致节点问题时,DaemonSet Pod 不会被逐出。 | | `node.kubernetes.io/unreachable` | NoExecute | 1.13+ | 当出现类似于网络断开的情况导致节点问题时,DaemonSet Pod 不会被逐出。 | | `node.kubernetes.io/unreachable` | NoExecute | 1.13+ | 当出现类似于网络断开的情况导致节点问题时,DaemonSet Pod 不会被逐出。 | | `node.kubernetes.io/disk-pressure` | NoSchedule | 1.8+ | | | `node.kubernetes.io/memory-pressure` | NoSchedule | 1.8+ | | | `node.kubernetes.io/unschedulable` | NoSchedule | 1.12+ | DaemonSet Pod 能够容忍默认调度器所设置的 `unschedulable` 属性. |"} {"_id":"q-en-website-2884b7ae2be5007798ff769e504db00da1db3b22db68370343b59190cd57c862","text":"[main_read_more] other = \"Przeczytaj więcej\" [not_applicable] # Localization teams: it's OK to use a longer text here other = \"nie dotyczy\" [note] other = \"Informacja:\""} {"_id":"q-en-website-2a9a56b8cd4a09e162b2c108b25e6b79bcc763dd5df67f658dae4658da0548e4","text":"In general, Pods remain until a human or {{< glossary_tooltip term_id=\"controller\" text=\"controller\" >}} process explicitly removes them. The control plane cleans up terminated Pods (with a phase of `Succeeded` or The control plane cleans up terminated Pods (with a phase of `Succeeded` or `Failed`), when the number of Pods exceeds the configured threshold (determined by `terminated-pod-gc-threshold` in the kube-controller-manager). This avoids a resource leak as Pods are created and terminated over time."} {"_id":"q-en-website-2ac81321b2367fd129145d618ca60618907c7ed33392478936a24223cfdf8876","text":"Install and configure prerequisites: ```shell # Create the .conf file to load the modules at bootup cat < sudo modprobe overlay sudo modprobe br_netfilter"} {"_id":"q-en-website-2aea7305ee41ecb357f9090f1767875bc47b950ec902941424e95f10152796f4","text":"other = \"suggest an improvement\" [layouts_docs_partials_feedback_issue] other = \"Open an issue in the GitHub repo if you want to \" other = \"\"\"Open an issue in the [GitHub Repository](https://www.github.com/kubernetes/website/) if you want to \"\"\" [layouts_docs_partials_feedback_or] other = \"or\""} {"_id":"q-en-website-2b138d0d39e3f9ad260d2372d2b67dd4ac8fca76f01c167c349b6ba8c968e806","text":"* GCEPersistentDisk * AWSElasticBlockStore * AzureFile * FC (Fibre Channel) * NFS * iSCSI * RBD (Ceph Block Device) * CephFS * Cinder (OpenStack block storage) * Glusterfs * VsphereVolume * HostPath (single node testing only -- local storage is not supported in any way and WILL NOT WORK in a multi-node cluster)"} {"_id":"q-en-website-2b559e8a804fffbc6dbbae8c2f932594b75f3023af358bc41d0384b26dcf1d6a","text":"```shell sudo apt-get update sudo apt-get install -y apt-transport-https ca-certificates curl sudo apt-get install -y ca-certificates curl ``` {{< note >}} If you use Debian 9 (stretch) or earlier you would also need to install `apt-transport-https`: ```shell sudo apt-get install -y apt-transport-https ``` {{< /note >}} 2. Download the Google Cloud public signing key: ```shell"} {"_id":"q-en-website-2b7944161baf0fc4db09b3284f79b27b06cfd10a5ee2db53f1d21db37b56737f","text":"it is required by kubectl. When present, the value of this annotation must be a comma separated list of the group-kinds, in the fully-qualified name format, i.e. `.`. ### applyset.kubernetes.io/contains-group-resources (deprecated) {#applyset-kubernetes-io-contains-group-resources} Type: Annotation Example: `applyset.kubernetes.io/contains-group-resources: \"certificates.cert-manager.io,configmaps,deployments.apps,secrets,services\"` Used on: Objects being used as ApplySet parents. For Kubernetes version {{< skew currentVersion >}}, you can use this annotation on Secrets, ConfigMaps, or custom resources if the CustomResourceDefinition defining them has the `applyset.kubernetes.io/is-parent-type` label. Part of the specification used to implement [ApplySet-based pruning in kubectl](/docs/tasks/manage-kubernetes-objects/declarative-config/#alternative-kubectl-apply-f-directory-prune). This annotation is applied to the parent object used to track an ApplySet to optimize listing of ApplySet member objects. It is optional in the ApplySet specification, as tools can perform discovery or use a different optimization. However, in Kubernetes version {{< skew currentVersion >}}, it is required by kubectl. When present, the value of this annotation must be a comma separated list of the group-kinds, in the fully-qualified name format, i.e. `.`. {{< note >}} This annotation is currently deprecated and replaced by [`applyset.kubernetes.io/contains-group-kinds`](#applyset-kubernetes-io-contains-group-kinds), support for this will be removed in applyset beta or GA. {{< /note >}} ### applyset.kubernetes.io/id (alpha) {#applyset-kubernetes-io-id} Type: Label"} {"_id":"q-en-website-2bcda062b4d485ff145b87a9389d0b0e08d520a8d5616a79cf25395535081f0a","text":"hostNetwork: true containers: - name: konnectivity-server-container image: us.gcr.io/k8s-artifacts-prod/kas-network-proxy/proxy-server:v0.0.16 image: registry.k8s.io/kas-network-proxy/proxy-server:v0.0.32 command: [\"/proxy-server\"] args: [ \"--logtostderr=true\","} {"_id":"q-en-website-2c8cebfc0d1b4e8905fe78021c807726c483b55af008057d3fef334646d01298","text":" apiVersion: apps/v1 kind: Deployment metadata: name: retainkeys-demo spec: selector: matchLabels: app: nginx strategy: rollingUpdate: maxSurge: 30% template: metadata: labels: app: nginx spec: containers: - name: retainkeys-demo-ctr image: nginx "} {"_id":"q-en-website-2d5b5b14a95f746acc94f72c309d2b168886f5169d31f7c71d4f80990b11446f","text":"#### Terminating {{< feature-state for_k8s_version=\"v1.20\" state=\"alpha\" >}} {{< feature-state for_k8s_version=\"v1.22\" state=\"beta\" >}} `Terminating` is a condition that indicates whether an endpoint is terminating. For pods, this is any pod that has a deletion timestamp set."} {"_id":"q-en-website-2f5ca88ecbf619f213ca8167c67773b62a007c1e841485baa030eeddfb1ec82b","text":"$ kubectl get services --sort-by=.metadata.name # List pods Sorted by Restart Count $ kubectl get pods --sort-by=.status.containerStatuses[0].restartCount $ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' # Get the version label of all pods with label app=cassandra $ kubectl get pods --selector=app=cassandra rc -o 'jsonpath={.items[*].metadata.labels.version}'"} {"_id":"q-en-website-2f645eacb0b74cbb7b444e715e971ec1dad849e81b657e1df89d6f3caf3fba60","text":" --- title: リース content_type: concept weight: 30 --- しばしば分散システムでは共有リソースをロックしたりノード間の活動を調整する機構として\"リース\"が必要になります。 Kubernetesでは、\"リース\"のコンセプトは`coordination.k8s.io`APIグループの`Lease`オブジェクトに表されていて、ノードのハートビートやコンポーネントレベルのリーダー選出といったシステムにとって重要な機能に利用されています。 ## ノードハートビート Kubernetesでは、kubeletのノードハートビートをKubernetes APIサーバーに送信するのにLease APIが使われています。 各`Node`ごとに、`kube-node-lease`名前空間にノードとマッチする名前の`Lease`オブジェクトが存在します。 内部的には、kubeletのハートビートはこの`Lease`オブジェクトに対するUPDATEリクエストであり、Leaseの`spec.renewTime`フィールドを更新しています。 Kubernetesのコントロールプレーンはこのフィールドのタイムスタンプを見て、`Node`が利用可能かを判断しています。 詳しくは[Node Leaseオブジェクト](/ja/docs/concepts/architecture/nodes/#heartbeats)をご覧ください。 ## リーダー選出 Kubernetesでは、あるコンポーネントのインスタンスが常に一つだけ実行されていることを保証するためにもリースが利用されています。 これは`kube-controller-manager`や`kube-scheduler`といったコントロールプレーンのコンポーネントで、一つのインスタンスのみがアクティブに実行され、その他のインスタンスをスタンバイ状態とする必要があるような冗長構成を組むために利用されています。 ## APIサーバーのアイデンティティー {{< feature-state for_k8s_version=\"v1.26\" state=\"beta\" >}} Kubernetes v1.26から、各`kube-apiserver`はLease APIを利用して自身のアイデンティティーをその他のシステムに向けて公開するようになりました。 それ自体は特に有用ではありませんが、何台の`kube-apiserver`がKubernetesコントロールプレーンを稼働させているのかをクライアントが知るためのメカニズムを提供します。 kube-apiserverリースが存在することで、各kube-apiserver間の調整が必要となる可能性がある将来の機能が使えるようになります。 `kube-system`名前空間の`kube-apiserver-`という名前のリースオブジェクトを確認することで、各kube-apiserverが所有しているLeaseを確認することができます。 また、`k8s.io/component=kube-apiserver`ラベルセレクターを利用することもできます。 ```shell $ kubectl -n kube-system get lease -l k8s.io/component=kube-apiserver NAME HOLDER AGE kube-apiserver-c4vwjftbvpc5os2vvzle4qg27a kube-apiserver-c4vwjftbvpc5os2vvzle4qg27a_9cbf54e5-1136-44bd-8f9a-1dcd15c346b4 5m33s kube-apiserver-dz2dqprdpsgnm756t5rnov7yka kube-apiserver-dz2dqprdpsgnm756t5rnov7yka_84f2a85d-37c1-4b14-b6b9-603e62e4896f 4m23s kube-apiserver-fyloo45sdenffw2ugwaz3likua kube-apiserver-fyloo45sdenffw2ugwaz3likua_c5ffa286-8a9a-45d4-91e7-61118ed58d2e 4m43s ``` リースの名前に使われているSHA256ハッシュはkube-apiserverのOSホスト名に基づいています。各kube-apiserverはクラスター内で一意なホスト名を使用するように構成する必要があります。 同じホスト名を利用する新しいkube-apiserverインスタンスは、新しいリースオブジェクトを作成せずに、既存のLeaseを新しいインスタンスのアイデンティティーを利用して引き継ぎます。 kube-apiserverが使用するホスト名は`kubernetes.io/hostname`ラベルの値で確認できます。 ```shell $ kubectl -n kube-system get lease kube-apiserver-c4vwjftbvpc5os2vvzle4qg27a -o yaml ``` ```yaml apiVersion: coordination.k8s.io/v1 kind: Lease metadata: creationTimestamp: \"2022-11-30T15:37:15Z\" labels: k8s.io/component: kube-apiserver kubernetes.io/hostname: kind-control-plane name: kube-apiserver-c4vwjftbvpc5os2vvzle4qg27a namespace: kube-system resourceVersion: \"18171\" uid: d6c68901-4ec5-4385-b1ef-2d783738da6c spec: holderIdentity: kube-apiserver-c4vwjftbvpc5os2vvzle4qg27a_9cbf54e5-1136-44bd-8f9a-1dcd15c346b4 leaseDurationSeconds: 3600 renewTime: \"2022-11-30T18:04:27.912073Z\" ``` すでに存在しなくなったkube-apiserverの期限切れリースは、1時間後に新しいkube-apiserverによってガベージコレクションされます。 "} {"_id":"q-en-website-2f8898e80298d4f61865353c78dc22971aaedddd4cb4572b29b376bb4df6cdf7","text":"Help Labels Const Labels Deprecated Version "} {"_id":"q-en-website-30f8ecfc421b67cc877952ef25c2d5199a389114828f077e89524967b7151d73","text":"#### Manually provisioning a Regional PD PersistentVolume Dynamic provisioning is possible using a [StorageClass for GCE PD](/docs/concepts/storage/storage-classes/#gce). [StorageClass for GCE PD](/docs/concepts/storage/storage-classes/#gce-pd). Before creating a PersistentVolume, you must create the persistent disk: ```shell"} {"_id":"q-en-website-314932750d9cd59e2174cd67d5cbc43176be645546e435bf36a80de7c8b11b0f","text":" --- layout: blog title: \"k8s.gcr.io 重定向到 registry.k8s.io - 用户须知\" date: 2023-03-10T17:00:00.000Z slug: image-registry-redirect --- **作者**:Bob Killen (Google)、Davanum Srinivas (AWS)、Chris Short (AWS)、Frederico Muñoz (SAS Institute)、Tim Bannister (The Scale Factory)、Ricky Sadowski (AWS)、Grace Nguyen (Expo)、Mahamed Ali (Rackspace Technology)、Mars Toktonaliev(独立个人)、Laura Santamaria (Dell)、Kat Cosgrove (Dell) **译者**:Michael Yao (DaoCloud) 3 月 20 日星期一,k8s.gcr.io 仓库[被重定向到了社区拥有的仓库](https://kubernetes.io/blog/2022/11/28/registry-k8s-io-faster-cheaper-ga/): **registry.k8s.io** 。 ## 长话短说:本次变更须知 {#you-need-to-know} - 3 月 20 日星期一,来自 k8s.gcr.io 旧仓库的流量被重定向到了 registry.k8s.io, 最终目标是逐步淘汰 k8s.gcr.io。 - 如果你在受限的环境中运行,且你为 k8s.gcr.io 限定采用了严格的域名或 IP 地址访问策略, 那么 k8s.gcr.io 开始重定向到新仓库之后镜像拉取操作将不起作用。 - 少量非标准的客户端不会处理镜像仓库的 HTTP 重定向,将需要直接指向 registry.k8s.io。 - 本次重定向只是一个协助用户进行切换的权宜之计。弃用的 k8s.gcr.io 仓库将在某个时间点被淘汰。 **请尽快更新你的清单,尽快指向 registry.k8s.io。** - 如果你托管自己的镜像仓库,你可以将需要的镜像拷贝到自己的仓库,这样也能减少到社区所拥有仓库的流量压力。 如果你认为自己可能受到了影响,或如果你想知道本次变更的更多相关信息,请继续阅读下文。 ## 若我受到影响该怎样检查? {#how-can-i-check} 若要测试到 registry.k8s.io 的连通性,测试是否能够从 registry.k8s.io 拉取镜像, 可以在你所选的命名空间中执行类似以下的命令: ```shell kubectl run hello-world -ti --rm --image=registry.k8s.io/busybox:latest --restart=Never -- date ``` 当你执行上一条命令时,若一切工作正常,预期的输出如下: ```none $ kubectl run hello-world -ti --rm --image=registry.k8s.io/busybox:latest --restart=Never -- date Fri Feb 31 07:07:07 UTC 2023 pod \"hello-world\" deleted ``` ## 若我受到影响会看到哪种错误? {#what-kind-of-errors} 出现的错误可能取决于你正使用的容器运行时类别以及你被路由到的端点, 通常会出现 `ErrImagePull`、`ImagePullBackOff` 这类错误, 也可能容器创建失败时伴随着警告 `FailedCreatePodSandBox`。 以下举例的错误消息显示了由于未知的证书使得代理后的部署拉取失败: ```none FailedCreatePodSandBox: Failed to create pod sandbox: rpc error: code = Unknown desc = Error response from daemon: Head “https://us-west1-docker.pkg.dev/v2/k8s-artifacts-prod/images/pause/manifests/3.8”: x509: certificate signed by unknown authority ``` ## 哪些镜像会受影响? {#what-images-be-impacted} k8s.gcr.io 上的 **所有** 镜像都会受到本次变更的影响。 k8s.gcr.io 除了 Kubernetes 各个版本外还托管了许多镜像。 大量 Kubernetes 子项目也在其上托管了自己的镜像。 例如 `dns/k8s-dns-node-cache`、`ingress-nginx/controller` 和 `node-problem-detector/node-problem-detector` 这些镜像。 ## 我受影响了。我该怎么办? {#what-should-i-do} 若受影响的用户在受限的环境中运行,最好的办法是将必需的镜像拷贝到私有仓库,或在自己的仓库中配置一个直通缓存。 在仓库之间拷贝镜像可使用若干工具: [crane](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_copy.md) 就是其中一种工具,通过使用 `crane copy SRC DST` 可以将镜像拷贝到私有仓库。还有一些供应商特定的工具,例如 Google 的 [gcrane](https://cloud.google.com/container-registry/docs/migrate-external-containers#copy), 这个工具实现了类似的功能,但针对其平台自身做了一些精简。 ## 我怎样才能找到哪些镜像正使用旧仓库,如何修复? {#how-can-i-find-and-fix} **方案 1**: 试试[上一篇博文](https://kubernetes.io/blog/2023/02/06/k8s-gcr-io-freeze-announcement/#what-s-next)中所述的一条 kubectl 命令: ```shell kubectl get pods --all-namespaces -o jsonpath=\"{.items[*].spec.containers[*].image}\" | tr -s '[[:space:]]' 'n' | sort | uniq -c ``` **方案 2**:`kubectl` [krew](https://krew.sigs.k8s.io/) 的一个插件已被开发完成,名为 [`community-images`](https://github.com/kubernetes-sigs/community-images#kubectl-community-images), 它能够使用 k8s.gcr.io 端点扫描和报告所有正使用 k8s.gcr.io 的镜像。 如果你安装了 krew,你可以运行以下命令进行安装: ```shell kubectl krew install community-images ``` 并用以下命令生成一个报告: ```shell kubectl community-images ``` 对于安装和示例输出的其他方法,可以查阅代码仓库: [kubernetes-sigs/community-images](https://github.com/kubernetes-sigs/community-images)。 **方案 3**:如果你不能直接访问集群,或如果你管理了许多集群,最好的方式是在清单(manifest)和 Chart 中搜索 **\"k8s.gcr.io\"**。 **方案 4**:如果你想预防基于 k8s.gcr.io 的镜像在你的集群中运行,可以在 [AWS EKS 最佳实践代码仓库](https://github.com/aws/aws-eks-best-practices/tree/master/policies/k8s-registry-deprecation)中找到针对 [Gatekeeper](https://open-policy-agent.github.io/gatekeeper-library/website/) 和 [Kyverno](https://kyverno.io/) 的示例策略,这些策略可以阻止镜像被拉取。 你可以在任何 Kubernetes 集群中使用这些第三方策略。 **方案 5**:作为 **最后一个** 备选方案, 你可以使用[修改性质的准入 Webhook](/zh-cn/docs/reference/access-authn-authz/extensible-admission-controllers/#what-are-admission-webhooks) 来动态更改镜像地址。在更新你的清单之前这只应视为一个权宜之计。你可以在 [k8s-gcr-quickfix](https://github.com/abstractinfrastructure/k8s-gcr-quickfix) 中找到(第三方)可变性质的 Webhook 和 Kyverno 策略。 ## 为什么 Kubernetes 要换到一个全新的镜像仓库? {#why-did-k8s-change-registry} k8s.gcr.io 托管在一个 [Google Container Registry (GCR)](https://cloud.google.com/container-registry) 自定义的域中,这是专为 Kubernetes 项目搭建的域。自 Kubernetes 项目启动以来, 这个仓库一直运作良好,我们感谢 Google 提供这些资源,然而如今还有其他云提供商和供应商希望托管这些镜像, 以便为他们自己云平台上的用户提供更好的体验。除了去年 Google [捐赠 300 万美金的续延承诺](https://www.cncf.io/google-cloud-recommits-3m-to-kubernetes/)来支持本项目的基础设施外, Amazon Web Services (AWS) 也在[底特律召开的 Kubecon NA 2022 上发言](https://youtu.be/PPdimejomWo?t=236)公布了相当的捐赠金额。 AWS 能为用户提供更好的体验(距离用户更近的服务器 = 更快的下载速度),同时还能减轻 GCR 的出站带宽和成本。 有关此次变更的更多详情,请查阅 [registry.k8s.io:更快、成本更低且正式发布 (GA)](/blog/2022/11/28/registry-k8s-io-faster-cheaper-ga/)。 ## 为什么要设置重定向? {#why-is-a-redirect} 本项目在[去年发布 1.25 时切换至 registry.k8s.io](/blog/2022/11/28/registry-k8s-io-faster-cheaper-ga/); 然而,大多数镜像拉取流量仍被重定向到旧端点 k8s.gcr.io。 从项目角度看,这对我们来说是不可持续的,因为这样既没有完全利用其他供应商捐赠给本项目的资源, 也由于流量服务成本而使我们面临资金耗尽的危险。 重定向将使本项目能够利用这些新资源的优势,从而显著降低我们的出站带宽成本。 我们预计此次更改只会影响一小部分用户,他们可能在受限环境中运行 Kubernetes, 或使用了老旧到无法处理重定向行为的客户端。 ## k8s.gcr.io 将会怎样? {#what-will-happen-to-k8s-gcr-io} 除了重定向之外,k8s.gcr.io 将被冻结, [且在 2023 年 4 月 3 日之后将不会随着新的镜像而更新](/zh-cn/blog/2023/02/06/k8s-gcr-io-freeze-announcement/)。 `k8s.gcr.io` 将不再获取任何新的版本、补丁或安全更新。 这个旧仓库将继续保持可用,以帮助人们迁移,但在以后将会被彻底淘汰。 ## 我仍有疑问,我该去哪儿询问? {#what-should-i-go} 有关 registry.k8s.io 及其为何开发这个新仓库的更多信息,请参见 [registry.k8s.io:更快、成本更低且正式发布](/blog/2022/11/28/registry-k8s-io-faster-cheaper-ga/)。 如果你想了解镜像冻结以及最后一版可用镜像的更多信息,请参见博文: [k8s.gcr.io 镜像仓库将从 2023 年 4 月 3 日起被冻结](/zh-cn/blog/2023/02/06/k8s-gcr-io-freeze-announcement/)。 有关 registry.k8s.io 架构及其[请求处理决策树](https://github.com/kubernetes/registry.k8s.io/blob/8408d0501a88b3d2531ff54b14eeb0e3c900a4f3/cmd/archeio/docs/request-handling.md)的信息, 请查阅 [kubernetes/registry.k8s.io 代码仓库](https://github.com/kubernetes/registry.k8s.io)。 若你认为自己在使用新仓库和重定向时遇到 bug,请在 [kubernetes/registry.k8s.io 代码仓库](https://github.com/kubernetes/registry.k8s.io/issues/new/choose)中提出 Issue。 **请先检查是否有人提出了类似的 Issue,再行创建新 Issue。** "} {"_id":"q-en-website-315f26ef8256663f7b7b36471fa1f45f99d51eb83daf75670f2c5d6ba8794ebf","text":"``` {{% note %}} ページのweightについては、1、2、3…などの値を使用せず、10、20、30…のように一定の間隔を空けた方が賢明です。こうすることで、後で別のページを間に挿入できるようになります。 ページのweightについては、1、2、3…などの値を使用せず、10、20、30…のように一定の間隔を空けた方が賢明です。こうすることで、後で別のページを間に挿入できるようになります。さらに、同じディレクトリ(セクション)内の各ページのweightは、重複しないようにする必要があります。これにより、特にローカライズされたコンテンツでは、コンテンツが常に正しく整列されるようになります。 {{% /note %}} ### ドキュメントのメインメニュー"} {"_id":"q-en-website-32a0636e80b918d7df0c936c0bb8ce3181198de9469394c99fc801751f0ccdf7","text":"* Run etcd as a cluster of odd members. * etcd is a leader-based distributed system. Ensure that the leader periodically send heartbeats on time to all followers to keep the cluster stable. * etcd is a leader-based distributed system. Ensure that the leader periodically send heartbeats on time to all followers to keep the cluster stable. * Ensure that no resource starvation occurs. Performance and stability of the cluster is sensitive to network and disk IO. Any resource starvation can lead to heartbeat timeout, causing instability of the cluster. An unstable etcd indicates that no leader is elected. Under such circumstances, a cluster cannot make any changes to its current state, which implies no new pods can be scheduled. Performance and stability of the cluster is sensitive to network and disk I/O. Any resource starvation can lead to heartbeat timeout, causing instability of the cluster. An unstable etcd indicates that no leader is elected. Under such circumstances, a cluster cannot make any changes to its current state, which implies no new pods can be scheduled. * Keeping stable etcd clusters is critical to the stability of Kubernetes clusters. Therefore, run etcd clusters on dedicated machines or isolated environments for [guaranteed resource requirements](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/hardware.md#hardware-recommendations). * Keeping etcd clusters stable is critical to the stability of Kubernetes clusters. Therefore, run etcd clusters on dedicated machines or isolated environments for [guaranteed resource requirements](https://etcd.io/docs/current/op-guide/hardware/). * The minimum recommended version of etcd to run in production is `3.2.10+`. -->"} {"_id":"q-en-website-33bd69b4df54b230f0994b1d91a0767f79725ed37ec885611474f037c72c4388","text":"/api-ref/ https://github.com/kubernetes/kubernetes/milestones/ 301 /concepts/containers/container-lifecycle-hooks/ /docs/concepts/containers/container-lifecycle-hooks/ 301 /docs/ /docs/home/ 301 /docs/abstractions/controllers/petset/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/admin/ /docs/concepts/cluster-administration/cluster-administration-overview/ 301 /docs/admin/add-ons/ /docs/concepts/cluster-administration/addons/ 301"} {"_id":"q-en-website-33f65eeabba4ef58d2236965aa17a6ab9bd25330ccf2588938977a20d30f1b7f","text":"# i18n strings for the Chinese version of the site (https://kubernetes.io/zh-cn/) # 注意:修改此文件时请维持字符串名称的字母顺序并与英文版保持一致 # Avoid using conjunction_1. # Must match the context in layouts/shortcodes/release-data.html # Appears on https://kubernetes.io/releases/ # For example the \"and\" in \"Complete 1.25 Schedule and Changelog\" [conjunction_1] other = \"和\" [caution] other = \"注意:\""} {"_id":"q-en-website-34ee7b6ea76193ee5fd812fb642ec334687505b1a332704a4f8dae5b44a29432","text":"# Create temp directories to store files that will end up on other hosts mkdir -p /tmp/${HOST0}/ /tmp/${HOST1}/ /tmp/${HOST2}/ --> ```sh # 使用你的主机 IP 更新 HOST0、HOST1 和 HOST2 的 IP 地址 export HOST0=10.0.0.6"} {"_id":"q-en-website-35011cdb33f9025f0f9353b2dd166b32654f8230e54d5cbcbcfd4e14161fec82","text":"2. Download the Google Cloud public signing key: ```shell sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg sudo curl -fsSLo /etc/apt/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg ``` 3. Add the Kubernetes `apt` repository: ```shell echo \"deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list echo \"deb [signed-by=/etc/apt/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list ``` 4. Update `apt` package index with the new repository and install kubectl:"} {"_id":"q-en-website-350df2d28a825ed3605f936e762d3d32e06b459a42a12f4ea2dc4da912774637","text":"与 DaemonSet 中的 Pod 进行通信的几种可能模式如下: - **Push**:配置 DaemonSet 中的 Pod,将更新发送到另一个服务,例如统计数据库。 - **推送(Push)**:配置 DaemonSet 中的 Pod,将更新发送到另一个服务,例如统计数据库。 这些服务没有客户端。 - **NodeIP 和已知端口**:DaemonSet 中的 Pod 可以使用 `hostPort`,从而可以通过节点 IP"} {"_id":"q-en-website-36117ad8073541e26df610fb9ac1c28e8a5e88c794be2a19dfcec0c8a1efeeea","text":"

Once you've done that, move on to Using kubectl to create a Deployment.

"} {"_id":"q-en-website-36693364fcc455a543af11469c1a727f3caec5883d7de2b88299962414e6f6d1","text":"--- linktitle: Kubernetes Documentation title: Documentation sitemap: priority: 1.0 ---"} {"_id":"q-en-website-36cb4314acb3b4989e057d9330b7d061dc771b23e35bf6579dff9ada0f3cb4a7","text":"ready kubernetes cluster.local in-addr.arpa ip6.arpa { pods insecure upstream fallthrough in-addr.arpa ip6.arpa ttl 30 } prometheus :9153 proxy ./etc/resolv.conf forward ./etc/resolv.conf cache 30 loop reload"} {"_id":"q-en-website-36d6218ec04067f4e2772639e29c32e91c83effb278567495c3505b031aff033","text":"kubeadm join --token : --discovery-token-ca-cert-hash sha256: ``` To let kubectl work in the following steps, you need to run these commands as a regular user (which is part of the output above): ``` mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config ``` Make a record of the `kubeadm join` command that `kubeadm init` outputs. You will need this in a moment."} {"_id":"q-en-website-36f7ee84fb1689b680aaeb209cc6c0ca0fba46fec9623a10cd72e77706cfb918","text":"{{% capture overview %}} {{< feature-state state=\"beta\" >}} {{< feature-state state=\"beta\" for_k8s_version=\"v1.18\" >}} An increasing number of systems leverage a combination of CPUs and hardware accelerators to support latency-critical execution and high-throughput parallel computation. These include workloads in fields such as telecommunications, scientific computing, machine learning, financial services and data analytics. Such hybrid systems comprise a high performance environment."} {"_id":"q-en-website-3810f735fa6118ac594c15c876b4df562c069811c6259d3956f0b66b7f661165","text":"## {{% heading \"prerequisites\" %}} {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} {{< include \"task-tutorial-prereqs.md\" >}} "} {"_id":"q-en-website-38140e788b5e1dbce4f180ea39902f87c3603190a26e586d8f8f6ecd6f392a05","text":" --- reviewers: - freehan title: EndpointSlices content_type: concept weight: 60 description: >- La API de EndpointSlice es el mecanismo que Kubernetes utiliza para permitir que tu Servicio escale para manejar un gran número de backends, y permite que el cluster actualice tu lista de backends saludables eficientemente. --- {{< feature-state for_k8s_version=\"v1.21\" state=\"stable\" >}} La API _EndpointSlice_ de Kubernetes proporciona una forma de rastrear los endpoints de red dentro de un clúster Kubernetes. EndpointSlices ofrece una alternativa más escalable y extensible a [Endpoints].(/docs/concepts/services-networking/service/#endpoints). ## EndpointSlice API {#recurso-endpointslice} En Kubernetes, un EndpointSlice contiene referencias a un conjunto de endpoints de red. El plano de control crea automáticamente EndpointSlices para cualquier Servicio de Kubernetes que tenga especificado un {{< glossary_tooltip text=\"selector\" term_id=\"selector\" >}}. Estos EndpointSlices incluyen referencias a todos los Pods que coinciden con el selector de Servicio. Los EndpointSlices agrupan los endpoints de la red mediante combinaciones únicas de protocolo, número de puerto y nombre de Servicio. El nombre de un objeto EndpointSlice debe ser un [nombre de subdominio DNS](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names) válido. A modo de ejemplo, a continuación se muestra un objeto EndpointSlice de ejemplo, propiedad del servicio `example` Servicio Kubernetes. ```yaml apiVersion: discovery.k8s.io/v1 kind: EndpointSlice metadata: name: example-abc labels: kubernetes.io/service-name: example addressType: IPv4 ports: - name: http protocol: TCP port: 80 endpoints: - addresses: - \"10.1.2.3\" conditions: ready: true hostname: pod-1 nodeName: node-1 zone: us-west2-a ``` Por defecto, el plano de control crea y gestiona EndpointSlices para que no tengan más de 100 endpoints cada una. Puedes configurar esto con la bandera de funcionalidad `--max-endpoints-per-slice` {{< glossary_tooltip text=\"kube-controller-manager\" term_id=\"kube-controller-manager\" >}} hasta un máximo de 1000. EndpointSlices puede actuar como la fuente de verdad {{< glossary_tooltip term_id=\"kube-proxy\" text=\"kube-proxy\" >}} sobre cómo enrutar el tráfico interno. ### Tipos de dirección EndpointSlices admite tres tipos de direcciones: * IPv4 * IPv6 * FQDN (Fully Qualified Domain Name) Cada objeto `EndpointSlice` representa un tipo de dirección IP específico. Si tienes un servicio disponible a través de IPv4 e IPv6, habrá al menos dos objetos `EndpointSlice` (uno para IPv4 y otro para IPv6). ### Condiciones La API EndpointSlice almacena condiciones sobre los endpoints que pueden ser útiles para los consumidores. Las tres condiciones son `ready`, `serving` y `terminating`. #### Ready `ready` es una condición que corresponde a la condición `Ready` de un Pod. Un Pod en ejecución con la condición `Ready` establecida a `True` debería tener esta condición EndpointSlice también establecida a `true`. Por razones de compatibilidad, `ready` NUNCA es `true` cuando un Pod está terminando. Los consumidores deben referirse a la condición `serving` para inspeccionar la disponibilidad de los Pods que están terminando. La única excepción a esta regla son los servicios con `spec.publishNotReadyAddresses` a `true`. Los endpoints de estos servicios siempre tendrán la condición `ready` a `true`. #### Serving {{< feature-state for_k8s_version=\"v1.26\" state=\"stable\" >}} La condición `serving` es casi idéntica a la condición `ready`. La diferencia es que los consumidores de la API EndpointSlice deben comprobar la condición `serving` si se preocupan por la disponibilidad del pod mientras el pod también está terminando. {{< note >}} Aunque `serving` es casi idéntico a `ready`, se añadió para evitar romper el significado existente de `ready`. Podría ser inesperado para los clientes existentes si `ready` pudiera ser `true` para los endpoints de terminación, ya que históricamente los endpoints de terminación nunca se incluyeron en la API Endpoints o EndpointSlice para empezar. Por esta razón, `ready` es _siempre_ `false` para los puntos finales que terminan, y se ha añadido una nueva condición `serving` en la v1.20 para que los clientes puedan realizar un seguimiento de la disponibilidad de los pods que terminan independientemente de la semántica existente para `ready`. {{< /note >}} #### Terminating {{< feature-state for_k8s_version=\"v1.22\" state=\"beta\" >}} `Terminating` es una condición que indica si un endpoint está terminando. En el caso de los pods, se trata de cualquier pod que tenga establecida una marca de tiempo de borrado. ### Información sobre topología {#topology} Cada endpoint dentro de un EndpointSlice puede contener información topológica relevante. La información de topología incluye la ubicación del endpoint e información sobre el Nodo y la zona correspondientes. Estos están disponibles en los siguientes campos por endpoint en EndpointSlices: * `nodeName` - El nombre del Nodo en el que se encuentra este endpoint. * `zone` - La zona en la que se encuentra este punto final. {{< note >}} En la API v1, el endpoint `topology` se eliminó en favor de los campos dedicados `nodeName` y `zone`. La configuración de campos de topología arbitrarios en el campo `endpoint` de un recurso `EndpointSlice` ha quedado obsoleta y no se admite en la API v1. En su lugar, la API v1 permite establecer campos individuales `nodeName` y `zone`. Estos campos se traducen automáticamente entre versiones de la API. Por ejemplo, el valor de la clave \"topology.kubernetes.io/zone\" en el campo `topology` de la API v1beta1 es accesible como campo `zone` en la API v1. {{< /note >}} ### Administración En la mayoría de los casos, el plano de control (concretamente, el endpoint slice {{< glossary_tooltip text=\"controller\" term_id=\"controller\" >}}) crea y gestiona objetos EndpointSlice. Existe una variedad de otros casos de uso para EndpointSlices, como implementaciones de servicios Mesh, que podrían dar lugar a que otras entidades o controladores gestionen conjuntos adicionales de EndpointSlices. Para garantizar que varias entidades puedan gestionar EndpointSlices sin interferir unas con otras, Kubernetes define el parámetro {{< glossary_tooltip term_id=\"label\" text=\"label\" >}} `endpointslice.kubernetes.io/managed-by`, que indica la entidad que gestiona un EndpointSlice. El controlador de endpoint slice establece `endpointslice-controller.k8s.io` como valor para esta etiqueta en todos los EndpointSlices que gestiona. Otras entidades que gestionen EndpointSlices también deben establecer un valor único para esta etiqueta. ### Propiedad En la mayoría de los casos de uso, los EndpointSlices son propiedad del Servicio para el que el objeto EndpointSlices rastrea los endpoints. Esta propiedad se indica mediante una referencia de propietario en cada EndpointSlice, así como una etiqueta `kubernetes.io/service-name` que permite búsquedas sencillas de todos los EndpointSlices que pertenecen a un Servicio. ### Replicación de EndpointSlice En algunos casos, las aplicaciones crean recursos Endpoints personalizados. Para garantizar que estas aplicaciones no tengan que escribir simultáneamente en recursos Endpoints y EndpointSlice, el plano de control del clúster refleja la mayoría de los recursos Endpoints en los EndpointSlices correspondientes. The control plane mirrors Endpoints resources unless: El plano de control refleja los recursos de los Endpoints a menos que: * El recurso Endpoints tenga una etiqueta `endpointslice.kubernetes.io/skip-mirror` con el valor en `true`. * El recurso Endpoints tenga una anotación `control-plane.alpha.kubernetes.io/leader`. * El recurso de servicio correspondiente no existe. * El recurso Service correspondiente tiene un selector no nulo. Los recursos Endpoints individuales pueden traducirse en múltiples EndpointSlices. Esto ocurrirá si un recurso Endpoints tiene múltiples subconjuntos o incluye endpoints con múltiples familias IP (IPv4 e IPv6). Se reflejará un máximo de 1000 direcciones por subconjunto en EndpointSlices. ### Distribución de EndpointSlices Cada EndpointSlice tiene un conjunto de puertos que se aplica a todos los endpoints dentro del recurso. Cuando se utilizan puertos con nombre para un Servicio, los Pods pueden terminar con diferentes números de puerto de destino para el mismo puerto con nombre, requiriendo diferentes EndpointSlices. Esto es similar a la lógica detrás de cómo se agrupan los subconjuntos con Endpoints. El plano de control intenta llenar los EndpointSlices tanto como sea posible, pero no los reequilibra activamente. La lógica es bastante sencilla: 1. Iterar a través de los EndpointSlices existentes, eliminar los endpoints que ya no se deseen y actualizar los endpoints coincidentes que hayan cambiado. 2. Recorrer los EndpointSlices que han sido modificados en el primer paso y rellenarlos con los nuevos endpoints necesarios. 3. Si aún quedan nuevos endpoints por añadir, intente encajarlos en un slice que no se haya modificado previamente y/o cree otros nuevos. Es importante destacar que el tercer paso prioriza limitar las actualizaciones de EndpointSlice sobre una distribución perfectamente completa de EndpointSlices. Por ejemplo, si hay 10 nuevos endpoints que añadir y 2 EndpointSlices con espacio para 5 endpoints más cada uno, este enfoque creará un nuevo EndpointSlice en lugar de llenar los 2 EndpointSlices existentes. En otras palabras, es preferible una única creación de EndpointSlice que múltiples actualizaciones de EndpointSlice. Con kube-proxy ejecutándose en cada Nodo y vigilando los EndpointSlices, cada cambio en un EndpointSlice se vuelve relativamente caro ya que será transmitido a cada Nodo del cluster. Este enfoque pretende limitar el número de cambios que necesitan ser enviados a cada Nodo, incluso si puede resultar con múltiples EndpointSlices que no están llenos. En la práctica, esta distribución menos que ideal debería ser poco frecuente. La mayoría de los cambios procesados por el controlador EndpointSlice serán lo suficientemente pequeños como para caber en un EndpointSlice existente, y si no, es probable que pronto sea necesario un nuevo EndpointSlice de todos modos. Las actualizaciones continuas de los Despliegues también proporcionan un reempaquetado natural de los EndpointSlices con todos los Pods y sus correspondientes endpoints siendo reemplazados. ### Endpoints duplicados Debido a la naturaleza de los cambios de EndpointSlice, los endpoints pueden estar representados en más de un EndpointSlice al mismo tiempo. Esto ocurre de forma natural, ya que los cambios en diferentes objetos EndpointSlice pueden llegar a la vigilancia / caché del cliente de Kubernetes en diferentes momentos. {{< note >}} Los clientes de la API EndpointSlice deben iterar a través de todos los EndpointSlices existentes asociados a un Servicio y construir una lista completa de endpoints de red únicos. Es importante mencionar que los endpoints pueden estar duplicados en diferentes EndpointSlices. Puede encontrar una implementación de referencia sobre cómo realizar esta agregación y deduplicación de endpoints como parte del código `EndpointSliceCache` dentro de `kube-proxy`. {{< /note >}} ## Comparación con endpoints {#motivación} La API Endpoints original proporcionaba una forma simple y directa de rastrear los puntos finales de red en Kubernetes. A medida que los clústeres de Kubernetes y los {{< glossary_tooltip text=\"Services\" term_id=\"service\" >}} crecían para manejar más tráfico y enviar más tráfico a más Pods backend, las limitaciones de la API original se hicieron más visibles. Más notablemente, estos incluyen desafíos con la ampliación a un mayor número de endpoints de red. Dado que todos los puntos finales de red para un Servicio se almacenaban en un único objeto Endpoints, esos objetos Endpoints podían llegar a ser bastante grandes. Para los servicios que permanecían estables (el mismo conjunto de puntos finales durante un largo período de tiempo), el impacto era menos notable; incluso entonces, algunos casos de uso de Kubernetes no estaban bien servidos. Cuando un servicio tenía muchos puntos finales de backend y la carga de trabajo se escalaba con frecuencia o se introducían nuevos cambios con frecuencia, cada actualización del objeto Endpoints para ese servicio suponía mucho tráfico entre los componentes del clúster de Kubernetes (dentro del plano de control y también entre los nodos y el servidor de API). Este tráfico adicional también tenía un coste en términos de uso de la CPU. Con EndpointSlices, la adición o eliminación de un único Pod desencadena el mismo _número_ de actualizaciones a los clientes que están pendientes de los cambios, pero el tamaño de esos mensajes de actualización es mucho menor a gran escala. EndpointSlices también ha permitido innovar en torno a nuevas funciones, como las redes de doble pila y el enrutamiento con conocimiento de la topología. ## {{% heading \"whatsnext\" %}} * Sigue las instrucciones del tutorial [Conexión de aplicaciones con servicios](/docs/tutorials/services/connect-applications-service/) * Lee la [Referencia API](/docs/reference/kubernetes-api/service-resources/endpoint-slice-v1/) para la API EndpointSlice * Lee la [Referencia API](/docs/reference/kubernetes-api/service-resources/endpoints-v1/) para la API Endpoints "} {"_id":"q-en-website-39421cef70378c68b6b99bfb568d3ecd8df83a3bd919d119cff8b1fd44f1ecdf","text":"2. Download the Google Cloud public signing key: ```shell sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg sudo curl -fsSLo /etc/apt/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg ``` 3. Add the Kubernetes `apt` repository: ```shell echo \"deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list echo \"deb [signed-by=/etc/apt/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list ``` 4. Update `apt` package index, install kubelet, kubeadm and kubectl, and pin their version:"} {"_id":"q-en-website-3a57be040c5aa44bf9b8f9d60fd25328dca83b5552d60e97a0e53df4a94bc805","text":"spec: containers: - name: php-redis image: gcr.io/google_samples/gb-frontend:v5 image: us-docker.pkg.dev/google-samples/containers/gke/gb-frontend:v5 env: - name: GET_HOSTS_FROM value: \"dns\""} {"_id":"q-en-website-3a980dd42cf952d1a0bdcaa513f55b644754765ba40dcc04e4791859ade5c9c0","text":"--> ## 资源要求 使用有限的资源运行 etcd 只适合测试目的。为了在生产中部署,需要先进的硬件配置。在生产中部署 etcd 之前,请查看[所需资源参考文档](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/hardware.md#example-hardware-configurations)。 使用有限的资源运行 etcd 只适合测试目的。为了在生产中部署,需要先进的硬件配置。 在生产中部署 etcd 之前,请查看 [所需资源参考文档](https://etcd.io/docs/current/op-guide/hardware/#example-hardware-configurations)。 ## 启动 etcd 集群"} {"_id":"q-en-website-3de6b906061edde18e657751bd0e4b44d113c0911f33c833315edaadffe5051d","text":" --- title: \"Kubernetesオブジェクトの管理\" description: Kubernetes APIと対話するための宣言型および命令型のパラダイム。 weight: 25 --- "} {"_id":"q-en-website-3f82c93eaec524eed6a9a3776c4ca7705e5c154c3dcdb5a78eda9a9f1d54c03c","text":"[downward API](/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/). User defined environment variables from the Pod definition are also available to the Container, as are any environment variables specified statically in the Docker image. as are any environment variables specified statically in the container image. ### Cluster information A list of all services that were running when a Container was created is available to that Container as environment variables. This list is limited to services within the same namespace as the new Container's Pod and Kubernetes control plane services. Those environment variables match the syntax of Docker links. For a service named *foo* that maps to a Container named *bar*, the following variables are defined:"} {"_id":"q-en-website-3f9d45485ef224d91d1e40d14103378a891eaa5edb56e9ae7b411fa5061cf320","text":"kubectl label nodes --all node.kubernetes.io/exclude-from-external-load-balancers- ``` ### Joining your nodes {#join-nodes} The nodes are where your workloads (containers and Pods, etc) run. To add new nodes to your cluster do the following for each machine: * SSH to the machine * Become root (e.g. `sudo su -`) * [Install a runtime](/docs/setup/production-environment/tools/kubeadm/install-kubeadm/#installing-runtime) if needed * Run the command that was output by `kubeadm init`. For example: ```bash kubeadm join --token : --discovery-token-ca-cert-hash sha256: ``` If you do not have the token, you can get it by running the following command on the control-plane node: ```bash kubeadm token list ``` The output is similar to this: ```console TOKEN TTL EXPIRES USAGES DESCRIPTION EXTRA GROUPS 8ewj1p.9r9hcjoqgajrj4gi 23h 2018-06-12T02:51:28Z authentication, The default bootstrap system: signing token generated by bootstrappers: 'kubeadm init'. kubeadm: default-node-token ``` By default, tokens expire after 24 hours. If you are joining a node to the cluster after the current token has expired, you can create a new token by running the following command on the control-plane node: ```bash kubeadm token create ``` The output is similar to this: ### Adding more control plane nodes ```console 5didvk.d09sbcov8ph2amjw ``` If you don't have the value of `--discovery-token-ca-cert-hash`, you can get it by running the following command chain on the control-plane node: ```bash openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //' ``` The output is similar to: ```console 8cb2de97839780a412b93877f8507ad6c94f73add17d5d7058e91741c9d5ec78 ``` {{< note >}} To specify an IPv6 tuple for `:`, IPv6 address must be enclosed in square brackets, for example: `[2001:db8::101]:2073`. {{< /note >}} See [Creating Highly Available Clusters with kubeadm](/docs/setup/production-environment/tools/kubeadm/high-availability/) for steps on creating a high availability kubeadm cluster by adding more control plane nodes. The output should look something like: ### Adding worker nodes {#join-nodes} ``` [preflight] Running pre-flight checks The worker nodes are where your workloads run. ... (log output of join workflow) ... The following pages show how to add Linux and Windows worker nodes to the cluster by using the `kubeadm join` command: Node join complete: * Certificate signing request sent to control-plane and response received. * Kubelet informed of new secure connection details. Run 'kubectl get nodes' on control-plane to see this machine join. ``` A few seconds later, you should notice this node in the output from `kubectl get nodes` when run on the control-plane node. {{< note >}} As the cluster nodes are usually initialized sequentially, the CoreDNS Pods are likely to all run on the first control-plane node. To provide higher availability, please rebalance the CoreDNS Pods with `kubectl -n kube-system rollout restart deployment coredns` after at least one new node is joined. {{< /note >}} * [Adding Linux worker nodes](/docs/tasks/administer-cluster/kubeadm/adding-linux-nodes/) * [Adding Windows worker nodes](/docs/tasks/administer-cluster/kubeadm/adding-windows-nodes/) ### (Optional) Controlling your cluster from machines other than the control-plane node"} {"_id":"q-en-website-409f282f1255b4c68fc6aec33abddd59c305d0b2adcfac5f8fb4302d189d88fe","text":"

Create a TLS secret from the given public/private key pair.

The public/private key pair must exist beforehand. The public key certificate must be .PEM encoded and match the given private key.

Usage

$ kubectl create tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run=server|client|none]

$ kubectl create secret tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run=server|client|none]

Flags

"} {"_id":"q-en-website-414e0cc924f609a7ad189f20c06598bfb8361894034b43934a250e947d35ecb3","text":"### CRIの設定 {#cri-configuration} CRIランタイムのセットアップに関するさらなる詳細は、[CRIのインストール](/docs/setup/cri/)を参照してください。 CRIランタイムのセットアップに関するさらなる詳細は、[コンテナランタイム](/ja/docs/setup/production-environment/container-runtimes/)を参照してください。 #### {{< glossary_tooltip term_id=\"containerd\" >}}"} {"_id":"q-en-website-42a6a5058f80f3958daf396e05b7a3fccd49505f0740387b2d79039465f09d26","text":"### Create a CertificateSigningRequest {#create-certificatessigningrequest} Create a CertificateSigningRequest and submit it to a Kubernetes Cluster via kubectl. Below is a script to generate the CertificateSigningRequest. Create a [CertificateSigningRequest](/docs/reference/kubernetes-api/authentication-resources/certificate-signing-request-v1/) and submit it to a Kubernetes Cluster via kubectl. Below is a script to generate the CertificateSigningRequest. ```shell cat < A `PersistentVolume` can be mounted on a host in any way supported by the resource provider. Providers will have different capabilities and each PV's access modes are set to the specific modes supported by that particular volume. For example, NFS can support multiple read/write clients, but a specific NFS PV might be exported on the server as read-only. Each PV gets its own set of access modes describing that specific PV's capabilities. A `PersistentVolume` can be mounted on a host in any way supported by the resource provider. As shown in the table below, providers will have different capabilities and each PV's access modes are set to the specific modes supported by that particular volume. For example, NFS can support multiple read/write clients, but a specific NFS PV might be exported on the server as read-only. Each PV gets its own set of access modes describing that specific PV's capabilities. The access modes are:"} {"_id":"q-en-website-46daaa9a0503432ae6e9cf07f2d6c47dc0c309ff7e74a27c2a80744ef802461c","text":"spec: containers: - name: follower image: gcr.io/google_samples/gb-redis-follower:v2 image: us-docker.pkg.dev/google-samples/containers/gke/gb-redis-follower:v2 resources: requests: cpu: 100m"} {"_id":"q-en-website-483f7d72bd858286d49f8bc3b74d0b083a825a8b1fc63660b886931084c3bf6e","text":"Network policies are implemented by the [network plugin](/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/). To use network policies, you must be using a networking solution which supports NetworkPolicy. Creating a NetworkPolicy resource without a controller that implements it will have no effect. ## Isolated and Non-isolated Pods ## The Two Sorts of Pod Isolation By default, pods are non-isolated; they accept traffic from any source. There are two sorts of isolation for a pod: isolation for egress, and isolation for ingress. They concern what connections may be established. \"Isolation\" here is not absolute, rather it means \"some restrictions apply\". The alternative, \"non-isolated for $direction\", means that no restrictions apply in the stated direction. The two sorts of isolation (or not) are declared independently, and are both relevant for a connection from one pod to another. Pods become isolated by having a NetworkPolicy that selects them. Once there is any NetworkPolicy in a namespace selecting a particular pod, that pod will reject any connections that are not allowed by any NetworkPolicy. (Other pods in the namespace that are not selected by any NetworkPolicy will continue to accept all traffic.) By default, a pod is non-isolated for egress; all outbound connections are allowed. A pod is isolated for egress if there is any NetworkPolicy that both selects the pod and has \"Egress\" in its `policyTypes`; we say that such a policy applies to the pod for egress. When a pod is isolated for egress, the only allowed connections from the pod are those allowed by the `egress` list of some NetworkPolicy that applies to the pod for egress. The effects of those `egress` lists combine additively. Network policies do not conflict; they are additive. If any policy or policies select a pod, the pod is restricted to what is allowed by the union of those policies' ingress/egress rules. Thus, order of evaluation does not affect the policy result. By default, a pod is non-isolated for ingress; all inbound connections are allowed. A pod is isolated for ingress if there is any NetworkPolicy that both selects the pod and has \"Ingress\" in its `policyTypes`; we say that such a policy applies to the pod for ingress. When a pod is isolated for ingress, the only allowed connections into the pod are those from the pod's node and those allowed by the `ingress` list of some NetworkPolicy that applies to the pod for ingress. The effects of those `ingress` lists combine additively. For a network flow between two pods to be allowed, both the egress policy on the source pod and the ingress policy on the destination pod need to allow the traffic. If either the egress policy on the source, or the ingress policy on the destination denies the traffic, the traffic will be denied. Network policies do not conflict; they are additive. If any policy or policies apply to a given pod for a given direction, the connections allowed in that direction from that pod is the union of what the applicable policies allow. Thus, order of evaluation does not affect the policy result. For a connection from a source pod to a destination pod to be allowed, both the egress policy on the source pod and the ingress policy on the destination pod need to allow the connection. If either side does not allow the connection, it will not happen. ## The NetworkPolicy resource {#networkpolicy-resource}"} {"_id":"q-en-website-4890bc5d3f9f6e6cb134dd0e31970e613b19e1273989a0601d85dd0f1462a77c","text":"localization's two-letter language code. For example, the two-letter code for Korean is `ko`. Some languages use a lowercase version of the country code as defined by the ISO-3166 along with their language codes. For example, the Brazilian Portuguese language code is `pt-br`. ### Fork and clone the repo First, [create your own"} {"_id":"q-en-website-4bc6dc0312265d44e1fd7747a594bc0a1ae2f8a31cf7a4d9a255a991790e2944","text":"[deprecation_file_warning] other = \"Przestarzały\" [dockershim_message] other = \"\"\"Dockershim został usunięty z projektu Kubernetes w wydaniu 1.24. Po dalsze informacje zajrzyj do Dockershim Removal FAQ.\"\"\" [docs_label_browse] other = \"Przeglądaj dokumentację\""} {"_id":"q-en-website-500441876ff682c0561bbcf65bf0a404c17a4bbcf6b1a76bf2de8d8384fa23b7","text":"是集群范围资源用量数据的聚合器。 默认情况下,在由 `kube-up.sh` 脚本创建的集群中会以 Deployment 的形式被部署。 如果你使用其他 Kubernetes 安装方法,则可以使用提供的 [部署组件 components.yaml](https://github.com/kubernetes-incubator/metrics-server/tree/master/deploy) [部署组件 components.yaml](https://github.com/kubernetes-sigs/metrics-server/releases) 来部署。 ### 内置快照 etcd 支持内置快照,因此备份 etcd 集群很容易。快照可以从使用 `etcdctl snapshot save` 命令的活动成员中获取,也可以通过从 etcd [数据目录](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/configuration.md#--data-dir)复制 `member/snap/db` 文件,该 etcd 数据目录目前没有被 etcd 进程使用。获取快照通常不会影响成员的性能。 etcd 支持内置快照。快照可以从使用 `etcdctl snapshot save` 命令的活动成员中获取, 也可以通过从 etcd [数据目录](https://etcd.io/docs/current/op-guide/configuration/#--data-dir) 复制 `member/snap/db` 文件,该 etcd 数据目录目前没有被 etcd 进程使用。获取快照不会影响成员的性能。 下面是一个示例,用于获取 `$ENDPOINT` 所提供的键空间的快照到文件 `snapshotdb`: ```sh ```shell ETCDCTL_API=3 etcdctl --endpoints $ENDPOINT snapshot save snapshotdb # exit 0 ``` # verify the snapshot 验证快照: ```shell ETCDCTL_API=3 etcdctl --write-out=table snapshot status snapshotdb ``` ```console +----------+----------+------------+------------+ | HASH | REVISION | TOTAL KEYS | TOTAL SIZE | +----------+----------+------------+------------+"} {"_id":"q-en-website-55dfa405bbebed525fd40b156d11d8e94935d2d5924b7c7e32734da1558e8fb1","text":"/docs/user-guide/persistent-volumes/index /docs/concepts/storage/persistent-volumes/ 301 /docs/user-guide/persistent-volumes/index.md /docs/concepts/storage/persistent-volumes/ 301 /docs/user-guide/persistent-volumes/walkthrough/ /docs/tasks/configure-pod-container/configure-persistent-volume-storage/ 301 /docs/user-guide/petset/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/user-guide/petset/bootstrapping/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/user-guide/pod-preset/ /docs/tasks/inject-data-application/podpreset/ 301 /docs/user-guide/pod-security-policy/ /docs/concepts/policy/pod-security-policy/ 301 /docs/user-guide/pod-states/ /docs/concepts/workloads/pods/pod-lifecycle/ 301"} {"_id":"q-en-website-56cbfdf8db340b82476138aca403be0cb890e2107ddb7592d0a775bdfaa4e9e4","text":"# Install Docker CE apt-get update && apt-get install -y containerd.io=1.2.13-2 docker-ce=5:19.03.11~3-0~~ubuntu-$(lsb_release -cs) docker-ce-cli=5:19.03.11~3-0~~ubuntu-$(lsb_release -cs) docker-ce=5:19.03.11~3-0~ubuntu-$(lsb_release -cs) docker-ce-cli=5:19.03.11~3-0~ubuntu-$(lsb_release -cs) ``` ```shell"} {"_id":"q-en-website-58191702761c7a9af9304441d771b092958c2e3a50390787babc24e82231fbee","text":"- Administrators should limit access to etcd to admin users - Secret data in the API server is at rest on the disk that etcd uses; admins may want to wipe/shred disks used by etcd when no longer in use - If you configure the secret through a manifest (JSON or YAML) file which has the secret data encoded as base64, sharing this file or checking it in to a source repository means the secret is compromised. Base64 encoding is not an encryption method and is considered the same as plain text. - Applications still need to protect the value of secret after reading it from the volume, such as not accidentally logging it or transmitting it to an untrusted party. - A user who can create a pod that uses a secret can also see the value of that secret. Even"} {"_id":"q-en-website-588802df3a149d5e4da715184c7686c95d75c122693df1dc1ae22bf4182474aa","text":"you implement yourself * using the [Operator Framework](https://operatorframework.io) * [Publish](https://operatorhub.io/) your operator for other people to use * Read [CoreOS' original article](https://coreos.com/blog/introducing-operators.html) that introduced the Operator pattern * Read [CoreOS' original article](https://web.archive.org/web/20170129131616/https://coreos.com/blog/introducing-operators.html) that introduced the Operator pattern (this is an archived version of the original article). * Read an [article](https://cloud.google.com/blog/products/containers-kubernetes/best-practices-for-building-kubernetes-operators-and-stateful-apps) from Google Cloud about best practices for building Operators"} {"_id":"q-en-website-58d262f4d1a656a81f8d03279f4e413484350942e9e437a629e72f21167dec8a","text":"{{< feature-state for_k8s_version=\"v1.19\" state=\"stable\" >}} A CertificateSigningRequest (CSR) resource is used to request that a certificate be signed A [CertificateSigningRequest](/docs/reference/kubernetes-api/authentication-resources/certificate-signing-request-v1/) (CSR) resource is used to request that a certificate be signed by a denoted signer, after which the request may be approved or denied before finally being signed."} {"_id":"q-en-website-59347853def2cadc22d2ef068e70906be8956864ea1e58f05b7582c6babfd312","text":"* Block device mapping * Memory as the storage medium (for example, `emptyDir.medium` set to `Memory`) * File system features like uid/gid; per-user Linux filesystem permissions * Setting [secret permissions with DefaultMode](/docs/concepts/configuration/secret/#secret-files-permissions) (due to UID/GID dependency) * Setting [secret permissions with DefaultMode](/docs/tasks/inject-data-application/distribute-credentials-secure/#set-posix-permissions-for-secret-keys) (due to UID/GID dependency) * NFS based storage/volume support * Expanding the mounted volume (resizefs)"} {"_id":"q-en-website-59c9f183c5cf68fd5f27b47444e2861f7ae34637d991a79b85e77818e4e32062","text":"[community_youtube_name] other = \"YouTube\" [cve_id] other = \"CVE ID\" [cve_issue_url] other = \"CVE GitHub Issue URL\" [cve_json_external_url] other = \"external_url\" [cve_json_id] other = \"id\" [cve_json_summary] other = \"概要\" [cve_json_url] other = \"url\" [cve_summary] other = \"问题描述\" [cve_table] other = \"Kubernetes CVE 列表\" [cve_url] other = \"CVE URL\" [deprecation_title] other = \"您正在查看 Kubernetes 版本的文档:\" other = \"你正在查看的文档所针对的是 Kubernetes 版本:\" [deprecation_warning] other = \" 版本的文档已不再维护。您现在看到的版本来自于一份静态的快照。如需查阅最新文档,请点击\" other = \" 版本的文档已不再维护。你现在看到的版本来自于一份静态的快照。如需查阅最新文档,请点击\" [deprecation_file_warning] other = \"已过时\""} {"_id":"q-en-website-5ae7f52673a01f483f925a5f36a93ca013cc19d299e3a8c2a072eee1183e5746","text":"``` Serviços possuem endereço IP dedicado e são disponibilizados para o contêiner via DNS, se possuírem [DNS addon](https://releases.k8s.io/{{< param \"githubbranch\" >}}/cluster/addons/dns/) habilitado. se possuírem [DNS addon](https://releases.k8s.io/{{< param \"fullversion\" >}}/cluster/addons/dns/) habilitado. "} {"_id":"q-en-website-5b10f801f2390d7bff6268b1982bc3be835f9d41622ba751628cf3f8bd7bb584","text":" --- title: Job content_type: concept feature: title: バッチ実行 description: > Kubernetesはサービスに加えて、バッチやCIのワークロードを管理し、必要に応じて失敗したコンテナを置き換えることができます。 weight: 60 --- Jobは1つ以上のPodを作成し、指定された数のPodが正常に終了することを保証します。 JobはPodの正常終了を追跡します。正常終了が指定された回数に達すると、そのタスク(つまりJob)は完了します。Jobを削除すると、そのJobが作成したPodがクリーンアップされます。 簡単な例としては、1つのPodを確実に実行して完了させるために、1つのJobオブジェクトを作成することです。 ノードのハードウェア障害やノードの再起動などにより最初のPodが失敗したり削除されたりした場合、Jobオブジェクトは新たなPodを立ち上げます。 また、Jobを使用して複数のPodを並行して実行することもできます。 ## Jobの実行例 ここでは、Jobの設定例を示します。πの値を2000桁目まで計算して出力します。 完了までに10秒程度かかります。 {{< codenew file=\"controllers/job.yaml\" >}} このコマンドで例を実行できます。 ```shell kubectl apply -f https://kubernetes.io/examples/controllers/job.yaml ``` ``` job.batch/pi created ``` Jobのステータスは、`kubectl`を用いて確認します。 ```shell kubectl describe jobs/pi ``` ``` Name: pi Namespace: default Selector: controller-uid=c9948307-e56d-4b5d-8302-ae2d7b7da67c Labels: controller-uid=c9948307-e56d-4b5d-8302-ae2d7b7da67c job-name=pi Annotations: kubectl.kubernetes.io/last-applied-configuration: {\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"metadata\":{\"annotations\":{},\"name\":\"pi\",\"namespace\":\"default\"},\"spec\":{\"backoffLimit\":4,\"template\":... Parallelism: 1 Completions: 1 Start Time: Mon, 02 Dec 2019 15:20:11 +0200 Completed At: Mon, 02 Dec 2019 15:21:16 +0200 Duration: 65s Pods Statuses: 0 Running / 1 Succeeded / 0 Failed Pod Template: Labels: controller-uid=c9948307-e56d-4b5d-8302-ae2d7b7da67c job-name=pi Containers: pi: Image: perl Port: Host Port: Command: perl -Mbignum=bpi -wle print bpi(2000) Environment: Mounts: Volumes: Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal SuccessfulCreate 14m job-controller Created pod: pi-5rwd7 ``` Jobの完了したPodを表示するには、`kubectl get pods`を使います。 あるJobに属するすべてのPodの一覧を機械可読な形式で出力するには、次のようなコマンドを使います。 ```shell pods=$(kubectl get pods --selector=job-name=pi --output=jsonpath='{.items[*].metadata.name}') echo $pods ``` ``` pi-5rwd7 ``` ここでのセレクターは、Jobのセレクターと同じです。`--output = jsonpath`オプションは、返されたリストの各Podから名前だけを取得する式を指定します。 いずれかのPodの標準出力を表示します。 ```shell kubectl logs $pods ``` 出力例は以下の通りです。 ```shell 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632788659361533818279682303019520353018529689957736225994138912497217752834791315155748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035637076601047101819429555961989467678374494482553797747268471040475346462080466842590694912933136770289891521047521620569660240580381501935112533824300355876402474964732639141992726042699227967823547816360093417216412199245863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818347977535663698074265425278625518184175746728909777727938000816470600161452491921732172147723501414419735685481613611573525521334757418494684385233239073941433345477624168625189835694855620992192221842725502542568876717904946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886269456042419652850222106611863067442786220391949450471237137869609563643719172874677646575739624138908658326459958133904780275901 ``` ## Jobの仕様の作成 他のすべてのKubernetesの設定と同様に、Jobには`apiVersion`、` kind`、および`metadata`フィールドが必要です。 その名前は有効な[DNSサブドメイン名](/ja/docs/concepts/overview/working-with-objects/names#dns-subdomain-names)である必要があります。 Jobには[`.spec`セクション](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status)も必要です。 ### Podテンプレート `.spec.template`は、`.spec`の唯一の必須フィールドです。 `.spec.template`は[Podテンプレート](/ja/docs/concepts/workloads/pods/#pod-templates)です。 ネストされており、`apiVersion`や`kind`ないことを除けば、{{< glossary_tooltip text=\"Pod\" term_id=\"pod\" >}}とまったく同じスキーマを持ちます。 Podの必須フィールドに加えて、JobのPodテンプレートでは、適切なラベル([Podセレクター](#pod-selector)参照)と適切な再起動ポリシーを指定しなければなりません。 `Never`または`OnFailure`と等しい[`RestartPolicy`](/ja/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy)のみが許可されます。 ### Podセレクター {#pod-selector} `.spec.selector`フィールドはオプションです。ほとんどの場合、指定すべきではありません。 セクション「[独自のPodセレクターの指定](#specifying-your-own-pod-selector)」を参照してください。 ### Jobの並列実行 {#parallel-jobs} Jobとして実行するのに適したタスクは、大きく分けて3つあります。 1. 非並列Job - 通常は、Podが失敗しない限り、1つのPodのみが起動されます。 - そのPodが正常に終了するとすぐにJobが完了します。 2. *固定の完了数*を持つ並列Job - `.spec.completions`に、0以外の正の値を指定します。 - Jobはタスク全体を表し、1から`.spec.completions`の範囲内の各値に対して、1つの成功したPodがあれば完了です。 - **まだ実装されていません**が、各Podには、1から`.spec.completions`の範囲内で異なるインデックスが渡されます。 3. *ワークキュー*を持つ並列Job - `.spec.completions`は指定しません。デフォルトは`.spec.parallelism`です。 - Podは、それぞれが何を処理するか決定するために、 Pod間または外部サービス間で調整する必要があります。例えば、あるPodはワークキューから最大N個のアイテムのバッチを取得します。 - 各Podはすべてのピアが完了したかどうか、つまりJob全体が完了したかどうかを、独立して判断できます。 - Jobの _任意の_ Podが正常終了すると、新しいPodは作成されません。 - 少なくとも1つのPodが正常終了し、すべてのPodが終了すると、Jobは正常に完了します。 - Podが正常終了した後は、他のPodがこのタスクの処理を行ったり、出力を書き込んだりしてはなりません。それらはすべて終了する必要があります。 _非並列_ Jobの場合、`.spec.completions`と`.spec.parallelism`の両方を未設定のままにすることができます。両方が設定されていない場合、どちらもデフォルトで1になります。 _ワークキュー_ を持つJobの場合、`.spec.completions`を未設定のままにし、`.spec.parallelism`を非負整数にする必要があります。 様々な種類のJobを利用する方法の詳細については、セクション「[Jobのパターン](#job-patterns)」をご覧ください。 #### 並列処理の制御 並列処理数(`.spec.parallelism`)については、任意の非負整数を設定できます。 指定しない場合、デフォルトで1になります。 0を指定した場合、並列処理数が増えるまで、Jobは実質的に一時停止されます。 以下に挙げる様々な理由から、実際の並列処理数(任意の時点で実行されるPodの数)が、要求された数より多い場合と少ない場合があります。 - _固定完了数_ を持つJobの場合、並行して実行されるPodの実際の数は、残りの完了数を超えることはありません。`.spec.parallelism`の大きい値は事実上無視されます。 - _ワークキュー_ を持つJobの場合、Podが成功しても新しいPodは開始されません。ただし、残りのPodは完了できます。 - Jobコントローラー({{< glossary_tooltip term_id=\"controller\" >}})が反応する時間がない場合も考えられます。 - Jobコントローラーが何らかの理由(`ResourceQuota`がない、権限がないなど)でPodの作成に失敗した場合、要求された数よりも少ないPod数になる可能性があります。 - Jobコントローラーは、同じJob内で以前のPodが過剰に失敗したために、新しいPodの作成を調整する場合があります。 - Podをグレースフルにシャットダウンした場合、停止までに時間がかかります。 ## Podおよびコンテナの障害の処理 Pod内のコンテナは、その中のプロセスが0以外の終了コードで終了した、またはメモリー制限を超えたためにコンテナが強制終了されたなど、さまざまな理由で失敗する可能性があります。これが発生し、`.spec.template.spec.restartPolicy = \"OnFailure\"`であ場合、Podはノードに残りますが、コンテナは再実行されます。したがって、プログラムはローカルで再起動するケースを処理するか、`.spec.template.spec.restartPolicy = \"Never\"`を指定する必要があります。 `restartPolicy`の詳細な情報は、[Podのライフサイクル](/ja/docs/concepts/workloads/pods/pod-lifecycle/#example-states)を参照してください。 さまざまな理由で、Pod全体が失敗することもあります。例えば、Podが(ノードのアップグレード、再起動、削除などにより)ノードから切り離された場合や、Podのコンテナが失敗して`.spec.template.spec.restartPolicy = \"Never\"`が設定されている場合などです。Podが失敗した場合、Jobコントローラーは新しいPodを開始します。つまり、アプリケーションは新しいPodで再起動されたケースを処理する必要があります。特に、前の実行によって発生した一時ファイル、ロック、不完全な出力などに対する処理が必要です。 たとえ`.spec.parallelism = 1`、`.spec.completions = 1`、`.spec.template.spec.restartPolicy = \"Never\"`を指定しても、同じプログラムが2回起動される場合があることに注意してください。 `.spec.parallelism`と`.spec.completions`の両方を1より大きい値に指定した場合は、複数のPodが同時に実行される可能性があります。したがって、Podは同時実行性にも対応する必要があります。 ### Pod Backoff Failure Policy 構成の論理エラーなどが原因で、ある程度の再試行後にJobを失敗させたい場合があります。 そのためには、`.spec.backoffLimit`を設定して、Jobが失敗したと見なすまでの再試行回数を指定します。デフォルトでは6に設定されています。 失敗したPodは、6分を上限とする指数バックオフ遅延(10秒、20秒、40秒...)に従って、Jobコントローラーにより再作成されます。 JobのPodが削除されるか、Jobの他のPodがその時間に失敗することなく成功すると、バックオフカウントがリセットされます。 {{< note >}} Jobに`restartPolicy = \"OnFailure\"`がある場合、Jobのバックオフ制限に達すると、Jobを実行しているコンテナが終了することに注意してください。これにより、Jobの実行可能ファイルのデバッグがより困難になる可能性があります。Jobのデバッグするまたはロギングシステムを使用する場合は、`restartPolicy = \"Never\"`を設定して、失敗したJobからの出力が誤って失われないようにすることをお勧めします。 {{< /note >}} ## Jobの終了とクリーンアップ Jobが完了すると、Podは作成されなくなりますが、Podの削除も行われません。それらを保持しておくと、完了したPodのログを表示して、エラー、警告、またはその他の診断の出力を確認できます。 Jobオブジェクトは完了後も残るため、ステータスを表示できます。ステータスを確認した後、古いJobを削除するのはユーザーの責任です。`kubectl`(例えば`kubectl delete jobs/pi`や`kubectl delete -f ./job.yaml`)を用いてJobを削除してください。`kubectl`でJobを削除すると、Jobが作成したすべてのPodも削除されます。 デフォルトでは、Podが失敗する(`restartPolicy=Never`)かコンテナがエラーで終了する(`restartPolicy=OnFailure`)場合を除き、Jobは中断されずに実行されます。その時点でJobは上記の`.spec.backoffLimit`に従います。`.spec.backoffLimit`に達すると、Jobは失敗としてマークされ、実行中のPodはすべて終了されます。 Jobを終了する別の方法は、アクティブな期限を設定することです。 これを行うには、Jobの`.spec.activeDeadlineSeconds`フィールドを秒数に設定します `activeDeadlineSeconds`は、作成されたPodの数に関係なく、Jobの期間に適用されます。 Jobが`activeDeadlineSeconds`に到達すると、実行中のすべてのPodが終了し、Jobのステータスは`type: Failed`および`reason: DeadlineExceeded`となります。 Jobの`.spec.activeDeadlineSeconds`は、`.spec.backoffLimit`よりも優先されることに注意してください。したがって、1つ以上の失敗したPodを再試行しているJobは、`backoffLimit`にまだ達していない場合でも、`activeDeadlineSeconds`で指定された制限時間に達すると、追加のPodをデプロイしません。 以下に例を挙げます。 ```yaml apiVersion: batch/v1 kind: Job metadata: name: pi-with-timeout spec: backoffLimit: 5 activeDeadlineSeconds: 100 template: spec: containers: - name: pi image: perl command: [\"perl\", \"-Mbignum=bpi\", \"-wle\", \"print bpi(2000)\"] restartPolicy: Never ``` Job内のJobの仕様と[Podテンプレートの仕様](/ja/docs/concepts/workloads/pods/init-containers/#detailed-behavior)の両方に`activeDeadlineSeconds`フィールドがあることに注意してください。このフィールドが適切なレベルに設定されていることを確認してください。 `restartPolicy`はPodに適用され、Job自体には適用されないことに注意してください。Jobのステータスが`type: Failed`になると、Jobの自動再起動は行われません。 つまり、 `.spec.activeDeadlineSeconds`と`.spec.backoffLimit`でアクティブ化されるJob終了のメカニズムは、手作業での介入が必要になるような永続的なJobの失敗を引き起こします。 ## 終了したJobの自動クリーンアップ 終了したJobは、通常、もう必要ありません。それらをシステム内に保持すると、APIサーバーに負担がかかります。[CronJobs](/ja/docs/concepts/workloads/controllers/cron-jobs/)などの上位レベルのコントローラーによってJobが直接管理されている場合、指定された容量ベースのクリーンアップポリシーに基づいて、JobをCronJobsでクリーンアップできます。 ### 終了したJobのTTLメカニズム {{< feature-state for_k8s_version=\"v1.12\" state=\"alpha\" >}} 完了したJob(`Complete`または`Failed`)を自動的にクリーンアップする別の方法は、[TTLコントローラー](/ja/docs/concepts/workloads/controllers/ttlafterfinished/)が提供するTTLメカニズムを使用して、完了したリソースを指定することです。Jobの`.spec.ttlSecondsAfterFinished`フィールドに指定します。 TTLコントローラーがJobをクリーンアップすると、Jobが連鎖的に削除されます。つまり、Podなどの依存オブジェクトがJobとともに削除されます。Jobが削除されるとき、ファイナライザーなどのライフサイクル保証が優先されることに注意してください。 例は以下の通りです。 ```yaml apiVersion: batch/v1 kind: Job metadata: name: pi-with-ttl spec: ttlSecondsAfterFinished: 100 template: spec: containers: - name: pi image: perl command: [\"perl\", \"-Mbignum=bpi\", \"-wle\", \"print bpi(2000)\"] restartPolicy: Never ``` Job`pi-with-ttl`は、Jobが終了してから`100`秒後に自動的に削除される。 フィールドが`0`に設定されている場合は、Jobは終了後すぐに自動的に削除されます。フィールドが設定されていない場合は、このJobは終了後にTTLコントローラーによってクリーンアップされません。 このTTLメカニズムはアルファ版であり、`TTLAfterFinished`フィーチャーゲートであることに注意してください。詳細は[TTLコントローラー](/ja/docs/concepts/workloads/controllers/ttlafterfinished/)のドキュメントを参照してください。 ## Jobのパターン {#job-patterns} Jobオブジェクトは、Podの信頼性の高い並列実行をサポートするために使用できます。Jobオブジェクトは、科学的コンピューティングで一般的に見られるような、密接に通信する並列プロセスをサポートするようには設計されていません。しかし、独立しているが関連性のある*ワークアイテム*の集合の並列処理はサポートしています。 例えば送信する電子メール、レンダリングするフレーム、トランスコードするファイル、スキャンするNoSQLデータベースのキーの範囲などです。 複雑なシステムでは、複数の異なるワークアイテムの集合があるかもしれません。ここでは、ユーザーがまとめて管理したい作業項目の1つの集合(バッチJob)を考えています。 並列計算にはいくつかのパターンがあり、それぞれ長所と短所があります。 トレードオフは以下の通りです。 - 各ワークアイテムに1つのJobオブジェクトを使用する場合と、すべてのワークアイテムに1つのJobオブジェクトを使用する場合を比較すると、後者の方がワークアイテムの数が多い場合に適しています。前者では、ユーザーとシステムが大量のJobオブジェクトを管理するためのオーバーヘッドが発生します。 - 作成されたPodの数がワークアイテムの数に等しい場合と、各Podが複数のワークアイテムを処理する場合を比較すると、前者の方が一般的に既存のコードやコンテナへの変更が少ないです。後者は上記の項目と同様の理由で、大量のワークアイテムを処理するのに適しています。 - いくつかのアプローチでは、ワークキューを使用します。これはキューサービスを実行している必要があり、既存のプログラムやコンテナを変更してワークキューを使用するようにする必要があります。他のアプローチは、既存のコンテナ化されたアプリケーションに適応するのがさらに容易です。 ここでは、上記のトレードオフに対応するものを、2から4列目にまとめています。 パターン名は、例とより詳細な説明へのリンクでもあります。 | パターン名 | 単一のJobオブジェクト | ワークアイテムよりPodが少ないか? | アプリをそのまま使用するか? | Kube 1.1で動作するか? | | ----------------------------------------------------------------------------------------------- |:-----------------:|:---------------------------:|:-------------------:|:-------------------:| | [Jobテンプレートを拡張する](/ja/docs/tasks/job/parallel-processing-expansion/) | | | ✓ | ✓ | | [ワークアイテムごとにPodでキューを作成する](/ja/docs/tasks/job/coarse-parallel-processing-work-queue/) | ✓ | | 場合による | ✓ | | [Pod数が可変であるキューを作成する](/ja/docs/tasks/job/fine-parallel-processing-work-queue/) | ✓ | ✓ | | ✓ | | 単一のJob静的な処理を割り当てる | ✓ | | ✓ | | 完了数を`.spec.completions`で指定すると、Jobコントローラーが作成した各Podは同じ[`spec`](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status)を持ちます。つまり、あるタスクを実行するすべてのPodは、同じコマンドラインと同じイメージ、同じボリューム、そして(ほぼ)同じ環境変数を持ちます。これらのパターンは、Podが異なる処理を行うように配置するための様々な方法です。 以下の表では、パターンごとに必要な`.spec.parallelism`と`.spec.completions`の設定を示します。 ここで、`W`はワークアイテム数とします。 | パターン名 | `.spec.completions` | `.spec.parallelism` | | ----------------------------------------------------------------------------------------------- |:-------------------:|:--------------------:| | [Jobテンプレートを拡張する](/ja/docs/tasks/job/parallel-processing-expansion/) | 1 | 1とする必要あり | | [ワークアイテムごとにPodでキューを作成する](/ja/docs/tasks/job/coarse-parallel-processing-work-queue/) | W | 任意 | | [Pod数が可変であるキューを作成する](/ja/docs/tasks/job/fine-parallel-processing-work-queue/) | 1 | 任意 | | 単一のJob静的な処理を割り当てる | W | 任意 | ## 高度な使用方法 ### 独自のPodセレクターを指定する {#specifying-your-own-pod-selector} 通常、Jobオブジェクトを作成する際には`.spec.selector`を指定しません。 システムのデフォルトのロジックで、Jobの作成時にこのフィールドを追加します。 セレクターの値は、他のJobと重複しないように選択されます。 しかし、場合によっては、この自動的に設定されるセレクターを上書きする必要があるかもしれません。 これを行うには、Jobの`.spec.selector`を指定します。 これを行う際には十分に注意が必要です。もし指定したラベルセレクターが、そのJobのPodに対して固有でなく、無関係なPodにマッチする場合、無関係なJobのPodが削除されたり、このJobが他のPodを完了したものとしてカウントしたり、一方または両方のJobがPodの作成や完了まで実行を拒否することがあります。 もし固有でないセレクターを選択した場合は、他のコントローラー(例えばレプリケーションコントローラーなど)やそのPodも予測不能な動作をする可能性があります。Kubernetesは`.spec.selector`を指定する際のミスを防ぐことはできません。 ここでは、この機能を使いたくなるようなケースの例をご紹介します。 `old`というJobがすでに実行されているとします。既存のPodを実行し続けたいが、作成した残りのPodには別のPodテンプレートを使用し、Jobには新しい名前を付けたいとします。 これらのフィールドは更新が不可能であるため、Jobを更新することはできません。 そのため、`kubectl delete jobs/old --cascade=false`を使って、`old`というJobを削除し、一方で _そのPodは実行したまま_ にします。 削除する前に、どのセレクターを使っているかメモしておきます。 ``` kubectl get job old -o yaml ``` ``` kind: Job metadata: name: old ... spec: selector: matchLabels: controller-uid: a8f3d00d-c6d2-11e5-9f87-42010af00002 ... ``` 次に`new`という名前の新しいJobを作成し、同じセレクターを明示的に指定します。 既存のPodには`controller-uid=a8f3d00d-c6d2-11e5-9f87-42010af00002`というラベルが付いているので、それらも同様にJob`new`で制御されます。 システムが自動的に生成するセレクターを使用していないので、新しいJobでは`manualSelector: true`を指定する必要があります。 ``` kind: Job metadata: name: new ... spec: manualSelector: true selector: matchLabels: controller-uid: a8f3d00d-c6d2-11e5-9f87-42010af00002 ... ``` 新しいJob自体は`a8f3d00d-c6d2-11e5-9f87-42010af00002`とは異なるuidを持つでしょう。 `manualSelector: true`を設定すると、あなたが何をしているかを知っていることをシステムに伝え、この不一致を許容するようにします。 ## 代替案 ### ベアPod Podが実行されているノードが再起動したり障害が発生したりすると、Podは終了し、再起動されません。しかし、Jobは終了したPodを置き換えるために新しいPodを作成します。 このため、アプリケーションが単一のPodしか必要としない場合でも、ベアPodではなくJobを使用することをお勧めします。 ### レプリケーションコントローラー Jobは[レプリケーションコントローラー](/ja/docs/user-guide/replication-controller)を補完するものです。 レプリケーションコントローラーは終了が予想されないPod(例えばWebサーバー)を管理し、Jobは終了が予想されるPod(例えばバッチタスク)を管理します。 [Podのライフサイクル](/ja/docs/concepts/workloads/pods/pod-lifecycle/)で説明したように、`Job`は`RestartPolicy`が`OnFailure`または`Never`と等しいPodに対して*のみ*適切です。 (注意: `RestartPolicy`が設定されていない場合、デフォルト値は`Always`です。) ### 単一のJobでコントローラーPodを起動 もう一つのパターンは、単一のJobでPodを作成し、そのPodが他のPodを作成し、それらのPodに対するカスタムコントローラーのように動作するというものです。これは最も柔軟性がありますが、始めるのがやや複雑で、Kubernetesとの統合性が低いかもしれません。 このパターンの例として、Podを起動してスクリプトを実行するJobがSparkマスターコントローラー([Sparkの例](https://github.com/kubernetes/examples/tree/{{< param \"githubbranch\" >}}/staging/spark/README.md)を参照)を起動し、Sparkドライバーを実行してからクリーンアップするというものがあります。 このアプローチの利点は、全体的なプロセスがJobオブジェクトが完了する保証を得ながらも、どのようなPodが作成され、どのように作業が割り当てられるかを完全に制御できることです。 ## Cron Job {#cron-jobs} Unixのツールである`cron`と同様に、指定した日時に実行されるJobを作成するために、[`CronJob`](/ja/docs/concepts/workloads/controllers/cron-jobs/)を使用することができます。 "} {"_id":"q-en-website-5b7c15243b24fb4a3a11daf0381ae4561dc9f3aefb8246496bfcca2b3f189646","text":"![Services overview diagram for iptables proxy](/images/docs/services-iptables-overview.svg) ### Proxy-mode: ipvs[alpha] **Warning:** This is an alpha feature and not recommended for production clusters yet. In this mode, kube-proxy watches Kubernetes `services` and `endpoints`, call `netlink` interface create ipvs rules accordingly and sync ipvs rules with Kubernetes `services` and `endpoints` periodically, to make sure ipvs status is consistent with the expectation. When access the `service`, traffic will be redirect to one of the backend `pod`. Similar to iptables, Ipvs is based on netfilter hook function, but use hash table as the underlying data structure and work in the kernal state. That means ipvs redirects traffic can be much faster, and have much better performance when sync proxy rules. Furthermore, ipvs provides more options for load balancing algorithm, such as: - rr: round-robin - lc: least connection - dh: destination hashing - sh: source hashing - sed: shortest expected delay - nq: never queue **Note:** ipvs mode assumed IPVS kernel modules are installed on the node before running kube-proxy. When kube-proxy starts, if proxy mode is ipvs, kube-proxy would validate if IPVS modules are installed on the node, if it's not installed kube-proxy will fall back to iptables proxy mode. ![Services overview diagram for ipvs proxy](/images/docs/services-ipvs-overview.svg) ## Multi-Port Services Many `Services` need to expose more than one port. For this case, Kubernetes"} {"_id":"q-en-website-5ba9bf1692042e4089be6645c214ad1d32da94c0393d5508f7cd91fa07ed3157","text":"[ZooKeeper](https://zookeeper.apache.org/doc/current/) is an interesting use case for StatefulSet for two reasons. First, it demonstrates that StatefulSet can be used to run a distributed, strongly consistent storage application on Kubernetes. Second, it's a prerequisite for running workloads like [Apache Hadoop](http://hadoop.apache.org/) and [Apache Kakfa](https://kafka.apache.org/) on Kubernetes. An [in-depth tutorial](/docs/tutorials/stateful-application/zookeeper/) on deploying a ZooKeeper ensemble on Kubernetes is available in the Kubernetes documentation, and we’ll outline a few of the key features below. **Creating a ZooKeeper Ensemble** Creating an ensemble is as simple as using [kubectl create](/docs/user-guide/kubectl/kubectl_create/) to generate the objects stored in the manifest. Creating an ensemble is as simple as using [kubectl create](/docs/reference/generated/kubectl/kubectl-commands#create) to generate the objects stored in the manifest. ```"} {"_id":"q-en-website-5bc38aac7c92b9e83b8407bda7de7aa81fd630e7e0a29d2354d0334b7f01812d","text":" --- layout: blog title: \"聚焦 SIG Storage\" slug: sig-storage-spotlight date: 2022-08-22 --- **作者**:Frederico Muñoz (SAS) 自 Kubernetes 诞生之初,持久数据以及如何解决有状态应用程序的需求一直是一个重要的话题。 对无状态部署的支持是很自然的、从一开始就存在的,并引起了人们的关注,变得众所周知。 从早期开始,我们也致力于更好地支持有状态应用程序,每个版本都增加了可以在 Kubernetes 上运行的范围。 消息队列、数据库、集群文件系统:这些是具有不同存储要求的解决方案的一些示例, 如今这些解决方案越来越多地部署在 Kubernetes 中。 处理来自许多不同供应商的临时和持久存储(本地或远程、文件或块),同时考虑如何提供用户期望的所需弹性和数据一致性, 所有这些都在 SIG Storage 的整体负责范围之内。 在这次 SIG Storage 采访报道中,[Frederico Muñoz](https://twitter.com/fredericomunoz) (SAS 的云和架构负责人)与 VMware 技术负责人兼 SIG Storage 联合主席 [Xing Yang](https://twitter.com/2000xyang),讨论了 SIG 的组织方式、当前的挑战是什么以及如何进行参与和贡献。 ## 关于 SIG Storage **Frederico (FSM)**:你好,感谢你给我这个机会了解更多关于 SIG Storage 的情况。 你能否介绍一下你自己、你的角色以及你是如何参与 SIG Storage 的。 **Xing Yang (XY)**:我是 VMware 的技术主管,从事云原生存储方面的工作。我也是 SIG Storage 的联合主席。 我从 2017 年底开始参与 K8s SIG Storage,开始为 [VolumeSnapshot](https://kubernetes.io/zh-cn/docs/concepts/storage/volume-snapshots/) 项目做贡献。 那时,VolumeSnapshot 项目仍处于实验性的 pre-alpha 阶段。它需要贡献者。所以我自愿提供帮助。 然后我与其他社区成员合作,在 2018 年的 K8s 1.12 版本中将 VolumeSnapshot 带入 Alpha, 2019 年在 K8s 1.17 版本中带入 Beta,并最终在 2020 年在 1.20 版本中带入 GA。 **FSM**:仅仅阅读 [SIG Storage 章程](https://github.com/kubernetes/community/blob/master/sig-storage/charter.md) 就可以看出,SIG Storage 涵盖了很多领域,你能描述一下 SIG 的组织方式吗? **XY**:在 SIG Storage 中,有两位联合主席和两位技术主管。来自 Google 的 Saad Ali 和我是联合主席。 来自 Google 的 Michelle Au 和来自 Red Hat 的 Jan Šafránek 是技术主管。 我们每两周召开一次会议,讨论我们正在为每个特定版本开发的功能,获取状态,确保每个功能都有开发人员和审阅人员在处理它, 并提醒人们发布截止日期等。有关 SIG 的更多信息,请查阅[社区页面](https://github.com/kubernetes/community/tree/master/sig-storage)。 人们还可以将需要关注的 PR、需要讨论的设计提案和其他议题添加到会议议程文档中。 我们将在项目跟踪完成后对其进行审查。 我们还举行其他的定期会议,如 CSI 实施会议,Object Bucket API 设计会议,以及在需要时针对特定议题的一次性会议。 还有一个由 SIG Storage 和 SIG Apps 赞助的 [K8s 数据保护工作组](https://github.com/kubernetes/community/blob/master/wg-data-protection/README.md)。 SIG Storage 拥有或共同拥有数据保护工作组正在讨论的功能特性。 ## 存储和 Kubernetes **FSM**:存储是很多模块的基础组件,尤其是 Kubernetes:你认为 Kubernetes 在存储管理方面的具体挑战是什么? **XY**:在 Kubernetes 中,卷操作涉及多个组件。例如,创建一个使用 PVC 的 Pod 涉及多个组件。 有 Attach Detach Controller 和 external-attacher 负责将 PVC 连接到 Pod。 还有 Kubelet 可以将 PVC 挂载到 Pod 上。当然,CSI 驱动程序也参与其中。 在多个组件之间进行协调时,有时可能会出现竞争状况。 另一个挑战是关于核心与 [Custom Resource Definitions](https://kubernetes.io/zh-cn/docs/concepts/extend-kubernetes/api-extension/custom-resources/)(CRD), 这并不是特定于存储的。CRD 是一种扩展 Kubernetes 功能的好方法,同时又不会向 Kubernetes 核心本身添加太多代码。 然而,这也意味着运行 Kubernetes 集群时需要许多外部组件。 在 SIG Storage 方面,一个最好的例子是卷快照。卷快照 API 被定义为 CRD。 API 定义和控制器是 out-of-tree。有一个通用的快照控制器和一个快照验证 Webhook 应该部署在控制平面上,类似于 kube-controller-manager 的部署方式。 虽然 Volume Snapshot 是一个 CRD,但它是 SIG Storage 的核心特性。 建议 K8s 集群发行版部署卷快照 CRD、快照控制器和快照验证 Webhook,然而,大多数时候我们没有看到发行版部署它们。 因此,这对存储供应商来说就成了一个问题:现在部署这些非驱动程序特定的通用组件成为他们的责任。 如果客户需要使用多个存储系统,且部署多个 CSI 驱动,可能会导致冲突。 **FSM**:不仅要考虑单个存储系统的复杂性,还要考虑它们在 Kubernetes 中如何一起使用? **XY**:是的,有许多不同的存储系统可以为 Kubernetes 中的容器提供存储。它们的工作方式不同。找到适合所有人的解决方案是具有挑战性的。 **FSM**:Kubernetes 中的存储还涉及与外部解决方案的交互,可能比 Kubernetes 的其他部分更多。 这种与供应商和外部供应商的互动是否具有挑战性?它是否以任何方式随着时间而演变? **XY**:是的,这绝对是具有挑战性的。最初 Kubernetes 存储具有 in-tree 卷插件接口。 多家存储供应商实现了 in-tree 接口,并在 Kubernetes 核心代码库中拥有卷插件。这引起了很多问题。 如果卷插件中存在错误,它会影响整个 Kubernetes 代码库。所有卷插件必须与 Kubernetes 一起发布。 如果存储供应商需要修复其插件中的错误或希望与他们自己的产品版本保持一致,这是不灵活的。 **FSM**:这就是 CSI 加入的原因? **XY**:没错,接下来就是[容器存储接口](https://kubernetes-csi.github.io/docs/)(CSI)。 这是一个试图设计通用存储接口的行业标准,以便存储供应商可以编写一个插件并让它在一系列容器编排系统(CO)中工作。 现在 Kubernetes 是主要的 CO,但是在 CSI 刚开始的时候,除了 Kubernetes 之外,还有 Docker、Mesos、Cloud Foundry。 CSI 驱动程序是 out-of-tree 的,因此可以按照自己的节奏进行错误修复和发布。 与 in-tree 卷插件相比,CSI 绝对是一个很大的改进。CSI 的 Kubernetes 实现[自 1.13 版本以来](https://kubernetes.io/blog/2019/01/15/container-storage-interface-ga/)就达到 GA。 它已经发展了很长时间。SIG Storage 一直致力于将 in-tree 卷插件迁移到 out-of-tree 的 CSI 驱动,已经有几个版本了。 **FSM**:将驱动程序从 Kubernetes 主仓移到 CSI 中是一项重要的改进。 **XY**: CSI 接口是对 in-tree 卷插件接口的改进,但是仍然存在挑战。有很多存储系统。 目前在 [CSI 驱动程序文档中列出了 100 多个 CSI 驱动程序](https://kubernetes-csi.github.io/docs/drivers.html)。 这些存储系统也非常多样化。因此,很难设计一个适用于所有人的通用 API。 我们在 CSI 驱动层面引入了功能,但当同一驱动配置的卷具有不同的行为时,我们也会面临挑战。 前几天我们刚刚开会讨论每种卷 CSI 驱动程序功能。 当同一个驱动程序同时支持块卷和文件卷时,我们在区分某些 CSI 驱动程序功能时遇到了问题。 我们将召开后续会议来讨论这个问题。 ## 持续的挑战 **FSM**:具体来说,对于 [1.25 版本](https://github.com/kubernetes/sig-release/tree/master/releases/release-1.25) 们可以看到管道中有一些与存储相关的 [KEPs](https://bit.ly/k8s125-enhancements)。 你是否认为这个版本对 SIG 特别重要? **XY**:我不会说一个版本比其他版本更重要。在任何给定的版本中,我们都在做一些非常重要的事情。 **FSM**:确实如此,但你是否想指出 1.25 版本的特定特性和亮点呢? **XY**:好的。对于 1.25 版本,我想强调以下几点: * [CSI 迁移](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/625-csi-migration) 是一项持续的工作,SIG Storage 已经工作了几个版本了。目标是将 in-tree 卷插件移动到 out-of-tree 的 CSI 驱动程序,并最终删除 in-tree 卷插件。在 1.25 版本中,有 7 个 KEP 与 CSI 迁移有关。 有一个核心 KEP 用于通用的 CSI 迁移功能。它的目标是在 1.25 版本中达到 GA。 GCE PD 和 AWS EBS 的 CSI 迁移以 GA 为目标。vSphere 的 CSI 迁移的目标是在默认情况下启用特性门控, 在 1.25 版本中达到 Beta。Ceph RBD 和 PortWorx 的目标是达到 Beta,默认关闭特性门控。 Ceph FS 的目标是达到 Alpha。 * 我要强调的第二个是 [COSI,容器对象存储接口](https://github.com/kubernetes-sigs/container-object-storage-interface-spec)。 这是 SIG Storage 下的一个子项目。COSI 提出对象存储 Kubernetes API 来支持 Kubernetes 工作负载的对象存储操作的编排。 它还为对象存储提供商引入了 gRPC 接口,以编写驱动程序来配置存储桶。COSI 团队已经在这个项目上工作两年多了。 COSI 功能的目标是 1.25 版本中达到 Alpha。KEP 刚刚合入。COSI 团队正在根据更新后的 KEP 更新实现。 * 我要提到的另一个功能是 [CSI 临时卷](https://github.com/kubernetes/enhancements/issues/596)支持。 此功能允许在临时用例的 Pod 规约中直接指定 CSI 卷。它们可用于使用已安装的卷直接在 Pod 内注入任意状态, 例如配置、Secrets、身份、变量或类似信息。这最初是在 1.15 版本中作为一个 Alpha 功能引入的,现在它的目标是在 1.25 版本中达到 GA。 **FSM**:如果你必须单独列出一些内容,那么 SIG 正在研究的最紧迫的领域是什么? **XY**:CSI 迁移绝对是 SIG 投入大量精力的领域之一,并且现在已经进行了多个版本。它还涉及来自多个云提供商和存储供应商的工作。 ## 社区参与 **FSM**:Kubernetes 是一个社区驱动的项目。对任何希望参与 SIG Storage 工作的人有什么建议吗?他们应该从哪里开始? **XY**:查看 [SIG Storage 社区页面](https://github.com/kubernetes/community/tree/master/sig-storage), 它有很多关于如何开始的信息。[SIG 年度报告](https://github.com/kubernetes/community/blob/master/sig-storage/annual-report-2021.md)告诉你我们每年做了什么。 查看贡献指南。它有一些演示的链接,可以帮助你熟悉 Kubernetes 存储概念。 参加我们[在星期四举行的双周会议](https://github.com/kubernetes/community/tree/master/sig-storage#meetings)。 了解 SIG 的运作方式以及我们为每个版本所做的工作。找到你感兴趣的项目并提供贡献。 正如我之前提到的,我通过参与 Volume Snapshot 项目开始了 SIG Storage。 **FSM**:你有什么要补充的结束语吗? **XY**:SIG Storage 总是欢迎新的贡献者。 我们需要贡献者来帮助构建新功能、修复错误、进行代码审查、编写测试、监控测试网格的健康状况以及改进文档等。 **FSM**:非常感谢你抽出宝贵时间让我们深入了解 SIG Storage! No newline at end of file"} {"_id":"q-en-website-5bebe9579bf0c71c787b146ec149a32a748d4959b6fb92b7bbb7e81569449fd2","text":"默认调度器接下来将 Pod 绑定到目标主机。 如果 DaemonSet Pod 的节点亲和性配置已存在,则被替换。 DaemonSet 控制器仅在创建或修改 DaemonSet Pod 时执行这些操作, 并且不回更改 DaemonSet 的 `spec.template`。 并且不会更改 DaemonSet 的 `spec.template`。 ```yaml nodeAffinity:"} {"_id":"q-en-website-5c02ebb7dcae3f5e8ec947a53adbd9b56d22a64dc63dc9a4109724d315909e2c","text":"1. Run the following: ```sh ./etcd --listen-client-urls=http://$PRIVATE_IP:2379 --advertise-client-urls=http://$PRIVATE_IP:2379 ``` ```sh etcd --listen-client-urls=http://$PRIVATE_IP:2379 --advertise-client-urls=http://$PRIVATE_IP:2379 ``` 2. Start Kubernetes API server with the flag `--etcd-servers=$PRIVATE_IP:2379`. 2. Start the Kubernetes API server with the flag `--etcd-servers=$PRIVATE_IP:2379`. Replace `PRIVATE_IP` with your etcd client IP. Make sure `PRIVATE_IP` is set to your etcd client IP. --> ### 单节点 etcd 集群"} {"_id":"q-en-website-5c451910f8e78ac45de972273513f704966eaaeae4f20a5c656b5c2d167dd580","text":"- Keep the blog content the same. If there are changes, they should be made to the original article first, and then to the mirrored article. - The mirrored blog should have a `canonicalUrl`, that is, essentially the url of the original blog after it has been published. - [Kubernetes contributor blogs](https://kubernetes.dev/blog) have their authors mentioned in the YAML header, while the Kubernetes blog posts mention authors in the blog content itself. This should be changed when mirroring the content. - Same as [Kubernetes contributor blogs](https://kubernetes.dev/blog), Kubernetes blog posts also mention authors in the YAML header as per the new guidelines. This should be ensured. - Publication dates stay the same as the original blog. All of the other guidelines and expectations detailed above apply as well."} {"_id":"q-en-website-5eaab77a386ed8ef0153ee5c4f35ec860c87c7222decec91a86a5cfead5f4200","text":"for the upcoming **{{< skew nextMinorVersion >}}** Kubernetes release! ## Helpful Resources Refer to the [Kubernetes Release Team](https://github.com/kubernetes/sig-release/tree/master/release-team) resources for key information on roles and the release process. "} {"_id":"q-en-website-606a5b472a9f5d2c26bf1298b821b7b2fc1da4c84408dcdb622d7e5315886e97","text":" apiVersion: v1 kind: ConfigMap metadata: name: special-config namespace: default data: special.how: very --- apiVersion: v1 kind: ConfigMap metadata: name: env-config namespace: default data: log_level: INFO "} {"_id":"q-en-website-6109143fa5c6701ed8910657a7b866e5c8668e361bca1907e04b2b92a5f82357","text":" --- title: Prácticas Recomendadas de Configuración content_type: concept weight: 10 --- Este documento destaca y consolida las prácticas recomendadas de configuración que se presentan a lo largo de la guía del usuario, la documentación de Introducción y los ejemplos. Este es un documento vivo. Si se te ocurre algo que no está en esta lista pero que puede ser útil a otros, no dudes en crear un _issue_ o enviar un PR. ## Consejos Generales de Configuración - Al definir configuraciones, especifica la última versión estable de la API. - Los archivos de configuración deben almacenarse en el control de versiones antes de enviarse al clúster. Este le permite revertir rápidamente un cambio de configuración si es necesario. También ayuda a la recreación y restauración del clúster. - Escribe tus archivos de configuración usando YAML en lugar de JSON. Aunque estos formatos se pueden utilizarse indistintamente en casi todos los escenarios, YAML tiende a ser más amigable con el usuario. - Agrupa los objetos relacionados en un solo archivo siempre que tenga sentido. Un archivo suele ser más fácil de administrar que varios. Ver el archivo [guestbook-all-in-one.yaml](https://github.com/kubernetes/examples/tree/master/guestbook/all-in-one/guestbook-all-in-one.yaml) como un ejemplo de esta sintaxis. - Ten en cuenta también que se pueden llamar muchos comandos `kubectl` en un directorio. Por ejemplo, puedes llamar `kubectl apply` en un directorio de archivos de configuración. - No especifiques valores predeterminados innecesariamente: una configuración simple y mínima hará que los errores sean menos probables. - Coloca descripciones de objetos en anotaciones, para permitir una mejor introspección. ## \"Naked\" Pods vs ReplicaSets, Deployments y Jobs {#naked-pods-vs-replicasets-deployments-and-jobs} - No usar \"Naked\" Pods (es decir, Pods no vinculados a un [ReplicaSet](/docs/concepts/workloads/controllers/replicaset/) o a un [Deployment](/docs/concepts/workloads/controllers/deployment/)) si puedes evitarlo. Los Naked Pods no se reprogramará en caso de falla de un nodo. Un Deployment, que crea un ReplicaSet para garantizar que se alcance la cantidad deseada de Pods está siempre disponible y especifica una estrategia para reemplazar los Pods (como [RollingUpdate](/docs/concepts/workloads/controllers/deployment/#rolling-update-deployment)), es casi siempre preferible a crear Pods directamente, excepto por algunos explícitos [`restartPolicy: Never`](/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy) escenarios. Un [Job](/docs/concepts/workloads/controllers/job/) también puede ser apropiado. ## Servicios - Crea un [Service](/docs/concepts/services-networking/service/) antes de tus cargas de trabajo de backend correspondientes (Deployments o ReplicaSets) y antes de cualquier carga de trabajo que necesite acceder a él. Cuando Kubernetes inicia un contenedor, proporciona variables de entorno que apuntan a todos los _Services_ que se estaban ejecutando cuando se inició el contenedor. Por ejemplo, si existe un _Service_ llamado `foo`, todos los contenedores obtendrán las siguientes variables en su entorno inicial: ```shell FOO_SERVICE_HOST= FOO_SERVICE_PORT= ``` * Esto implica un requisito de ordenamiento - cualquier `Service` al que un `Pod` quiera acceder debe ser creado antes del `Pod` en sí mismo, de lo contrario, las variables de entorno no se completarán. El DNS no tiene esta restricción. - Un [cluster add-on](/docs/concepts/cluster-administration/addons/) opcional (aunque muy recomendable) es un servidor DNS. El servidor DNS observa la API de Kubernetes en busca de nuevos `Servicios` y crea un conjunto de registros DNS para cada uno. Si el DNS se ha habilitado en todo el clúster, todos los `Pods` deben ser capaces de hacer la resolución de nombres de `Services` automáticamente. - No especifiques un `hostPort` para un Pod a menos que sea absolutamente necesario. Cuando vinculas un Pod a un `hostPort`, limita la cantidad de lugares en los que se puede agendar el Pod, porque cada combinación <`hostIP`, `hostPort`, `protocol`> debe ser única. Si no especificas el `hostIP` y `protocol` explícitamente, Kubernetes usará `0.0.0.0` como el `hostIP` predeterminado y `TCP` como el `protocol` por defecto. Si solo necesitas acceder al puerto con fines de depuración, puedes utilizar el [apiserver proxy](/docs/tasks/access-application-cluster/access-cluster/#manually-constructing-apiserver-proxy-urls) o [`kubectl port-forward`](/docs/tasks/access-application-cluster/port-forward-access-application-cluster/). Si necesitas exponer explícitamente el puerto de un Pod en el nodo, considera usar un [NodePort](/docs/concepts/services-networking/service/#type-nodeport) Service antes de recurrir a `hostPort`. - Evita usar `hostNetwork`, por las mismas razones que `hostPort`. - Usa [headless Services](/docs/concepts/services-networking/service/#headless-services) (que tiene un `ClusterIP` de `None`) para el descubrimiento de servicios cuando no necesites balanceo de carga `kube-proxy`. ## Usando Labels - Define y usa [labels](/docs/concepts/overview/working-with-objects/labels/) que identifiquen __atributos semánticos__ de tu aplicación o Deployment, como `{ app.kubernetes.io/name: MyApp, tier: frontend, phase: test, deployment: v3 }`. Puedes utilizar estas labels para seleccionar los Pods apropiados para otros recursos; por ejemplo, un Service que selecciona todo los Pods `tier: frontend`, o todos los componentes `phase: test` de `app.kubernetes.io/name: MyApp`. Revisa el [libro de visitas](https://github.com/kubernetes/examples/tree/master/guestbook/) para ver ejemplos de este enfoque. Un Service puede hacer que abarque múltiples Deployments omitiendo las labels específicas de la versión de su selector. Cuando necesites actualizar un servicio en ejecución sin downtime, usa un [Deployment](/docs/concepts/workloads/controllers/deployment/). Un estado deseado de un objeto se describe mediante una implementación, y si los cambios a esa especificación son _aplicados_, el controlador de implementación cambia el estado actual al estado deseado en un ritmo controlado. - Use las [labels comunes de Kubernetes](/docs/concepts/overview/working-with-objects/common-labels/) para casos de uso común. Estas labels estandarizadas enriquecen los metadatos de una manera que permite que las herramientas, incluyendo `kubectl` y el [dashboard](/docs/tasks/access-application-cluster/web-ui-dashboard), trabajen de forma interoperable. - Puedes manipular las labels para la depuración. Debido a que los controladores de Kubernetes (como ReplicaSet) y los Services coinciden con los Pods usando labels de selector, se detendrá la eliminación de las labels relevantes de un Pod que sea considerado por un controlador o que un Service sirva tráfico. si quitas las labels de un Pod existente, su controlador creará un nuevo Pod para ocupar su lugar. Esto es un forma útil de depurar un Pod previamente \"vivo\" en un entorno de \"cuarentena\". Para eliminar interactivamente o agregar labels, usa [`kubectl label`](/docs/reference/generated/kubectl/kubectl-commands#label). ## Usando kubectl - Usa `kubectl apply -f `. Esto busca la configuración de Kubernetes en todos los `.yaml`, `.yml`, y `.json` en `` y lo pasa a `apply`. - Usa selectores de labels para las operaciones `get` y `delete` en lugar de nombres de objetos específicos. Ve las secciones en [selectores de labels](/docs/concepts/overview/working-with-objects/labels/#label-selectors) y [usar labels de forma eficaz](/docs/concepts/cluster-administration/manage-deployment/#using-labels-effectively). - Usa `kubectl create deployment` y `kubectl expose` para crear rápidamente un contenedor único Deployments y Services. Consulta [Usar un Service para Acceder a una Aplicación en un Clúster](/docs/tasks/access-application-cluster/service-access-application-cluster/) para un ejemplo. "} {"_id":"q-en-website-61bf68b1ad27556e156e715c81d81e2fdb27d023f71448ddfb4f472df1d1971f","text":"card: name: concepts weight: 10 sitemap: priority: 0.9 --- "} {"_id":"q-en-website-61e89b00d6f44d2cb0205e6a4e1aa937880bec591cd1d8b245ac5154053cf6b2","text":" --- title: 静的な処理の割り当てを使用した並列処理のためのインデックス付きJob content_type: task min-kubernetes-server-version: v1.21 weight: 30 --- {{< feature-state for_k8s_version=\"v1.21\" state=\"alpha\" >}} この例では、複数の並列ワーカープロセスを使用するKubernetesのJobを実行します。各ワーカーは、それぞれが自分のPod内で実行される異なるコンテナです。Podはコントロールプレーンが自動的に設定する*インデックス値*を持ち、この値を利用することで、各Podは処理するタスク全体のどの部分を処理するのかを特定できます。 Podのインデックスは、{{< glossary_tooltip text=\"アノテーション\" term_id=\"annotation\" >}}内の`batch.kubernetes.io/job-completion-index`を整数値の文字列表現として利用できます。コンテナ化されたタスクプロセスがこのインデックスを取得できるようにするために、このアノテーションの値は[downward API](/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#the-downward-api)の仕組みを利用することで公開できます。利便性のために、コントロールプレーンは自動的にdownward APIを設定して、`JOB_COMPLETION_INDEX`環境変数にインデックスを公開します。 以下に、この例で実行するステップの概要を示します。 1. **completionのインデックスを使用してJobのマニフェストを定義する**。downward APIはPodのインデックスのアノテーションを環境変数またはファイルとしてコンテナに渡してくれます。 2. **そのマニフェストに基づいてインデックス付き(Indexed)のJobを開始する**。 ## {{% heading \"prerequisites\" %}} あらかじめ基本的な非並列の[Job](/docs/concepts/workloads/controllers/job/)の使用に慣れている必要があります。 {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} インデックス付きJobを作成できるようにするには、[APIサーバー](/docs/reference/command-line-tools-reference/kube-apiserver/)と[コントローラーマネージャー](/docs/reference/command-line-tools-reference/kube-controller-manager/)上で`IndexedJob`[フィーチャーゲート](/ja/docs/reference/command-line-tools-reference/feature-gates/)を有効にしていることを確認してください。 ## アプローチを選択する ワーカープログラムから処理アイテムにアクセスするには、いくつかの選択肢があります。 1. `JOB_COMPLETION_INDEX`環境変数を読み込む。Job{{< glossary_tooltip text=\"コントローラー\" term_id=\"controller\" >}}は、この変数をcompletion indexを含むアノテーションに自動的にリンクします。 1. completion indexを含むファイルを読み込む。 1. プログラムを修正できない場合、プログラムをスクリプトでラップし、上のいずれかの方法でインデックスを読み取り、プログラムが入力として使用できるものに変換する。 この例では、3番目のオプションを選択肢して、[rev](https://man7.org/linux/man-pages/man1/rev.1.html)ユーティリティを実行したいと考えているとしましょう。このプログラムはファイルを引数として受け取り、内容を逆さまに表示します。 ```shell rev data.txt ``` `rev`ツールは[`busybox`](https://hub.docker.com/_/busybox)コンテナイメージから利用できます。 これは単なる例であるため、各Podはごく簡単な処理(短い文字列を逆にする)をするだけです。現実のワークロードでは、たとえば、シーンデータをもとに60秒の動画を生成するというようなタスクを記述したJobを作成するかもしれません。ビデオレンダリングJobの各処理アイテムは、ビデオクリップの特定のフレームのレンダリングを行うものになるでしょう。その場合、インデックス付きの完了が意味するのは、クリップの最初からフレームをカウントすることで、Job内の各Podがレンダリングと公開をするのがどのフレームであるかがわかるということです。 ## インデックス付きJobを定義する 以下は、completion modeとして`Indexed`を使用するJobのマニフェストの例です。 {{< codenew language=\"yaml\" file=\"application/job/indexed-job.yaml\" >}} 上記の例では、Jobコントローラーがすべてのコンテナに設定する組み込みの`JOB_COMPLETION_INDEX`環境変数を使っています。[initコンテナ](/ja/docs/concepts/workloads/pods/init-containers/)がインデックスを静的な値にマッピングし、その値をファイルに書き込み、ファイルを[emptyDir volume](/docs/concepts/storage/volumes/#emptydir)を介してワーカーを実行しているコンテナと共有します。オプションとして、インデックスとコンテナに公開するために[downward APIを使用して独自の環境変数を定義する](/ja/docs/tasks/inject-data-application/environment-variable-expose-pod-information/)こともできます。[環境変数やファイルとして設定したConfigMap](/ja/docs/tasks/configure-pod-container/configure-pod-configmap/)から値のリストを読み込むという選択肢もあります。 他には、以下の例のように、直接[downward APIを使用してアノテーションの値をボリュームファイルとして渡す](/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#store-pod-fields)こともできます。 {{< codenew language=\"yaml\" file=\"application/job/indexed-job-vol.yaml\" >}} ## Jobを実行する 次のコマンドでJobを実行します。 ```shell # このコマンドでは1番目のアプローチを使っています ($JOB_COMPLETION_INDEX に依存しています) kubectl apply -f https://kubernetes.io/examples/application/job/indexed-job.yaml ``` このJobを作成したら、コントロールプレーンは指定した各インデックスごとに一連のPodを作成します。`.spec.parallelism`の値が同時に実行できるPodの数を決定し、`.spec.completions`の値がJobが作成するPodの合計数を決定します。 `.spec.parallelism`は`.spec.completions`より小さいため、コントロールプレーンは別のPodを開始する前に最初のPodの一部が完了するまで待機します。 Jobを作成したら、少し待ってから進行状況を確認します。 ```shell kubectl describe jobs/indexed-job ``` 出力は次のようになります。 ``` Name: indexed-job Namespace: default Selector: controller-uid=bf865e04-0b67-483b-9a90-74cfc4c3e756 Labels: controller-uid=bf865e04-0b67-483b-9a90-74cfc4c3e756 job-name=indexed-job Annotations: Parallelism: 3 Completions: 5 Start Time: Thu, 11 Mar 2021 15:47:34 +0000 Pods Statuses: 2 Running / 3 Succeeded / 0 Failed Completed Indexes: 0-2 Pod Template: Labels: controller-uid=bf865e04-0b67-483b-9a90-74cfc4c3e756 job-name=indexed-job Init Containers: input: Image: docker.io/library/bash Port: Host Port: Command: bash -c items=(foo bar baz qux xyz) echo ${items[$JOB_COMPLETION_INDEX]} > /input/data.txt Environment: Mounts: /input from input (rw) Containers: worker: Image: docker.io/library/busybox Port: Host Port: Command: rev /input/data.txt Environment: Mounts: /input from input (rw) Volumes: input: Type: EmptyDir (a temporary directory that shares a pod's lifetime) Medium: SizeLimit: Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal SuccessfulCreate 4s job-controller Created pod: indexed-job-njkjj Normal SuccessfulCreate 4s job-controller Created pod: indexed-job-9kd4h Normal SuccessfulCreate 4s job-controller Created pod: indexed-job-qjwsz Normal SuccessfulCreate 1s job-controller Created pod: indexed-job-fdhq5 Normal SuccessfulCreate 1s job-controller Created pod: indexed-job-ncslj ``` この例では、各インデックスごとにカスタムの値を使用してJobを実行します。次のコマンドでPodの1つの出力を確認できます。 ```shell kubectl logs indexed-job-fdhq5 # これを対象のJobのPodの名前に一致するように変更してください。 ``` 出力は次のようになります。 ``` xuq ``` "} {"_id":"q-en-website-622d32a14188264933fa6dd26c55df36b09105259bb93f54a40bace9d002ce3b","text":"Kubernetesはオープンソースなので、オンプレミスやパブリッククラウド、それらのハイブリッドなどの利点を自由に得ることができ、簡単に移行することができます。 Kubernetesをダウンロードするには、[ダウンロード](/releases/download/)セクションを訪れてください。 {{% /blocks/feature %}} {{< /blocks/section >}}"} {"_id":"q-en-website-627dbb3cc5a720751aba3c12a10dc85d67e81be8450cc7c77cf7670ac8a6f8a0","text":"

2022年5月16日〜20日のKubeCon EUバーチャルに参加する 2023年4月18日〜21日のKubeCon + CloudNativeCon Europeに参加する



2022年10月24日-28日のKubeCon NAバーチャルに参加する 2023年11月6日〜9日のKubeCon + CloudNativeCon North Americaに参加する
"} {"_id":"q-en-website-629c0a209d788af40367c4ff06f5ddf2ca73160bcccf1a9f9607a1a1df3f33db","text":"Details of the metric data that Kubernetes components export. --- ## Metrics (v1.26) ## Metrics (auto-generated 2022 Nov 01) This page details the metrics that different Kubernetes components export. You can query the metrics endpoint for these components using an HTTP scrape, and fetch the current metrics data in Prometheus format."} {"_id":"q-en-website-63f2ac2cbfbb17de8e53a95d37c744910e6a5d7c3f0ed31fb9000ee7c3ec0644","text":"* `kubectl debug` automatically generates the name of the new Pod based on the name of the Node. * The container runs in the host IPC, Network, and PID namespaces. * The root filesystem of the Node will be mounted at `/host`. * The container runs in the host IPC, Network, and PID namespaces, although the pod isn't privileged, so reading some process information may fail, and `chroot /host` will fail. * If you need a privileged pod, create it manually. Don't forget to clean up the debugging Pod when you're finished with it:"} {"_id":"q-en-website-640b6192f9baf282b310f4bba5c22c3e488ae929d5cceed3d4ae8d296279110d","text":" apiVersion: v1 kind: ConfigMap metadata: name: special-config namespace: default data: SPECIAL_LEVEL: very SPECIAL_TYPE: charm "} {"_id":"q-en-website-6433122a14964ffe8176e58bbe84e88fcd6700b399e86cf6e14218cfda89bf28","text":"{{< note >}} 如果集群中正在运行任何 API 服务器,则不应尝试还原 etcd 的实例。相反,请按照以下步骤还原 etcd: - 停止 *所有* kube-apiserver 实例 - 停止 *所有* API 服务实例 - 在所有 etcd 实例中恢复状态 - 重启所有 kube-apiserver 实例 - 重启所有 API 服务实例 我们还建议重启所有组件(例如 kube-scheduler、kube-controller-manager、kubelet),以确保它们不会 我们还建议重启所有组件(例如 `kube-scheduler`、`kube-controller-manager`、`kubelet`),以确保它们不会 依赖一些过时的数据。请注意,实际中还原会花费一些时间。 在还原过程中,关键组件将丢失领导锁并自行重启。 {{< note >}} ## 升级和回滚 etcd 集群 从 Kubernetes v1.13.0 开始,不在支持 etcd2 作为新的或现有 Kubernetes 集群的后端。Kubernetes 支持 etcd2 和 etcd3 的时间表如下: - Kubernetes v1.0: 仅限 etcd2 - Kubernetes v1.5.1: 添加了 etcd3 支持,新的集群仍默认为 etcd2 - Kubernetes v1.6.0: 使用 `kube-up.sh` 创建的新集群默认为 etcd3,而 `kube-apiserver` 默认为 etcd3 - Kubernetes v1.9.0: 宣布弃用 etcd2 存储后端 - Kubernetes v1.13.0: 删除了 etcd2 存储后端,`kube-apiserver` 将拒绝以 `--storage-backend = etcd2` 开头,消息 `etcd2 不再是支持的存储后端` 在使用 `--storage-backend = etcd2` 升级 v1.12.x kube-apiserver 到 v1.13.x 之前,etcd v2 数据必须迁移到 v3 存储后端,并且 kube-apiserver 调用改为使用 `--storage-backend=etcd3`。 从 etcd2 迁移到 etcd3 的过程在很大程度上取决于部署和配置 etcd 集群的方式,以及如何部署和配置 Kubernetes 集群。 我们建议您查阅集群提供商的文档,以了解是否存在预定义的解决方案。 如果您的集群是通过 `kube-up.sh` 创建的并且仍然使用 etcd2 作为其存储后端,请参阅 [Kubernetes v1.12 etcd 集群升级文档](https://v1-12.docs.kubernetes.io/docs/tasks/administer-cluster/configure-upgrade-etcd/#upgrading-and-rolling-back-etcd-clusters) ## 已知问题:具有安全端点的 etcd 客户端均衡器 在 etcd v3.3.13 或更早版本的 etcd v3 客户端有一个[严重的错误](https://github.com/kubernetes/kubernetes/issues/72102),会影响 kube-apiserver 和 HA 部署。etcd 客户端平衡器故障转移不适用于安全端点。结果是,etcd 服务器可能会失败或短暂地与 kube-apiserver 断开连接。这会影响 kube-apiserver HA 的部署。 该修复程序是在 [etcd v3.4](https://github.com/etcd-io/etcd/pull/10911) 中进行的(并反向移植到 v3.3.14 或更高版本):现在,新客户端将创建自己的凭证捆绑包,以在拨号功能中正确设置授权目标。 因为此修复程序要求将 gRPC 依赖升级(到 v1.23.0 ),因此,下游 Kubernetes [未反向移植 etcd 升级](https://github.com/kubernetes/kubernetes/issues/72102#issuecomment-526645978)。这意味着只能从 Kubernetes 1.16 获得 [kube-apiserver 中的 etcd 修复](https://github.com/etcd-io/etcd/pull/10911/commits/db61ee106ca9363ba3f188ecf27d1a8843da33ab)。 要紧急修复 Kubernetes 1.15 或更早版本的此错误,请构建一个自定义的 kube-apiserver 。 您可以使用[`vendor/google.golang.org/grpc/credentials/credentials.go`](https://github.com/kubernetes/kubernetes/blob/7b85be021cd2943167cd3d6b7020f44735d9d90b/vendor/google.golang.org/grpc/credentials/credentials.go#L135) 和 [etcd@db61ee106](https://github.com/etcd-io/etcd/pull/10911/commits/db61ee106ca9363ba3f188ecf27d1a8843da33ab) 来进行本地更改。 请看 [\"kube-apiserver 1.13.x refuses to work when first etcd-server is not available\"](https://github.com/kubernetes/kubernetes/issues/72102). {{< note >}} No newline at end of file"} {"_id":"q-en-website-645f679209a33029a5335b6b0ecc25efef5316b3942ca30c21864e817fcb0849","text":"### Linux {{< note >}} Dieses Dokument zeigt Ihnen, wie Sie Minikube mit einer statischen Binärdatei unter Linux installieren. Für alternative Linux-Installationsmethoden siehe [Andere Installationsmethoden](https://github.com/kubernetes/minikube#other-ways-to-install) im offiziellen Minikube-GitHub-Repository. Dieses Dokument zeigt Ihnen, wie Sie Minikube mit einer statischen Binärdatei unter Linux installieren. Für alternative Linux-Installationsmethoden siehe [Andere Installationsmethoden](https://minikube.sigs.k8s.io/docs/start/) im offiziellen Minikube-GitHub-Repository. {{< /note >}} Sie können Minikube unter Linux installieren, indem Sie eine statische Binärdatei herunterladen:"} {"_id":"q-en-website-64c180a1484e7aa17ab53e81dad455fd63c37f6e544a224aa4dee5219b185d12","text":"쿠버네티스 DNS는 클러스터의 서비스와 DNS 파드를 관리하며, 개별 컨테이너들이 DNS 네임을 해석할 때 DNS 서비스의 IP를 사용하도록 kubelets를 구성한다. DNS 서비스의 IP를 사용하도록 kubelet을 구성한다. 클러스터 내의 모든 서비스(DNS 서버 자신도 포함하여)에는 DNS 네임이 할당된다. 기본적으로 클라이언트 파드의 DNS 검색 리스트는 파드 자체의 네임스페이스와"} {"_id":"q-en-website-6545c590c5afe2afdb48d47e2d3205b01ba32b0133adb260c6b128ef6e2ac07e","text":"body.cid-community .community-section.community-frame { width: 100vw; width: 100%; } body.cid-community .community-section.community-frame .twittercol1 {"} {"_id":"q-en-website-674b536284b729d2b4b3a5887a2ba8f2ab8f2a62f8945690fafa350a00591858","text":"--- title: コンテンツの構造化 content_type: concept weight: 40 weight: 90 --- "} {"_id":"q-en-website-6801d576b53cfd64aeb65bf8336ceb836ead2811ddb1f08601384f148b36342d","text":"## Create a CustomResourceDefinition When you create a new CustomResourceDefinition (CRD), the Kubernetes API Server creates a new RESTful resource path for each version you specify. The CRD can be either namespaced or cluster-scoped, as specified in the CRD's `scope` field. As with existing built-in objects, deleting a namespace deletes all custom objects in that namespace. CustomResourceDefinitions themselves are non-namespaced and are available to all namespaces. creates a new RESTful resource path for each version you specify. The custom resource created from a CRD object can be either namespaced or cluster-scoped, as specified in the CRD's `spec.scope` field. As with existing built-in objects, deleting a namespace deletes all custom objects in that namespace. CustomResourceDefinitions themselves are non-namespaced and are available to all namespaces. For example, if you save the following CustomResourceDefinition to `resourcedefinition.yaml`:"} {"_id":"q-en-website-683756506dbc4f2a1183375dbdd0cd062b9af05c05cf68611e861e66146e3fb2","text":" apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: access-nginx spec: podSelector: matchLabels: app: nginx ingress: - from: - podSelector: matchLabels: access: \"true\" "} {"_id":"q-en-website-68967c6187c8a036527af090dd7b9ece155e5b6e91721b729690c9e342d8bc34","text":"[thirdparty_message] other = \"\"\"Ta sekcja przekierowuje do projektów osób trzecich, które udostępniają funkcjonalność wymaganą przez Kubernetesa. Autory projektu Kubernetes nie są odpowiedzialni za te projekty. Ta strona podąża za wytycznymi CNCF dla stron internetowych aby pokazać projekty w kolejności alfabetycznej. Aby dodać projekt na tę listę przeczytaj wytyczne dla zawartości przed wysyłaniem zmian.\"\"\" [thirdparty_message_edit_disclaimer] other=\"\"\"Zastrzeżenie dotyczące zawartości zewnętrznej\"\"\" [thirdparty_message_single_item] other = \"\"\"🛇 Ta pozycja przekierowuje do projektu lub produktu osób trzecich, będących poza projektem Kubernetes. Więcej informacji\"\"\" [thirdparty_message_disclaimer] other = \"\"\"

Niektóre elementy na tej stronie odnoszą się do zewnętrznych produktów lub projektów, które dostarczają funkcjonalności wymagane przez Kubernetesa. Autorzy projektu Kubernetes nie ponoszą odpowiedzialności za te produkty oraz projekty. Zajrzyj na stronę CNCF website guidelines po więcej informacji.

Zapoznaj się także z content guide zanim zaproponujesz zmianę dodającą odnośnik do zewnętrznej strony.

\"\"\"
[ui_search_placeholder] other = \"Szukaj\""} {"_id":"q-en-website-690fb8285765ea3b031a4767f55a86bf991c0354744369b48eb7b9309cc8dc27","text":" --- title: Adding Windows worker nodes content_type: task weight: 50 --- This page explains how to add Windows worker nodes to a kubeadm cluster. ## {{% heading \"prerequisites\" %}} * A running [Windows Server 2022](https://www.microsoft.com/cloud-platform/windows-server-pricing) (or higher) instance with administrative access. * A running kubeadm cluster created by `kubeadm init` and following the steps in the document [Creating a cluster with kubeadm](/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/). ## Adding Windows worker nodes {{< note >}} To facilitate the addition of Windows worker nodes to a cluster, PowerShell scripts from the repository https://sigs.k8s.io/sig-windows-tools are used. {{< /note >}} Do the following for each machine: 1. Open a PowerShell session on the machine. 1. Make sure you are Administrator or a privileged user. Then proceed with the steps outlined below. ### Install containerd {{% thirdparty-content %}} To install containerd, first run the following command: ```PowerShell curl.exe -LO https://raw.githubusercontent.com/kubernetes-sigs/sig-windows-tools/master/hostprocess/Install-Containerd.ps1 `````` Then run the following command, but first replace `CONTAINERD_VERSION` with a recent release from the [containerd repository](https://github.com/containerd/containerd/releases). The version must not have a `v` prefix. For example, use `1.7.22` instead of `v1.7.22`: ```PowerShell .Install-Containerd.ps1 -ContainerDVersion CONTAINERD_VERSION ``` * Adjust any other parameters for `Install-Containerd.ps1` such as `netAdapterName` as you need them. * Set `skipHypervisorSupportCheck` if your machine does not support Hyper-V and cannot host Hyper-V isolated containers. * If you change the `Install-Containerd.ps1` optional parameters `CNIBinPath` and/or `CNIConfigPath` you will need to configure the installed Windows CNI plugin with matching values. ### Install kubeadm and kubelet Run the following commands to install kubeadm and the kubelet: ```PowerShell curl.exe -LO https://raw.githubusercontent.com/kubernetes-sigs/sig-windows-tools/master/hostprocess/PrepareNode.ps1 .PrepareNode.ps1 -KubernetesVersion v{{< skew currentVersion >}} ``` * Adjust the parameter `KubernetesVersion` of `PrepareNode.ps1` if needed. ### Run `kubeadm join` Run the command that was output by `kubeadm init`. For example: ```bash kubeadm join --token : --discovery-token-ca-cert-hash sha256: ``` #### Additional information about kubeadm join {{< note >}} To specify an IPv6 tuple for `:`, IPv6 address must be enclosed in square brackets, for example: `[2001:db8::101]:2073`. {{< /note >}} If you do not have the token, you can get it by running the following command on the control plane node: ```bash kubeadm token list ``` The output is similar to this: ```console TOKEN TTL EXPIRES USAGES DESCRIPTION EXTRA GROUPS 8ewj1p.9r9hcjoqgajrj4gi 23h 2018-06-12T02:51:28Z authentication, The default bootstrap system: signing token generated by bootstrappers: 'kubeadm init'. kubeadm: default-node-token ``` By default, node join tokens expire after 24 hours. If you are joining a node to the cluster after the current token has expired, you can create a new token by running the following command on the control plane node: ```bash kubeadm token create ``` The output is similar to this: ```console 5didvk.d09sbcov8ph2amjw ``` If you don't have the value of `--discovery-token-ca-cert-hash`, you can get it by running the following commands on the control plane node: ```bash sudo cat /etc/kubernetes/pki/ca.crt | openssl x509 -pubkey | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //' ``` The output is similar to: ```console 8cb2de97839780a412b93877f8507ad6c94f73add17d5d7058e91741c9d5ec78 ``` The output of the `kubeadm join` command should look something like: ``` [preflight] Running pre-flight checks ... (log output of join workflow) ... Node join complete: * Certificate signing request sent to control-plane and response received. * Kubelet informed of new secure connection details. Run 'kubectl get nodes' on control-plane to see this machine join. ``` A few seconds later, you should notice this node in the output from `kubectl get nodes`. (for example, run `kubectl` on a control plane node). ### Network configuration CNI setup on clusters mixed with Linux and Windows nodes requires more steps than just running `kubectl apply` on a manifest file. Additionally, the CNI plugin running on control plane nodes must be prepared to support the CNI plugin running on Windows worker nodes. {{% thirdparty-content %}} Only a few CNI plugins currently support Windows. Below you can find individual setup instructions for them: * [Flannel](https://sigs.k8s.io/sig-windows-tools/guides/flannel.md) * [Calico](https://docs.tigera.io/calico/latest/getting-started/kubernetes/windows-calico/) ### Install kubectl for Windows (optional) {#install-kubectl} See [Install and Set Up kubectl on Windows](/docs/tasks/tools/install-kubectl-windows/). ## {{% heading \"whatsnext\" %}} * See how to [add Linux worker nodes](/docs/tasks/administer-cluster/kubeadm/adding-linux-nodes/). "} {"_id":"q-en-website-691afa853754362b7946e497200ef0a767bea8a8a91c289bc899bdff220b4c6c","text":"body.cid-community .community-section#meetups p:last-of-type { margin-bottom: 6em; /* extra space for background */ } } @media only screen and (max-width: 767px) { body.cid-community .community-section h2:before, body.cid-community .community-section h2:after { display: none; } } No newline at end of file"} {"_id":"q-en-website-697f6241abbd570f2882b540dcfd3fd518afedaded8963254e5d73e0579f54f9","text":"$ kubectl attach -i # Attach to Running Container $ kubectl port-forward # Forward port of Pod to your local machine $ kubectl port-forward # Forward port to service $ kubectl exec -- ls / # Run command in existing pod (1 container case) $ kubectl exec -c -- ls / # Run command in existing pod (multi-container case) $ kubectl exec -- ls / # Run command in existing pod (1 container case) $ kubectl exec -c -- ls / # Run command in existing pod (multi-container case) ```"} {"_id":"q-en-website-6b95f7507ad222ed95f54470f6a423639050a72e2c91b9a7efe99f9bc678ad2c","text":"$ kubectl logs -f my-pod -c my-container # stream pod container logs (stdout, multi-container case) $ kubectl run -i --tty busybox --image=busybox -- sh # Run pod as interactive shell $ kubectl attach my-pod -i # Attach to Running Container $ kubectl port-forward my-pod 5000:6000 # Forward port 6000 of Pod to your to 5000 on your local machine $ kubectl port-forward my-pod 5000:6000 # Listen on port 5000 on the local machine and forward to port 6000 on my-pod $ kubectl exec my-pod -- ls / # Run command in existing pod (1 container case) $ kubectl exec my-pod -c my-container -- ls / # Run command in existing pod (multi-container case) $ kubectl top pod POD_NAME --containers # Show metrics for a given pod and its containers"} {"_id":"q-en-website-6c83d1423571b59e906afc2c831533ae3007034b283800f7f86511f2f1613ca4","text":"[release_date_format] other = \"2006-01-02\" # Deprecated. Planned for removal in a future release. # Use [release_full_details_initial_text] instead. [release_complete] other = \"完整的\" # Replace [release_complete] with [release_full_details_initial_text] [release_full_details_initial_text] other = \"完整的\" [release_schedule] other = \"排期表\" [release_changelog] other = \"变更记录\" [seealso_heading] other = \"另请参见\""} {"_id":"q-en-website-6ce1d29df322898632675d7e6fd7b1ea7f21c6807e3ab0ab31f33a166ac97740","text":" You can use [kubectl apply](/docs/user-guide/kubectl/kubectl_apply/) to recreate the zk StatefulSet and redeploy the ensemble. You can use [kubectl apply](/docs/reference/generated/kubectl/kubectl-commands#apply) to recreate the zk StatefulSet and redeploy the ensemble. "} {"_id":"q-en-website-6d0887bb15c93da0b025470a2b16d860a6e21ab4b785c374b38b098840179ccb","text":"Pods aren't intended to be treated as durable entities. They won't survive scheduling failures, node failures, or other evictions, such as due to lack of resources, or in the case of node maintenance. In general, users shouldn't need to create pods directly. They should almost always use controllers (e.g., [Deployments](/docs/concepts/workloads/controllers/deployment/)), even for singletons. Controllers provide self-healing with a cluster scope, as well as replication and rollout management. In general, users shouldn't need to create pods directly. They should almost always use controllers even for singletons, for example, [Deployments](/docs/concepts/workloads/controllers/deployment/)). Controllers provide self-healing with a cluster scope, as well as replication and rollout management. Controllers like [StatefulSet](/docs/concepts/workloads/controllers/statefulset.md) can also provide support to stateful pods. The use of collective APIs as the primary user-facing primitive is relatively common among cluster scheduling systems, including [Borg](https://research.google.com/pubs/pub43438.html), [Marathon](https://mesosphere.github.io/marathon/docs/rest-api.html), [Aurora](http://aurora.apache.org/documentation/latest/reference/configuration/#job-schema), and [Tupperware](http://www.slideshare.net/Docker/aravindnarayanan-facebook140613153626phpapp02-37588997)."} {"_id":"q-en-website-6d76fcb81177ebd0b4df82581b33f30bbb1996b0ceb1ea6f1fbae2a5ba51e0a0","text":"kubectl apply -f ``` {{< note >}} Only a few CNI plugins support Windows. More details and setup instructions can be found in [Adding Windows worker nodes](/docs/tasks/administer-cluster/kubeadm/adding-windows-nodes/#network-config). {{< /note >}} You can install only one Pod network per cluster. Once a Pod network has been installed, you can confirm that it is working by"} {"_id":"q-en-website-6e4d622ca28dee8dc9ad3501195eabd05cff4b78a6a30ddf84644e827745dec5","text":"convert your old configuration files to a newer version. `kubeadm config images list` and `kubeadm config images pull` can be used to list and pull the images that kubeadm requires. For more information navigate to [Using kubeadm init with a configuration file](/docs/reference/setup-tools/kubeadm/kubeadm-init/#config-file) or [Using kubeadm join with a configuration file](/docs/reference/setup-tools/kubeadm/kubeadm-join/#config-file). In Kubernetes v1.13.0 and later to list/pull kube-dns images instead of the CoreDNS image the `--config` method described [here](/docs/reference/setup-tools/kubeadm/kubeadm-init-phase/#cmd-phase-addon) has to be used."} {"_id":"q-en-website-6f391b7bb396cdf840dfd3b967600f0ac420ded4ee49af2600f309dcee94753d","text":" apiVersion: v1 kind: Pod metadata: name: dapi-test-pod spec: containers: - name: test-container image: k8s.gcr.io/busybox command: [ \"/bin/sh\",\"-c\",\"cat /etc/config/keys\" ] volumeMounts: - name: config-volume mountPath: /etc/config volumes: - name: config-volume configMap: name: special-config items: - key: SPECIAL_LEVEL path: keys restartPolicy: Never "} {"_id":"q-en-website-709126a84331b7b1ada7bfb23c1f86de6f2680c7b2e3b4d7138672c37c088640","text":"# i18n strings for the Polish site. # NOTE: Please keep the entries in alphabetical order when editing # For \"and\", see [conjunction_1] [auto_generated_edit_notice] other = \"(strona utworzona automatycznie)\" [auto_generated_pageinfo] other = \"\"\"

Ta strona została utworzona przez automat.

Jeśli chcesz zgłosić problem dotyczący tej strony, pamiętaj o zaznaczeniu, że została wygenerowana automatycznie. Może być konieczna zmiana w zupełnie innymi miejscu projektu Kubernetes.

\"\"\"
[caution] other = \"Ostrzeżenie:\""} {"_id":"q-en-website-711c204aa0020881dd750e892d69aec24704b58163296e4c491a2926d6b77105","text":"[community_youtube_name] other = \"YouTube\" # Avoid using conjunction_1. # Must match the context in layouts/shortcodes/release-data.html # Appears on https://kubernetes.io/releases/ # For example the \"and\" in \"Complete 1.25 Schedule and Changelog\" [conjunction_1] other = \"i\" [cve_id] other = \"CVE ID\" [cve_issue_url] other = \"URL do CVE w GitHubie\" [cve_json_external_url] other = \"external_url\" [cve_json_id] other = \"id\" [cve_json_summary] other = \"podsumowanie\" [cve_json_url] other = \"url\" [cve_summary] other = \"Podsumowanie problemu\" [cve_table] other = \"Oficjalna lista CVE Kubernetesa\" [cve_url] other = \"CVE URL\" [deprecation_title] other = \"Teraz oglądasz dokumentację Kubernetesa w wersji:\""} {"_id":"q-en-website-7208170c8b006d128f0e1718a38f00a80fdddce9ee1677790b6d0ba227e29efb","text":"Production likes to run cattle, so let's create some cattle pods. ```shell kubectl run cattle --image=k8s.gcr.io/serve_hostname --replicas=5 -n=production kubectl create deployment cattle --image=k8s.gcr.io/serve_hostname -n=production kubectl scale deployment cattle --replicas=5 -n=production kubectl get deployment -n=production ```"} {"_id":"q-en-website-7314f0f7cf25e9f482065fec0d491b197a61aa71b89566ab1f2247a8700503b7","text":" --- title: \"セキュリティ\" weight: 40 --- "} {"_id":"q-en-website-743daa1c787d9b9b10779d5761c3fe95cc549de717dc6271033c7fffef3f4ae7","text":" Backend Pod 1 Backend Pod 2 Backend Pod 3 Client kube-proxy apiserver ServiceIP (Virtual Server) Node (Real Server) "} {"_id":"q-en-website-74ae4b8a1eccc9b0a667d015711f435b35d38d1961c8195c024fe4222d78f838","text":" --- title: Adding Linux worker nodes content_type: task weight: 50 --- This page explains how to add Linux worker nodes to a kubeadm cluster. ## {{% heading \"prerequisites\" %}} * Each joining worker node has installed the required components from [Installing kubeadm](/docs/setup/production-environment/tools/kubeadm/install-kubeadm/), such as, kubeadm, the kubelet and a {{< glossary_tooltip term_id=\"container-runtime\" text=\"container runtime\" >}}. * A running kubeadm cluster created by `kubeadm init` and following the steps in the document [Creating a cluster with kubeadm](/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/). * You need superuser access to the node. ## Adding Linux worker nodes To add new Linux worker nodes to your cluster do the following for each machine: 1. Connect to the machine by using SSH or another method. 1. Run the command that was output by `kubeadm init`. For example: ```bash sudo kubeadm join --token : --discovery-token-ca-cert-hash sha256: ``` ### Additional information for kubeadm join {{< note >}} To specify an IPv6 tuple for `:`, IPv6 address must be enclosed in square brackets, for example: `[2001:db8::101]:2073`. {{< /note >}} If you do not have the token, you can get it by running the following command on the control plane node: ```bash sudo kubeadm token list ``` The output is similar to this: ```console TOKEN TTL EXPIRES USAGES DESCRIPTION EXTRA GROUPS 8ewj1p.9r9hcjoqgajrj4gi 23h 2018-06-12T02:51:28Z authentication, The default bootstrap system: signing token generated by bootstrappers: 'kubeadm init'. kubeadm: default-node-token ``` By default, node join tokens expire after 24 hours. If you are joining a node to the cluster after the current token has expired, you can create a new token by running the following command on the control plane node: ```bash sudo kubeadm token create ``` The output is similar to this: ```console 5didvk.d09sbcov8ph2amjw ``` If you don't have the value of `--discovery-token-ca-cert-hash`, you can get it by running the following commands on the control plane node: ```bash sudo cat /etc/kubernetes/pki/ca.crt | openssl x509 -pubkey | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //' ``` The output is similar to: ```console 8cb2de97839780a412b93877f8507ad6c94f73add17d5d7058e91741c9d5ec78 ``` The output of the `kubeadm join` command should look something like: ``` [preflight] Running pre-flight checks ... (log output of join workflow) ... Node join complete: * Certificate signing request sent to control-plane and response received. * Kubelet informed of new secure connection details. Run 'kubectl get nodes' on control-plane to see this machine join. ``` A few seconds later, you should notice this node in the output from `kubectl get nodes`. (for example, run `kubectl` on a control plane node). {{< note >}} As the cluster nodes are usually initialized sequentially, the CoreDNS Pods are likely to all run on the first control plane node. To provide higher availability, please rebalance the CoreDNS Pods with `kubectl -n kube-system rollout restart deployment coredns` after at least one new node is joined. {{< /note >}} ## {{% heading \"whatsnext\" %}} * See how to [add Windows worker nodes](/docs/tasks/administer-cluster/kubeadm/adding-windows-nodes/). "} {"_id":"q-en-website-7762aa602d18831b69e7840aa4ad485e1ec51e6a28e3671c66cbcb2663fb33f9","text":"| ---------------------------------------- | ---------- | ------- | ----------- | | `node.kubernetes.io/not-ready` | NoExecute | 1.13+ | DaemonSet pods will not be evicted when there are node problems such as a network partition. | | `node.kubernetes.io/unreachable` | NoExecute | 1.13+ | DaemonSet pods will not be evicted when there are node problems such as a network partition. | | `node.kubernetes.io/disk-pressure` | NoSchedule | 1.8+ | | | `node.kubernetes.io/memory-pressure` | NoSchedule | 1.8+ | | | `node.kubernetes.io/disk-pressure` | NoSchedule | 1.8+ | DaemonSet pods tolerate disk-pressure attributes by default scheduler. | | `node.kubernetes.io/memory-pressure` | NoSchedule | 1.8+ | DaemonSet pods tolerate memory-pressure attributes by default scheduler. | | `node.kubernetes.io/unschedulable` | NoSchedule | 1.12+ | DaemonSet pods tolerate unschedulable attributes by default scheduler. | | `node.kubernetes.io/network-unavailable` | NoSchedule | 1.12+ | DaemonSet pods, who uses host network, tolerate network-unavailable attributes by default scheduler. |"} {"_id":"q-en-website-7776aa02adce1ab674952814744f5bf1a775b9011e160f1bfd376fb8dbce2bfd","text":"
Counter Counter of OpenAPI v2 spec regeneration count broken down by causing APIService name and reason.
apiservice
reason
None
aggregator_openapi_v2_regeneration_duration ALPHA Gauge Gauge of OpenAPI v2 spec regeneration duration in seconds.
reason
None
aggregator_unavailable_apiservice ALPHA Custom Gauge of APIServices which are marked as unavailable broken down by APIService name.
name
None
aggregator_unavailable_apiservice_total ALPHA Counter Counter of APIServices which are marked as unavailable broken down by APIService name and reason.
name
reason
None
apiextensions_openapi_v2_regeneration_count ALPHA Counter Counter of OpenAPI v2 spec regeneration count broken down by causing CRD name and reason.
crd
reason
None
apiextensions_openapi_v3_regeneration_count ALPHA Counter Counter of OpenAPI v3 spec regeneration count broken down by group, version, causing CRD and reason.
crd
group
reason
version
None
apiserver_admission_step_admission_duration_seconds_summary ALPHA Summary Admission sub-step latency summary in seconds, broken out for each operation and API resource and step type (validate or admit).
operation
rejected
type
None
apiserver_admission_webhook_fail_open_count ALPHA Counter Admission webhook fail open count, identified by name and broken out for each admission type (validating or mutating).
name
type
None
apiserver_admission_webhook_rejection_count ALPHA Counter Admission webhook rejection count, identified by name and broken out for each admission type (validating or admit) and operation. Additional labels specify an error type (calling_webhook_error or apiserver_internal_error if an error occurred; no_error otherwise) and optionally a non-zero rejection code if the webhook rejects the request with an HTTP status code (honored by the apiserver when the code is greater or equal to 400). Codes greater than 600 are truncated to 600, to keep the metrics cardinality bounded.
error_type
name
operation
rejection_code
type
None
apiserver_admission_webhook_request_total ALPHA Counter Admission webhook request total, identified by name and broken out for each admission type (validating or mutating) and operation. Additional labels specify whether the request was rejected or not and an HTTP status code. Codes greater than 600 are truncated to 600, to keep the metrics cardinality bounded.
code
name
operation
rejected
type
None
apiserver_audit_error_total ALPHA Counter Counter of audit events that failed to be audited properly. Plugin identifies the plugin affected by the error.
plugin
None
apiserver_audit_event_total ALPHA Counter Counter of audit events generated and sent to the audit backend.
None None
apiserver_audit_level_total ALPHA Counter Counter of policy levels for audit events (1 per request).
level
None
apiserver_audit_requests_rejected_total ALPHA Counter Counter of apiserver requests rejected due to an error in audit logging backend.
None None
apiserver_cache_list_fetched_objects_total ALPHA Counter Number of objects read from watch cache in the course of serving a LIST request
index
resource_prefix
None
apiserver_cache_list_returned_objects_total ALPHA Counter Number of objects returned for a LIST request from watch cache
resource_prefix
None
apiserver_cache_list_total ALPHA Counter Number of LIST requests served from watch cache
index
resource_prefix
None
apiserver_cel_compilation_duration_seconds ALPHA Histogram
None None
apiserver_cel_evaluation_duration_seconds ALPHA Histogram
None None
apiserver_certificates_registry_csr_honored_duration_total ALPHA Counter Total number of issued CSRs with a requested duration that was honored, sliced by signer (only kubernetes.io signer names are specifically identified)
signerName
None
apiserver_certificates_registry_csr_requested_duration_total ALPHA Counter Total number of issued CSRs with a requested duration, sliced by signer (only kubernetes.io signer names are specifically identified)
signerName
None
apiserver_client_certificate_expiration_seconds ALPHA Histogram Distribution of the remaining lifetime on the certificate used to authenticate a request.
None None
apiserver_crd_webhook_conversion_duration_seconds ALPHA Histogram CRD webhook conversion duration in seconds
crd_name
from_version
succeeded
to_version
None
apiserver_current_inqueue_requests ALPHA Gauge Maximal number of queued requests in this apiserver per request kind in last second.
request_kind
None
apiserver_delegated_authn_request_duration_seconds ALPHA Histogram Request latency in seconds. Broken down by status code.
code
None
apiserver_delegated_authn_request_total ALPHA Counter Number of HTTP requests partitioned by status code.
code
None
apiserver_delegated_authz_request_duration_seconds ALPHA Histogram Request latency in seconds. Broken down by status code.
code
None
apiserver_delegated_authz_request_total ALPHA Counter Number of HTTP requests partitioned by status code.
code
None
apiserver_egress_dialer_dial_duration_seconds ALPHA Histogram Dial latency histogram in seconds, labeled by the protocol (http-connect or grpc), transport (tcp or uds)
protocol
transport
None
apiserver_egress_dialer_dial_failure_count ALPHA Counter Dial failure count, labeled by the protocol (http-connect or grpc), transport (tcp or uds), and stage (connect or proxy). The stage indicates at which stage the dial failed
protocol
stage
transport
apiserver_egress_dialer_dial_start_total ALPHA Counter Dial starts, labeled by the protocol (http-connect or grpc) and transport (tcp or uds).
protocol
transport
None
apiserver_envelope_encryption_dek_cache_fill_percent ALPHA Gauge Percent of the cache slots currently occupied by cached DEKs.
None None
apiserver_envelope_encryption_dek_cache_inter_arrival_time_seconds ALPHA Histogram Time (in seconds) of inter arrival of transformation requests.
transformation_type
None
apiserver_flowcontrol_current_executing_requests ALPHA Gauge Number of requests in initial (for a WATCH) or any (for a non-WATCH) execution stage in the API Priority and Fairness subsystem
flow_schema
priority_level
None
apiserver_flowcontrol_current_inqueue_requests ALPHA Gauge Number of requests currently pending in queues of the API Priority and Fairness subsystem
flow_schema
priority_level
apiserver_flowcontrol_current_limit_seats ALPHA Gauge current derived number of execution seats available to each priority level
priority_level
None
apiserver_flowcontrol_current_r ALPHA Gauge R(time of last change)
priority_level
apiserver_flowcontrol_demand_seats ALPHA TimingRatioHistogram Observations, at the end of every nanosecond, of (the number of seats each priority level could use) / (nominal number of seats for that level)
priority_level
apiserver_flowcontrol_demand_seats_average ALPHA Gauge Time-weighted average, over last adjustment period, of demand_seats
priority_level
apiserver_flowcontrol_demand_seats_high_watermark ALPHA Gauge High watermark, over last adjustment period, of demand_seats
priority_level
apiserver_flowcontrol_demand_seats_smoothed ALPHA Gauge Smoothed seat demands
priority_level
apiserver_flowcontrol_demand_seats_stdev ALPHA Gauge Time-weighted standard deviation, over last adjustment period, of demand_seats
priority_level
None
apiserver_flowcontrol_dispatch_r ALPHA Gauge R(time of last dispatch)
priority_level
None
apiserver_flowcontrol_dispatched_requests_total ALPHA Counter Number of requests executed by API Priority and Fairness subsystem
flow_schema
priority_level
None
apiserver_flowcontrol_epoch_advance_total ALPHA Counter Number of times the queueset's progress meter jumped backward
priority_level
success
None
apiserver_flowcontrol_latest_s ALPHA Gauge S(most recently dispatched request)
priority_level
apiserver_flowcontrol_lower_limit_seats ALPHA Gauge Configured lower bound on number of execution seats available to each priority level
priority_level
None
apiserver_flowcontrol_next_discounted_s_bounds ALPHA Gauge min and max, over queues, of S(oldest waiting request in queue) - estimated work in progress
bound
priority_level
None
apiserver_flowcontrol_next_s_bounds ALPHA Gauge min and max, over queues, of S(oldest waiting request in queue)
bound
priority_level
apiserver_flowcontrol_nominal_limit_seats ALPHA Gauge Nominal number of execution seats configured for each priority level
priority_level
None
apiserver_flowcontrol_priority_level_request_utilization ALPHA TimingRatioHistogram Observations, at the end of every nanosecond, of number of requests (as a fraction of the relevant limit) waiting or in any stage of execution (but only initial stage for WATCHes)
phase
priority_level
None
apiserver_flowcontrol_priority_level_seat_utilization ALPHA TimingRatioHistogram Observations, at the end of every nanosecond, of utilization of seats for any stage of execution (but only initial stage for WATCHes)
priority_level
phase:executing
map[phase:executing]
apiserver_flowcontrol_read_vs_write_current_requests ALPHA TimingRatioHistogram Observations, at the end of every nanosecond, of the number of requests (as a fraction of the relevant limit) waiting or in regular stage of execution
phase
request_kind
None
apiserver_flowcontrol_rejected_requests_total ALPHA Counter Number of requests rejected by API Priority and Fairness subsystem
flow_schema
priority_level
reason
None
apiserver_flowcontrol_request_concurrency_in_use ALPHA Gauge Concurrency (number of seats) occupied by the currently executing (initial stage for a WATCH, any stage otherwise) requests in the API Priority and Fairness subsystem
flow_schema
priority_level
None
apiserver_flowcontrol_request_concurrency_limit ALPHA Gauge Shared concurrency limit in the API Priority and Fairness subsystem
priority_level
None
apiserver_flowcontrol_request_dispatch_no_accommodation_total ALPHA Counter Number of times a dispatch attempt resulted in a non accommodation due to lack of available seats
flow_schema
priority_level
None
apiserver_flowcontrol_request_execution_seconds ALPHA Histogram Duration of initial stage (for a WATCH) or any (for a non-WATCH) stage of request execution in the API Priority and Fairness subsystem
flow_schema
priority_level
type
None
apiserver_flowcontrol_request_queue_length_after_enqueue ALPHA Histogram Length of queue in the API Priority and Fairness subsystem, as seen by each request after it is enqueued
flow_schema
priority_level
None
apiserver_flowcontrol_request_wait_duration_seconds ALPHA Histogram Length of time a request spent waiting in its queue
execute
flow_schema
priority_level
apiserver_flowcontrol_seat_fair_frac ALPHA Gauge Fair fraction of server's concurrency to allocate to each priority level that can use it
apiserver_flowcontrol_target_seats ALPHA Gauge Seat allocation targets
priority_level
apiserver_flowcontrol_upper_limit_seats ALPHA Gauge Configured upper bound on number of execution seats available to each priority level
priority_level
None
apiserver_flowcontrol_watch_count_samples ALPHA Histogram count of watchers for mutating requests in API Priority and Fairness
flow_schema
priority_level
None
apiserver_flowcontrol_work_estimated_seats ALPHA Histogram Number of estimated seats (maximum of initial and final seats) associated with requests in API Priority and Fairness
flow_schema
priority_level
None
apiserver_init_events_total ALPHA Counter Counter of init events processed in watch cache broken by resource type.
resource
None
apiserver_kube_aggregator_x509_insecure_sha1_total ALPHA Counter Counts the number of requests to servers with insecure SHA1 signatures in their serving certificate OR the number of connection failures due to the insecure SHA1 signatures (either/or, based on the runtime environment)
None None
apiserver_kube_aggregator_x509_missing_san_total ALPHA Counter Counts the number of requests to servers missing SAN extension in their serving certificate OR the number of connection failures due to the lack of x509 certificate SAN extension missing (either/or, based on the runtime environment)
None None
apiserver_request_aborts_total ALPHA Counter Number of requests which apiserver aborted possibly due to a timeout, for each group, version, verb, resource, subresource and scope
group
resource
scope
subresource
verb
version
None
apiserver_request_body_sizes ALPHA Histogram Apiserver request body sizes broken out by size.
resource
verb
None
apiserver_request_filter_duration_seconds ALPHA Histogram Request filter latency distribution in seconds, for each filter type
filter
None
apiserver_request_post_timeout_total ALPHA Counter Tracks the activity of the request handlers after the associated requests have been timed out by the apiserver
source
status
apiserver_request_sli_duration_seconds ALPHA Histogram Response latency distribution (not counting webhook duration) in seconds for each verb, group, version, resource, subresource, scope and component.
component
group
resource
scope
subresource
verb
version
None
apiserver_request_slo_duration_seconds ALPHA Histogram Response latency distribution (not counting webhook duration) in seconds for each verb, group, version, resource, subresource, scope and component.
component
group
resource
scope
subresource
verb
version
1.27.0
None
apiserver_request_terminations_total ALPHA Counter Number of requests which apiserver terminated in self-defense.
code
component
group
resource
scope
subresource
verb
version
None
apiserver_request_timestamp_comparison_time ALPHA Histogram Time taken for comparison of old vs new objects in UPDATE or PATCH requests
code_path
None
apiserver_selfrequest_total ALPHA Counter Counter of apiserver self-requests broken out for each verb, API resource and subresource.
resource
subresource
verb
None
apiserver_storage_data_key_generation_duration_seconds ALPHA Histogram Latencies in seconds of data encryption key(DEK) generation operations.
None None
apiserver_storage_data_key_generation_failures_total ALPHA Counter Total number of failed data encryption key(DEK) generation operations.
None None
apiserver_storage_db_total_size_in_bytes ALPHA Gauge Total size of the storage database file physically allocated in bytes.
endpoint
None
apiserver_storage_envelope_transformation_cache_misses_total ALPHA Counter Total number of cache misses while accessing key decryption key(KEK).
None None
apiserver_storage_list_evaluated_objects_total ALPHA Counter Number of objects tested in the course of serving a LIST request from storage
resource
None
apiserver_storage_list_fetched_objects_total ALPHA Counter Number of objects read from storage in the course of serving a LIST request
resource
None
apiserver_storage_list_returned_objects_total ALPHA Counter Number of objects returned for a LIST request from storage
resource
None
apiserver_storage_list_total ALPHA Counter Number of LIST requests served from storage
resource
None
apiserver_storage_transformation_duration_seconds ALPHA Histogram Latencies in seconds of value transformation operations.
transformation_type
None
apiserver_storage_transformation_operations_total ALPHA Counter Total number of transformations.
status
transformation_type
transformer_prefix
None
apiserver_terminated_watchers_total ALPHA Counter Counter of watchers closed due to unresponsiveness broken by resource type.
resource
None
apiserver_tls_handshake_errors_total ALPHA Counter Number of requests dropped with 'TLS handshake error from' error
None None
apiserver_validating_admission_policy_check_duration_seconds ALPHA Histogram Validation admission latency for individual validation expressions in seconds, labeled by policy and further including binding, state and enforcement action taken.
enforcement_action
policy
policy_binding
state
Validation admission latency for individual validation expressions in seconds, labeled by policy and param resource, further including binding, state and enforcement action taken.
enforcement_action
params
policy
policy_binding
state
validation_expression
None
apiserver_validating_admission_policy_check_total ALPHA Counter Validation admission policy check total, labeled by policy and further identified by binding, enforcement action taken, and state.
enforcement_action
policy
policy_binding
state
Validation admission policy check total, labeled by policy and param resource, and further identified by binding, validation expression, enforcement action taken, and state.
enforcement_action
params
policy
policy_binding
state
validation_expression
None
apiserver_validating_admission_policy_definition_total ALPHA Counter Validation admission policy count total, labeled by state and enforcement action.
enforcement_action
state
None
apiserver_watch_cache_events_dispatched_total ALPHA Counter Counter of events dispatched in watch cache broken by resource type.
resource
None
apiserver_watch_cache_initializations_total ALPHA Counter Counter of watch cache initializations broken by resource type.
resource
None
apiserver_watch_events_sizes ALPHA Histogram Watch event size distribution in bytes
group
kind
version
None
apiserver_watch_events_total ALPHA Counter Number of events sent in watch clients
group
kind
version
None
apiserver_webhooks_x509_insecure_sha1_total ALPHA Counter Counts the number of requests to servers with insecure SHA1 signatures in their serving certificate OR the number of connection failures due to the insecure SHA1 signatures (either/or, based on the runtime environment)
None None
apiserver_webhooks_x509_missing_san_total ALPHA Counter Counts the number of requests to servers missing SAN extension in their serving certificate OR the number of connection failures due to the lack of x509 certificate SAN extension missing (either/or, based on the runtime environment)
None None
attachdetach_controller_forced_detaches ALPHA Counter Number of times the A/D Controller performed a forced detach
None None
attachdetach_controller_total_volumes ALPHA Custom Number of volumes in A/D Controller
plugin_name
state
None
authenticated_user_requests ALPHA Counter Counter of authenticated requests broken out by username.
username
None
authentication_attempts ALPHA Counter Counter of authenticated attempts.
result
None
authentication_duration_seconds ALPHA Histogram Authentication duration in seconds broken out by result.
result
None
authentication_token_cache_active_fetch_count ALPHA Gauge
status
None
authentication_token_cache_fetch_total ALPHA Counter
status
None
authentication_token_cache_request_duration_seconds ALPHA Histogram
status
None
authentication_token_cache_request_total ALPHA Counter
status
None
cloudprovider_aws_api_request_duration_seconds ALPHA Histogram Latency of AWS API calls
request
None
cloudprovider_aws_api_request_errors ALPHA Counter AWS API errors
request
None
cloudprovider_aws_api_throttled_requests_total ALPHA Counter AWS API throttled requests
operation_name
None
cloudprovider_azure_api_request_duration_seconds ALPHA Histogram Latency of an Azure API call
request
resource_group
source
subscription_id
None
cloudprovider_azure_api_request_errors ALPHA Counter Number of errors for an Azure API call
request
resource_group
source
subscription_id
None
cloudprovider_azure_api_request_ratelimited_count ALPHA Counter Number of rate limited Azure API calls
request
resource_group
source
subscription_id
None
cloudprovider_azure_api_request_throttled_count ALPHA Counter Number of throttled Azure API calls
request
resource_group
source
subscription_id
None
cloudprovider_azure_op_duration_seconds ALPHA Histogram Latency of an Azure service operation
request
resource_group
source
subscription_id
None
cloudprovider_azure_op_failure_count ALPHA Counter Number of failed Azure service operations
request
resource_group
source
subscription_id
None
cloudprovider_gce_api_request_duration_seconds ALPHA Histogram Latency of a GCE API call
region
request
version
zone
None
cloudprovider_gce_api_request_errors ALPHA Counter Number of errors for an API call
region
request
version
zone
None
cloudprovider_vsphere_api_request_duration_seconds ALPHA Histogram Latency of vsphere api call
request
None
cloudprovider_vsphere_api_request_errors ALPHA Counter vsphere Api errors
request
None
cloudprovider_vsphere_operation_duration_seconds ALPHA Histogram Latency of vsphere operation call
operation
None
cloudprovider_vsphere_operation_errors ALPHA Counter vsphere operation errors
operation
None
cloudprovider_vsphere_vcenter_versions ALPHA Custom Versions for connected vSphere vCenters
hostname
version
build
None
container_cpu_usage_seconds_total ALPHA Custom Cumulative cpu time consumed by the container in core-seconds
container
pod
namespace
None
container_memory_working_set_bytes ALPHA Custom Current working set of the container in bytes
container
pod
namespace
None
container_start_time_seconds ALPHA Custom Start time of the container since unix epoch in seconds
container
pod
namespace
None
cronjob_controller_cronjob_job_creation_skew_duration_seconds ALPHA Histogram Time between when a cronjob is scheduled to be run, and when the corresponding job is created None None
csi_operations_seconds ALPHA Histogram Container Storage Interface operation duration with gRPC error code status total
driver_name
grpc_status_code
method_name
migrated
None
endpoint_slice_controller_changes ALPHA Counter Number of EndpointSlice changes
operation
None
endpoint_slice_controller_desired_endpoint_slices ALPHA Gauge Number of EndpointSlices that would exist with perfect endpoint allocation
None None
endpoint_slice_controller_endpoints_added_per_sync ALPHA Histogram Number of endpoints added on each Service sync
None None
endpoint_slice_controller_endpoints_desired ALPHA Gauge Number of endpoints desired
None None
endpoint_slice_controller_endpoints_removed_per_sync ALPHA Histogram Number of endpoints removed on each Service sync
None None
endpoint_slice_controller_endpointslices_changed_per_sync ALPHA Histogram Number of EndpointSlices changed on each Service sync
topology
None
endpoint_slice_controller_num_endpoint_slices ALPHA Gauge Number of EndpointSlices
None None
endpoint_slice_controller_syncs ALPHA Counter Number of EndpointSlice syncs
result
None
endpoint_slice_mirroring_controller_addresses_skipped_per_sync ALPHA Histogram Number of addresses skipped on each Endpoints sync due to being invalid or exceeding MaxEndpointsPerSubset
None None
endpoint_slice_mirroring_controller_changes ALPHA Counter Number of EndpointSlice changes
operation
None
endpoint_slice_mirroring_controller_desired_endpoint_slices ALPHA Gauge Number of EndpointSlices that would exist with perfect endpoint allocation
None None
endpoint_slice_mirroring_controller_endpoints_added_per_sync ALPHA Histogram Number of endpoints added on each Endpoints sync
None None
endpoint_slice_mirroring_controller_endpoints_desired ALPHA Gauge Number of endpoints desired
None None
endpoint_slice_mirroring_controller_endpoints_removed_per_sync ALPHA Histogram Number of endpoints removed on each Endpoints sync
None None
endpoint_slice_mirroring_controller_endpoints_sync_duration ALPHA Histogram Duration of syncEndpoints() in seconds
None None
endpoint_slice_mirroring_controller_endpoints_updated_per_sync ALPHA Histogram Number of endpoints updated on each Endpoints sync
None None
endpoint_slice_mirroring_controller_num_endpoint_slices ALPHA Gauge Number of EndpointSlices
None None
ephemeral_volume_controller_create_failures_total ALPHA Counter Number of PersistenVolumeClaims creation requests
None None
ephemeral_volume_controller_create_total ALPHA Counter Number of PersistenVolumeClaims creation requests
None None
etcd_bookmark_counts ALPHA Gauge Number of etcd bookmarks (progress notify events) split by kind.
resource
None
etcd_lease_object_counts ALPHA Histogram Number of objects attached to a single etcd lease.
None None
etcd_request_duration_seconds ALPHA Histogram Etcd request latency in seconds for each operation and object type.
operation
type
None
etcd_version_info ALPHA Gauge Etcd server's binary version
binary_version
None
field_validation_request_duration_seconds ALPHA Histogram Response latency distribution in seconds for each field validation value and whether field validation is enabled or not
enabled
field_validation
None
garbagecollector_controller_resources_sync_error_total ALPHA Counter Number of garbage collector resources sync errors
None None
get_token_count ALPHA Counter Counter of total Token() requests to the alternate token source
None None
get_token_fail_count ALPHA Counter Counter of failed Token() requests to the alternate token source
None None
job_controller_job_finished_total ALPHA Counter The number of finished job
completion_mode
reason
result
None
job_controller_job_pods_finished_total ALPHA Counter The number of finished Pods that are fully tracked
completion_mode
result
None
job_controller_job_sync_duration_seconds ALPHA Histogram The time it took to sync a job
action
completion_mode
result
None
job_controller_job_sync_total ALPHA Counter The number of job syncs
action
completion_mode
result
None
job_controller_pod_failures_handled_by_failure_policy_total ALPHA Counter `The number of failed Pods handled by failure policy with, \t\t\trespect to the failure policy action applied based on the matched, \t\t\trule. Possible values of the action label correspond to the, \t\t\tpossible values for the failure policy rule action, which are:, \t\t\t\"FailJob\", \"Ignore\" and \"Count\".`
action
None
job_controller_terminated_pods_tracking_finalizer_total ALPHA Counter `The number of terminated pods (phase=Failed|Succeeded), that have the finalizer batch.kubernetes.io/job-tracking, The event label can be \"add\" or \"delete\".`
event
None
kube_apiserver_clusterip_allocator_allocated_ips ALPHA Gauge Gauge measuring the number of allocated IPs for Services
cidr
None
kube_apiserver_clusterip_allocator_allocation_errors_total ALPHA Counter Number of errors trying to allocate Cluster IPs
cidr
scope
None
kube_apiserver_clusterip_allocator_allocation_total ALPHA Counter Number of Cluster IPs allocations
cidr
scope
None
kube_apiserver_clusterip_allocator_available_ips ALPHA Gauge Gauge measuring the number of available IPs for Services
cidr
None
kube_apiserver_pod_logs_pods_logs_backend_tls_failure_total ALPHA Counter Total number of requests for pods/logs that failed due to kubelet server TLS verification
None None
kube_apiserver_pod_logs_pods_logs_insecure_backend_total ALPHA Counter Total number of requests for pods/logs sliced by usage type: enforce_tls, skip_tls_allowed, skip_tls_denied
usage
None
kube_pod_resource_limit ALPHA Custom Resources limit for workloads on the cluster, broken down by pod. This shows the resource usage the scheduler and kubelet expect per pod for resources along with the unit for the resource if any.
namespace
pod
node
scheduler
priority
resource
unit
None
kube_pod_resource_request ALPHA Custom Resources requested by workloads on the cluster, broken down by pod. This shows the resource usage the scheduler and kubelet expect per pod for resources along with the unit for the resource if any.
namespace
pod
node
scheduler
priority
resource
unit
None
kubelet_certificate_manager_client_expiration_renew_errors ALPHA Counter Counter of certificate renewal errors.
None None
kubelet_certificate_manager_client_ttl_seconds ALPHA Gauge Gauge of the TTL (time-to-live) of the Kubelet's client certificate. The value is in seconds until certificate expiry (negative if already expired). If client certificate is invalid or unused, the value will be +INF.
None None
kubelet_certificate_manager_server_rotation_seconds ALPHA Histogram Histogram of the number of seconds the previous certificate lived before being rotated.
None None
kubelet_certificate_manager_server_ttl_seconds ALPHA Gauge Gauge of the shortest TTL (time-to-live) of the Kubelet's serving certificate. The value is in seconds until certificate expiry (negative if already expired). If serving certificate is invalid or unused, the value will be +INF.
None None
kubelet_cgroup_manager_duration_seconds ALPHA Histogram Duration in seconds for cgroup manager operations. Broken down by method.
operation_type
None
kubelet_container_log_filesystem_used_bytes ALPHA Custom Bytes used by the container's logs on the filesystem.
uid
namespace
pod
container
None
kubelet_containers_per_pod_count ALPHA Histogram The number of containers per pod.
None None
kubelet_cpu_manager_pinning_errors_total ALPHA Counter The number of cpu core allocations which required pinning failed.
None None
kubelet_cpu_manager_pinning_requests_total ALPHA Counter The number of cpu core allocations which required pinning.
kubelet_credential_provider_plugin_duration ALPHA Histogram Duration of execution in seconds for credential provider plugin
plugin_name
kubelet_credential_provider_plugin_errors ALPHA Counter Number of errors from credential provider plugin
plugin_name
None None
kubelet_device_plugin_alloc_duration_seconds ALPHA Histogram Duration in seconds to serve a device plugin Allocation request. Broken down by resource name.
resource_name
None
kubelet_device_plugin_registration_total ALPHA Counter Cumulative number of device plugin registrations. Broken down by resource name.
resource_name
None
kubelet_eviction_stats_age_seconds ALPHA Histogram Time between when stats are collected, and when pod is evicted based on those stats by eviction signal
eviction_signal
None
kubelet_evictions ALPHA Counter Cumulative number of pod evictions by eviction signal
eviction_signal
None
kubelet_graceful_shutdown_end_time_seconds ALPHA Gauge Last graceful shutdown start time since unix epoch in seconds
None None
kubelet_graceful_shutdown_start_time_seconds ALPHA Gauge Last graceful shutdown start time since unix epoch in seconds
None None
kubelet_http_inflight_requests ALPHA Gauge Number of the inflight http requests
long_running
method
path
server_type
None
kubelet_http_requests_duration_seconds ALPHA Histogram Duration in seconds to serve http requests
long_running
method
path
server_type
None
kubelet_http_requests_total ALPHA Counter Number of the http requests received since the server started
long_running
method
path
server_type
None
kubelet_kubelet_credential_provider_plugin_duration ALPHA Histogram Duration of execution in seconds for credential provider plugin
plugin_name
None
kubelet_kubelet_credential_provider_plugin_errors ALPHA Counter Number of errors from credential provider plugin
plugin_name
None
kubelet_lifecycle_handler_http_fallbacks_total ALPHA Counter The number of times lifecycle handlers successfully fell back to http from https.
None None
kubelet_managed_ephemeral_containers ALPHA Gauge Current number of ephemeral containers in pods managed by this kubelet. Ephemeral containers will be ignored if disabled by the EphemeralContainers feature gate, and this number will be 0.
None None
kubelet_node_name ALPHA Gauge The node's name. The count is always 1.
node
None
kubelet_pleg_discard_events ALPHA Counter The number of discard events in PLEG.
None None
kubelet_pleg_last_seen_seconds ALPHA Gauge Timestamp in seconds when PLEG was last seen active.
None None
kubelet_pleg_relist_duration_seconds ALPHA Histogram Duration in seconds for relisting pods in PLEG.
None None
kubelet_pleg_relist_interval_seconds ALPHA Histogram Interval in seconds between relisting in PLEG.
None None
kubelet_pod_resources_endpoint_errors_get_allocatable ALPHA Counter Number of requests to the PodResource GetAllocatableResources endpoint which returned error. Broken down by server api version.
server_api_version
None
kubelet_pod_resources_endpoint_errors_list ALPHA Counter Number of requests to the PodResource List endpoint which returned error. Broken down by server api version.
server_api_version
None
kubelet_pod_resources_endpoint_requests_get_allocatable ALPHA Counter Number of requests to the PodResource GetAllocatableResources endpoint. Broken down by server api version.
server_api_version
None
kubelet_pod_resources_endpoint_requests_list ALPHA Counter Number of requests to the PodResource List endpoint. Broken down by server api version.
server_api_version
None
kubelet_pod_resources_endpoint_requests_total ALPHA Counter Cumulative number of requests to the PodResource endpoint. Broken down by server api version.
server_api_version
None
kubelet_pod_start_duration_seconds ALPHA Histogram Duration in seconds from kubelet seeing a pod for the first time to the pod starting to run
kubelet_pod_start_sli_duration_seconds ALPHA Histogram Duration in seconds to start a pod, excluding time to pull images and run init containers, measured from pod creation timestamp to when all its containers are reported as started and observed via watch
None None
kubelet_pod_status_sync_duration_seconds ALPHA Histogram Duration in seconds to sync a pod status update. Measures time from detection of a change to pod status until the API is successfully updated for that pod, even if multiple intevening changes to pod status occur.
None None
kubelet_pod_worker_duration_seconds ALPHA Histogram Duration in seconds to sync a single pod. Broken down by operation type: create, update, or sync
operation_type
None
kubelet_pod_worker_start_duration_seconds ALPHA Histogram Duration in seconds from kubelet seeing a pod to starting a worker.
None None
kubelet_preemptions ALPHA Counter Cumulative number of pod preemptions by preemption resource
preemption_signal
None
kubelet_run_podsandbox_duration_seconds ALPHA Histogram Duration in seconds of the run_podsandbox operations. Broken down by RuntimeClass.Handler.
runtime_handler
None
kubelet_run_podsandbox_errors_total ALPHA Counter Cumulative number of the run_podsandbox operation errors by RuntimeClass.Handler.
runtime_handler
None
kubelet_running_containers ALPHA Gauge Number of containers currently running
container_state
None
kubelet_running_pods ALPHA Gauge Number of pods that have a running pod sandbox
None None
kubelet_runtime_operations_duration_seconds ALPHA Histogram Duration in seconds of runtime operations. Broken down by operation type.
operation_type
None
kubelet_runtime_operations_errors_total ALPHA Counter Cumulative number of runtime operation errors by operation type.
operation_type
None
kubelet_runtime_operations_total ALPHA Counter Cumulative number of runtime operations by operation type.
operation_type
None
kubelet_server_expiration_renew_errors ALPHA Counter Counter of certificate renewal errors.
None None
kubelet_started_containers_errors_total ALPHA Counter Cumulative number of errors when starting containers
code
container_type
None
kubelet_started_containers_total ALPHA Counter Cumulative number of containers started
container_type
None
kubelet_started_host_process_containers_errors_total ALPHA Counter Cumulative number of errors when starting hostprocess containers. This metric will only be collected on Windows and requires WindowsHostProcessContainers feature gate to be enabled.
code
container_type
None
kubelet_started_host_process_containers_total ALPHA Counter Cumulative number of hostprocess containers started. This metric will only be collected on Windows and requires WindowsHostProcessContainers feature gate to be enabled.
container_type
None
kubelet_started_pods_errors_total ALPHA Counter Cumulative number of errors when starting pods
None None
kubelet_started_pods_total ALPHA Counter Cumulative number of pods started
None None
kubelet_volume_metric_collection_duration_seconds ALPHA Histogram Duration in seconds to calculate volume stats
metric_source
None
kubelet_volume_stats_available_bytes ALPHA Custom Number of available bytes in the volume
namespace
persistentvolumeclaim
None
kubelet_volume_stats_capacity_bytes ALPHA Custom Capacity in bytes of the volume
namespace
persistentvolumeclaim
None
kubelet_volume_stats_health_status_abnormal ALPHA Custom Abnormal volume health status. The count is either 1 or 0. 1 indicates the volume is unhealthy, 0 indicates volume is healthy
namespace
persistentvolumeclaim
None
kubelet_volume_stats_inodes ALPHA Custom Maximum number of inodes in the volume
namespace
persistentvolumeclaim
None
kubelet_volume_stats_inodes_free ALPHA Custom Number of free inodes in the volume
namespace
persistentvolumeclaim
None
kubelet_volume_stats_inodes_used ALPHA Custom Number of used inodes in the volume
namespace
persistentvolumeclaim
None
kubelet_volume_stats_used_bytes ALPHA Custom Number of used bytes in the volume
namespace
persistentvolumeclaim
None
kubeproxy_network_programming_duration_seconds ALPHA Histogram In Cluster Network Programming Latency in seconds
None None
kubeproxy_sync_proxy_rules_duration_seconds ALPHA Histogram SyncProxyRules latency in seconds
None None
kubeproxy_sync_proxy_rules_endpoint_changes_pending ALPHA Gauge Pending proxy rules Endpoint changes
None None
kubeproxy_sync_proxy_rules_endpoint_changes_total ALPHA Counter Cumulative proxy rules Endpoint changes
kubeproxy_sync_proxy_rules_iptables_partial_restore_failures_total ALPHA Counter Cumulative proxy iptables partial restore failures
None None
kubeproxy_sync_proxy_rules_iptables_restore_failures_total ALPHA Counter Cumulative proxy iptables restore failures
None None
kubeproxy_sync_proxy_rules_iptables_total ALPHA Gauge Number of proxy iptables rules programmed
table
None
kubeproxy_sync_proxy_rules_last_queued_timestamp_seconds ALPHA Gauge The last time a sync of proxy rules was queued
None None
kubeproxy_sync_proxy_rules_last_timestamp_seconds ALPHA Gauge The last time proxy rules were successfully synced
None None
kubeproxy_sync_proxy_rules_no_local_endpoints_total ALPHA Gauge Number of services with a Local traffic policy and no endpoints
traffic_policy
None
kubeproxy_sync_proxy_rules_service_changes_pending ALPHA Gauge Pending proxy rules Service changes
None None
kubeproxy_sync_proxy_rules_service_changes_total ALPHA Counter Cumulative proxy rules Service changes
None None
kubernetes_build_info ALPHA Gauge A metric with a constant '1' value labeled by major, minor, git version, git commit, git tree state, build date, Go version, and compiler from which Kubernetes was built, and platform on which it is running.
build_date
compiler
git_commit
git_tree_state
git_version
go_version
major
minor
platform
None
kubernetes_feature_enabled ALPHA Gauge This metric records the data about the stage and enablement of a k8s feature.
name
stage
None
kubernetes_healthcheck ALPHA Gauge This metric records the result of a single healthcheck.
name
type
None
kubernetes_healthchecks_total ALPHA Counter This metric records the results of all healthcheck.
name
status
type
None
leader_election_master_status ALPHA Gauge Gauge of if the reporting system is master of the relevant lease, 0 indicates backup, 1 indicates master. 'name' is the string used to identify the lease. Please make sure to group by name.
name
None
node_authorizer_graph_actions_duration_seconds ALPHA Histogram Histogram of duration of graph actions in node authorizer.
operation
None
node_collector_evictions_number ALPHA Counter Number of Node evictions that happened since current instance of NodeController started, This metric is replaced by node_collector_evictions_total.
zone
1.24.0
None
node_collector_unhealthy_nodes_in_zone ALPHA Gauge Gauge measuring number of not Ready Nodes per zones.
zone
None
node_collector_zone_health ALPHA Gauge Gauge measuring percentage of healthy nodes per zone.
zone
None
node_collector_zone_size ALPHA Gauge Gauge measuring number of registered Nodes per zones.
zone
None
node_cpu_usage_seconds_total ALPHA Custom Cumulative cpu time consumed by the node in core-seconds
None None
node_ipam_controller_cidrset_allocation_tries_per_request ALPHA Histogram Number of endpoints added on each Service sync
clusterCIDR
None
node_ipam_controller_cidrset_cidrs_allocations_total ALPHA Counter Counter measuring total number of CIDR allocations.
clusterCIDR
None
node_ipam_controller_cidrset_cidrs_releases_total ALPHA Counter Counter measuring total number of CIDR releases.
clusterCIDR
None
node_ipam_controller_cidrset_usage_cidrs ALPHA Gauge Gauge measuring percentage of allocated CIDRs.
clusterCIDR
None
node_ipam_controller_multicidrset_allocation_tries_per_request ALPHA Histogram Histogram measuring CIDR allocation tries per request.
clusterCIDR
None
node_ipam_controller_multicidrset_cidrs_allocations_total ALPHA Counter Counter measuring total number of CIDR allocations.
clusterCIDR
None
node_ipam_controller_multicidrset_cidrs_releases_total ALPHA Counter Counter measuring total number of CIDR releases.
clusterCIDR
None
node_ipam_controller_multicidrset_usage_cidrs ALPHA Gauge Gauge measuring percentage of allocated CIDRs.
clusterCIDR
None
node_memory_working_set_bytes ALPHA Custom Current working set of the node in bytes
None None
number_of_l4_ilbs ALPHA Gauge Number of L4 ILBs
feature
None
plugin_manager_total_plugins ALPHA Custom Number of plugins in Plugin Manager
socket_path
state
None
pod_cpu_usage_seconds_total ALPHA Custom Cumulative cpu time consumed by the pod in core-seconds
pod
namespace
pod_gc_collector_force_delete_pod_errors_total ALPHA Counter Number of errors encountered when forcefully deleting the pods since the Pod GC Controller started.
pod_gc_collector_force_delete_pods_total ALPHA Counter Number of pods that are being forcefully deleted since the Pod GC Controller started.
None
pod_memory_working_set_bytes ALPHA Custom Current working set of the pod in bytes
pod
namespace
None
pod_security_errors_total ALPHA Counter Number of errors preventing normal evaluation. Non-fatal errors may result in the latest restricted profile being used for evaluation.
fatal
request_operation
resource
subresource
None
pod_security_evaluations_total ALPHA Counter Number of policy evaluations that occurred, not counting ignored or exempt requests.
decision
mode
policy_level
policy_version
request_operation
resource
subresource
None
pod_security_exemptions_total ALPHA Counter Number of exempt requests, not counting ignored or out of scope requests.
request_operation
resource
subresource
None
prober_probe_duration_seconds ALPHA Histogram Duration in seconds for a probe response.
container
namespace
pod
probe_type
None
prober_probe_total ALPHA Counter Cumulative number of a liveness, readiness or startup probe for a container by result.
container
namespace
pod
pod_uid
probe_type
result
None
pv_collector_bound_pv_count ALPHA Custom Gauge measuring number of persistent volume currently bound
storage_class
None
pv_collector_bound_pvc_count ALPHA Custom Gauge measuring number of persistent volume claim currently bound
namespace
None
pv_collector_total_pv_count ALPHA Custom Gauge measuring total number of persistent volumes
plugin_name
volume_mode
None
pv_collector_unbound_pv_count ALPHA Custom Gauge measuring number of persistent volume currently unbound
storage_class
None
pv_collector_unbound_pvc_count ALPHA Custom Gauge measuring number of persistent volume claim currently unbound
namespace
None
replicaset_controller_sorting_deletion_age_ratio ALPHA Histogram The ratio of chosen deleted pod's ages to the current youngest pod's age (at the time). Should be <2.The intent of this metric is to measure the rough efficacy of the LogarithmicScaleDown feature gate's effect onthe sorting (and deletion) of pods when a replicaset scales down. This only considers Ready pods when calculating and reporting.
None None
rest_client_exec_plugin_call_total ALPHA Counter Number of calls to an exec plugin, partitioned by the type of event encountered (no_error, plugin_execution_error, plugin_not_found_error, client_internal_error) and an optional exit code. The exit code will be set to 0 if and only if the plugin call was successful.
call_status
code
None
rest_client_exec_plugin_certificate_rotation_age ALPHA Histogram Histogram of the number of seconds the last auth exec plugin client certificate lived before being rotated. If auth exec plugin client certificates are unused, histogram will contain no data.
None None
rest_client_exec_plugin_ttl_seconds ALPHA Gauge Gauge of the shortest TTL (time-to-live) of the client certificate(s) managed by the auth exec plugin. The value is in seconds until certificate expiry (negative if already expired). If auth exec plugins are unused or manage no TLS certificates, the value will be +INF.
None None
rest_client_rate_limiter_duration_seconds ALPHA Histogram Client side rate limiter latency in seconds. Broken down by verb, and host.
host
verb
None
rest_client_request_duration_seconds ALPHA Histogram Request latency in seconds. Broken down by verb, and host.
host
verb
None
rest_client_request_size_bytes ALPHA Histogram Request size in bytes. Broken down by verb and host.
host
verb
None
rest_client_requests_total ALPHA Counter Number of HTTP requests, partitioned by status code, method, and host.
code
host
method
None
rest_client_response_size_bytes ALPHA Histogram Response size in bytes. Broken down by verb and host.
host
verb
None
retroactive_storageclass_errors_total ALPHA Counter Total number of failed retroactive StorageClass assignments to persistent volume claim
None None
retroactive_storageclass_total ALPHA Counter Total number of retroactive StorageClass assignments to persistent volume claim
None None
root_ca_cert_publisher_sync_duration_seconds ALPHA Histogram Number of namespace syncs happened in root ca cert publisher.
code
None
root_ca_cert_publisher_sync_total ALPHA Counter Number of namespace syncs happened in root ca cert publisher.
code
None
running_managed_controllers ALPHA Gauge Indicates where instances of a controller are currently running
manager
name
None
scheduler_e2e_scheduling_duration_seconds ALPHA Histogram E2e scheduling latency in seconds (scheduling algorithm + binding). This metric is replaced by scheduling_attempt_duration_seconds.
profile
result
1.23.0
None
scheduler_goroutines ALPHA Gauge Number of running goroutines split by the work they do such as binding.
operation
None
scheduler_permit_wait_duration_seconds ALPHA Histogram Duration of waiting on permit.
result
None
scheduler_plugin_execution_duration_seconds ALPHA Histogram Duration for running a plugin at a specific extension point.
extension_point
plugin
status
None
scheduler_scheduler_cache_size ALPHA Gauge Number of nodes, pods, and assumed (bound) pods in the scheduler cache.
type
None
scheduler_scheduler_goroutines ALPHA Gauge Number of running goroutines split by the work they do such as binding. This metric is replaced by the \"goroutines\" metric.
work
1.26.0
None
scheduler_scheduling_algorithm_duration_seconds ALPHA Histogram Scheduling algorithm latency in seconds
None None
scheduler_unschedulable_pods ALPHA Gauge The number of unschedulable pods broken down by plugin name. A pod will increment the gauge for all plugins that caused it to not schedule and so this metric have meaning only when broken down by plugin.
plugin
profile
None
scheduler_volume_binder_cache_requests_total ALPHA Counter Total number for request volume binding cache
operation
None
scheduler_volume_scheduling_stage_error_total ALPHA Counter Volume scheduling stage error count
operation
None
scrape_error ALPHA Custom 1 if there was an error while getting container metrics, 0 otherwise
None None
service_controller_nodesync_latency_seconds ALPHA Histogram A metric measuring the latency for nodesync which updates loadbalancer hosts on cluster node updates.
None None
service_controller_update_loadbalancer_host_latency_seconds ALPHA Histogram A metric measuring the latency for updating each load balancer hosts.
None None
serviceaccount_legacy_tokens_total ALPHA Counter Cumulative legacy service account tokens used
None None
serviceaccount_stale_tokens_total ALPHA Counter Cumulative stale projected service account tokens used
None None
serviceaccount_valid_tokens_total ALPHA Counter Cumulative valid projected service account tokens used
None None
storage_count_attachable_volumes_in_use ALPHA Custom Measure number of volumes in use
node
volume_plugin
None
storage_operation_duration_seconds ALPHA Histogram Storage operation duration
migrated
operation_name
status
volume_plugin
None
ttl_after_finished_controller_job_deletion_duration_seconds ALPHA Histogram The time it took to delete the job since it became eligible for deletion
None None
volume_manager_selinux_container_errors_total ALPHA Gauge Number of errors when kubelet cannot compute SELinux context for a container. Kubelet can't start such a Pod then and it will retry, therefore value of this metric may not represent the actual nr. of containers.
None None
volume_manager_selinux_container_warnings_total ALPHA Gauge Number of errors when kubelet cannot compute SELinux context for a container that are ignored. They will become real errors when SELinuxMountReadWriteOncePod feature is expanded to all volume access modes.
None None
volume_manager_selinux_pod_context_mismatch_errors_total ALPHA Gauge Number of errors when a Pod defines different SELinux contexts for its containers that use the same volume. Kubelet can't start such a Pod then and it will retry, therefore value of this metric may not represent the actual nr. of Pods.
None None
volume_manager_selinux_pod_context_mismatch_warnings_total ALPHA Gauge Number of errors when a Pod defines different SELinux contexts for its containers that use the same volume. They are not errors yet, but they will become real errors when SELinuxMountReadWriteOncePod feature is expanded to all volume access modes.
None None
volume_manager_selinux_volume_context_mismatch_errors_total ALPHA Gauge Number of errors when a Pod uses a volume that is already mounted with a different SELinux context than the Pod needs. Kubelet can't start such a Pod then and it will retry, therefore value of this metric may not represent the actual nr. of Pods.
None None
volume_manager_selinux_volume_context_mismatch_warnings_total ALPHA Gauge Number of errors when a Pod uses a volume that is already mounted with a different SELinux context than the Pod needs. They are not errors yet, but they will become real errors when SELinuxMountReadWriteOncePod feature is expanded to all volume access modes.
None None
volume_manager_selinux_volumes_admitted_total ALPHA Gauge Number of volumes whose SELinux context was fine and will be mounted with mount -o context option.
None None
volume_manager_total_volumes ALPHA Custom Number of volumes in Volume Manager
plugin_name
state
None
volume_operation_total_errors ALPHA Counter Total volume operation errors
operation_name
plugin_name
None
volume_operation_total_seconds ALPHA Histogram Storage operation end to end duration in seconds
operation_name
plugin_name
None
watch_cache_capacity ALPHA Gauge Total capacity of watch cache broken by resource type.
resource
None
watch_cache_capacity_decrease_total ALPHA Counter Total number of watch cache capacity decrease events broken by resource type.
resource
None
watch_cache_capacity_increase_total ALPHA Counter Total number of watch cache capacity increase events broken by resource type.
resource
None
workqueue_adds_total ALPHA Counter Total number of adds handled by workqueue
name
None
workqueue_depth ALPHA Gauge Current depth of workqueue
name
None
workqueue_longest_running_processor_seconds ALPHA Gauge How many seconds has the longest running processor for workqueue been running.
name
None
workqueue_queue_duration_seconds ALPHA Histogram How long in seconds an item stays in workqueue before being requested.
name
None
workqueue_retries_total ALPHA Counter Total number of retries handled by workqueue
name
None
workqueue_unfinished_work_seconds ALPHA Gauge How many seconds of work has done that is in progress and hasn't been observed by work_duration. Large values indicate stuck threads. One can deduce the number of stuck threads by observing the rate at which this increases.
name
None
workqueue_work_duration_seconds ALPHA Histogram How long in seconds processing an item from workqueue takes.
name
None
"} {"_id":"q-en-website-784bfd91d8ac67fb178c3743dd87e50939613a1058af3508d92035c56ca78464","text":"## Usando Labels - Defina e use [labels](/docs/concepts/overview/working-with-objects/labels/) que identifiquem _atributos semânticos_ da sua aplicação ou Deployment, como `{ app: myapp, tier: frontend, phase: test, deployment: v3 }`. Você pode usar essas labels para selecionar os Pods apropriados para outros recursos; por exemplo, um Service que seleciona todos os Pods `tier: frontend`, ou todos os componentes de `app: myapp`. Veja o app [guestbook](https://github.com/kubernetes/examples/tree/{{< param \"githubbranch\" >}}/guestbook/) para exemplos dessa abordagem. os componentes de `app: myapp`. Veja o app [guestbook](https://github.com/kubernetes/examples/tree/master/guestbook/) para exemplos dessa abordagem. Um Service pode ser feito para abranger vários Deployments, omitindo labels específicas de lançamento de seu seletor. Quando você precisar atualizar um serviço em execução sem _downtime_, use um [Deployment](/docs/concepts/workloads/controllers/deployment/)."} {"_id":"q-en-website-7aca413077477b8207ca74c2960454fffab26952f6a26723c87c46c597120cf8","text":"{{< note >}} If the `SizeMemoryBackedVolumes` [feature gate](/docs/reference/command-line-tools-reference/feature-gates/) is enabled, you can specify a size for memory backed volumes. If no size is specified, memory backed volumes are sized to 50% of the memory on a Linux host. backed volumes are sized to node allocatable memory. {{< /note>}} #### emptyDir configuration example"} {"_id":"q-en-website-7c3c0ba32b68d799375a6d33a236054dea55c2195d6e74a97812948d56a3a0fa","text":"node-3 Ready v1.19.6 containerd://1.4.1 ``` コンテナランタイムについては、[コンテナランタイム](/docs/setup/production-environment/container-runtimes/)のページで詳細を確認することができます。 コンテナランタイムについては、[コンテナランタイム](/ja/docs/setup/production-environment/container-runtimes/)のページで詳細を確認することができます。 "} {"_id":"q-en-website-7d9750cde1c6aa58ebb1f1d1dc9baf5c577de8048e11a78e863104969b4823b1","text":"# Last commit for the localized file LASTCOMMIT=`git log -n 1 --pretty=format:%h -- $LOCALIZED` git diff $LASTCOMMIT...HEAD $EN_VERSION git diff --exit-code $LASTCOMMIT...HEAD $EN_VERSION if [ \"$?\" -eq 0 ]; then echo \"$LOCALIZED is still in sync\""} {"_id":"q-en-website-7e25cc607d6793b8e9565cee23bc27ddd68faa5a9333e7016c946d2fec11ff57","text":"## {{% heading \"whatsnext\" %}} - [Secretのコンセプト](/ja/docs/concepts/configuration/secret/)を読む - [設定ファイルを使用してSecretを管理する](/docs/tasks/configmap-secret/managing-secret-using-config-file/)方法を知る - [設定ファイルを使用してSecretを管理する](/ja/docs/tasks/configmap-secret/managing-secret-using-config-file/)方法を知る - [kustomizeを使用してSecretを管理する](/docs/tasks/configmap-secret/managing-secret-using-kustomize/)方法を知る"} {"_id":"q-en-website-7ebaa22d4e0b3d5d6ca3a56bb131d033e261af3ee3890d1a1b909c9979f4ff72","text":"app: hello tier: backend track: stable replicas: 7 replicas: 3 template: metadata: labels:"} {"_id":"q-en-website-800936b2178429f7784ba75331daba339bd2a82020ec9f4153670ffad8a7c721","text":" --- approvers: - bprashanth - enisoc - erictune - foxish - janetkuo - kow3ns - smarterclayton title: Upgrade from PetSets to StatefulSets --- {% capture overview %} This page shows how to upgrade from PetSets (Kubernetes version 1.3 or 1.4) to *StatefulSets* (Kubernetes version 1.5 or later). {% endcapture %} {% capture prerequisites %} * If you don't have PetSets in your current cluster, or you don't plan to upgrade your master to Kubernetes 1.5 or later, you can skip this task. {% endcapture %} {% capture steps %} ## Differences between alpha PetSets and beta StatefulSets PetSet was introduced as an alpha resource in Kubernetes release 1.3, and was renamed to StatefulSet as a beta resource in 1.5. Here are some notable changes: * **StatefulSet is the new PetSet**: PetSet is no longer available in Kubernetes release 1.5 or later. It becomes beta StatefulSet. To understand why the name was changed, see this [discussion thread](https://github.com/kubernetes/kubernetes/issues/27430). * **StatefulSet guards against split brain**: StatefulSets guarantee at most one Pod for a given ordinal index can be running anywhere in a cluster, to guard against split brain scenarios with distributed applications. *TODO: Link to doc about fencing.* * **Flipped debug annotation behavior**: The default value of the debug annotation (`pod.alpha.kubernetes.io/initialized`) is `true` in 1.5 through 1.7. The annotation is completely ignored in 1.8 and above, which always behave as if it were `true`. The absence of this annotation will pause PetSet operations, but will NOT pause StatefulSet operations. In most cases, you no longer need this annotation in your StatefulSet manifests. ## Upgrading from PetSets to StatefulSets Note that these steps need to be done in the specified order. You **should NOT upgrade your Kubernetes master, nodes, or `kubectl` to Kubernetes version 1.5 or later**, until told to do so. ### Find all PetSets and their manifests First, find all existing PetSets in your cluster: ```shell kubectl get petsets --all-namespaces ``` If you don't find any existing PetSets, you can safely upgrade your cluster to Kubernetes version 1.5 or later. If you find existing PetSets and you have all their manifests at hand, you can continue to the next step to prepare StatefulSet manifests. Otherwise, you need to save their manifests so that you can recreate them as StatefulSets later. Here's an example command for you to save all existing PetSets as one file. ```shell # Save all existing PetSets in all namespaces into a single file. Only needed when you don't have their manifests at hand. kubectl get petsets --all-namespaces -o yaml > all-petsets.yaml ``` ### Prepare StatefulSet manifests Now, for every PetSet manifest you have, prepare a corresponding StatefulSet manifest: 1. Change `apiVersion` from `apps/v1alpha1` to `apps/v1beta1`. 2. Change `kind` from `PetSet` to `StatefulSet`. 3. If you have the debug hook annotation `pod.alpha.kubernetes.io/initialized` set to `true`, you can remove it because it's redundant. If you don't have this annotation or have it set to `false`, be aware that StatefulSet operations might resume after the upgrade. If you are upgrading to 1.6 or 1.7, you can set the annotation explicitly to `false` to maintain the paused behavior. If you are upgrading to 1.8 or above, there's no longer any debug annotation to pause StatefulSets. It's recommended that you keep both PetSet manifests and StatefulSet manifests, so that you can safely roll back and recreate your PetSets, if you decide not to upgrade your cluster. ### Delete all PetSets without cascading If you find existing PetSets in your cluster in the previous step, you need to delete all PetSets *without cascading*. You can do this from `kubectl` with `--cascade=false`. Note that if the flag isn't set, **cascading deletion will be performed by default**, and all Pods managed by your PetSets will be gone. Delete those PetSets by specifying file names. This only works when the files contain only PetSets, but not other resources such as Services: ```shell # Delete all existing PetSets without cascading # Note that should only contain PetSets that you want to delete, but not any other resources kubectl delete -f --cascade=false ``` Alternatively, delete them by specifying resource names: ```shell # Alternatively, delete them by name and namespace without cascading kubectl delete petsets -n= --cascade=false ``` Make sure you've deleted all PetSets in the system: ```shell # Get all PetSets again to make sure you deleted them all # This should return nothing kubectl get petsets --all-namespaces ``` At this moment, you've deleted all PetSets in your cluster, but not their Pods, Persistent Volumes, or Persistent Volume Claims. However, since the Pods are not managed by PetSets anymore, they will be vulnerable to node failures until you finish the master upgrade and recreate StatefulSets. ### Upgrade your master to Kubernetes version 1.5 or later Now, you can [upgrade your Kubernetes master](/docs/admin/cluster-management/#upgrading-a-cluster) to Kubernetes version 1.5 or later. Note that **you should NOT upgrade Nodes at this time**, because the Pods (that were once managed by PetSets) are now vulnerable to node failures. ### Upgrade kubectl to Kubernetes version 1.5 or later Upgrade `kubectl` to Kubernetes version 1.5 or later, following [the steps for installing and setting up kubectl](/docs/tasks/kubectl/install/). ### Create StatefulSets Make sure you have both master and `kubectl` upgraded to Kubernetes version 1.5 or later before continuing: ```shell kubectl version ``` The output is similar to this: ```shell Client Version: version.Info{Major:\"1\", Minor:\"5\", GitVersion:\"v1.5.0\", GitCommit:\"0776eab45fe28f02bbeac0f05ae1a203051a21eb\", GitTreeState:\"clean\", BuildDate:\"2016-11-24T22:35:03Z\", GoVersion:\"go1.7.3\", Compiler:\"gc\", Platform:\"linux/amd64\"} Server Version: version.Info{Major:\"1\", Minor:\"5\", GitVersion:\"v1.5.0\", GitCommit:\"0776eab45fe28f02bbeac0f05ae1a203051a21eb\", GitTreeState:\"clean\", BuildDate:\"2016-11-24T22:30:23Z\", GoVersion:\"go1.7.3\", Compiler:\"gc\", Platform:\"linux/amd64\"} ``` If both `Client Version` (`kubectl` version) and `Server Version` (master version) are 1.5 or later, you are good to go. Create StatefulSets to adopt the Pods belonging to the deleted PetSets with the StatefulSet manifests generated in the previous step: ```shell kubectl create -f ``` Make sure all StatefulSets are created and running as expected in the newly-upgraded cluster: ```shell kubectl get statefulsets --all-namespaces ``` ### Upgrade nodes to Kubernetes version 1.5 or later (optional) You can now [upgrade Kubernetes nodes](/docs/admin/cluster-management/#upgrading-a-cluster) to Kubernetes version 1.5 or later. This step is optional, but needs to be done after all StatefulSets are created to adopt PetSets' Pods. You should be running Node version >= 1.1.0 to run StatefulSets safely. Older versions do not support features which allow the StatefulSet to guarantee that at any time, there is **at most** one Pod with a given identity running in a cluster. {% endcapture %} {% capture whatsnext %} Learn more about [scaling a StatefulSet](/docs/tasks/manage-stateful-set/scale-stateful-set/). {% endcapture %} {% include templates/task.md %} "} {"_id":"q-en-website-802fce7e948af9c64997cdcc4eec87516d190ae03a59a539fd39ad2f460053de","text":"The value is a comma-separated list of the names of namespaces other than the parent's namespace in which objects are found. ### applyset.kubernetes.io/contains-group-resources (alpha) {#applyset-kubernetes-io-contains-group-resources} ### applyset.kubernetes.io/contains-group-kinds (alpha) {#applyset-kubernetes-io-contains-group-kinds} Type: Annotation Example: `applyset.kubernetes.io/contains-group-resources: \"certificates.cert-manager.io,configmaps,deployments.apps,secrets,services\"` Example: `applyset.kubernetes.io/contains-group-kinds: \"certificates.cert-manager.io,configmaps,deployments.apps,secrets,services\"` Used on: Objects being used as ApplySet parents."} {"_id":"q-en-website-80721b1a09dffb50e06fa27f43252ae61de9d9f4ecc841e1e92c99458971b890","text":"* コンテナランタイムがcgroup v2をサポートしていること。例えば、 * [containerd](https://containerd.io/) v1.4以降 * [cri-o](https://cri-o.io/) v1.20以降 * kubeletとコンテナランタイムが[systemd cgroupドライバー](/docs/setup/production-environment/container-runtimes#systemd-cgroup-driver)を使うように設定されていること * kubeletとコンテナランタイムが[systemd cgroupドライバー](/ja/docs/setup/production-environment/container-runtimes#systemd-cgroup-driver)を使うように設定されていること ### Linuxディストリビューションのcgroup v2サポート"} {"_id":"q-en-website-80d88dc26b7812fd08120adc781ad27253a9a4bdbbd13faa6180b0b9a841ce4a","text":"You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using [minikube](/docs/tasks/tools/#minikube) [minikube](https://minikube.sigs.k8s.io/docs/tutorials/multi_node/) or you can use one of these Kubernetes playgrounds: * [Katacoda](https://www.katacoda.com/courses/kubernetes/playground)"} {"_id":"q-en-website-856fbe9ff6e74f0e46768616016c0a1da32e47235aadd256b4459564ae7b2df2","text":" apiVersion: v1 kind: Pod metadata: name: dapi-test-pod spec: containers: - name: test-container image: k8s.gcr.io/busybox command: [ \"/bin/sh\", \"-c\", \"echo $(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)\" ] env: - name: SPECIAL_LEVEL_KEY valueFrom: configMapKeyRef: name: special-config key: SPECIAL_LEVEL - name: SPECIAL_TYPE_KEY valueFrom: configMapKeyRef: name: special-config key: SPECIAL_TYPE restartPolicy: Never "} {"_id":"q-en-website-8830dec1d937898e15bda568734b55239fa45636a127b4190a250ca0724d0b90","text":" --- title: Podを構成してConfigMapを使用する content_template: templates/task weight: 150 card: name: tasks weight: 50 --- {{% capture overview %}} ConfigMapを使用すると、設定をイメージコンテンツから切り離して、コンテナ化されたアプリケーションの移植性を維持できます。このページでは、ConfigMapを作成し、ConfigMapに保存されているデータを使用してPodを構成する一連の使用例を示します。 {{% /capture %}} {{% capture prerequisites %}} {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} {{% /capture %}} {{% capture steps %}} ## ConfigMapを作成する `kubectl create configmap`コマンドまたは`kustomization.yaml`のConfigMap generatorを使用してConfigMapを作成できます。`kubectl`が`kustomization.yaml`をサポートをしているのは1.14からである点に注意してください。 ### kubectl create configmapコマンドを使用してConfigMapを作成する `kubectl create configmap`コマンドを使用してConfigMapを[ディレクトリ](#create-configmaps-from-directories)、[ファイル](#create-configmaps-from-files)、または[リテラル値](#create-configmaps-from-literal-values)から作成します: ```shell kubectl create configmap ``` の部分はConfigMapに割り当てる名前で、はデータを取得するディレクトリ、ファイル、またはリテラル値です。ConfigMapオブジェクト名は有効な[DNSサブドメイン名](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names)である必要があります。 ファイルを基にConfigMapを作成する場合、 のキーはデフォルトでファイルのベース名になり、値はデフォルトでファイルのコンテンツになります。 [`kubectl describe`](/docs/reference/generated/kubectl/kubectl-commands/#describe)または [`kubectl get`](/docs/reference/generated/kubectl/kubectl-commands/#get)を使用して、ConfigMapに関する情報を取得できます。 #### ディレクトリからConfigMapを作成する{#create-configmaps-from-directories} `kubectl create configmap`を使用すると、同一ディレクトリ内にある複数のファイルから1つのConfigMapを作成できます。ディレクトリをベースにConfigMapを作成する場合、kubectlはディレクトリ内でベース名が有効なキーであるファイルを識別し、それらのファイルを新たなConfigMapにパッケージ化します。ディレクトリ内にある通常のファイルでないものは無視されます(例: サブディレクトリ、シンボリックリンク、デバイス、パイプなど)。 例えば: ```shell # ローカルディレクトリを作成します mkdir -p configure-pod-container/configmap/ # `configure-pod-container/configmap/`ディレクトリにサンプルファイルをダウンロードします wget https://kubernetes.io/examples/configmap/game.properties -O configure-pod-container/configmap/game.properties wget https://kubernetes.io/examples/configmap/ui.properties -O configure-pod-container/configmap/ui.properties # ConfigMapを作成します kubectl create configmap game-config --from-file=configure-pod-container/configmap/ ``` 上記のコマンドは各ファイルを、この場合、`configure-pod-container/configmap/` ディレクトリの`game.properties` と `ui.properties`をgame-config ConfigMapにパッケージ化します。 以下のコマンドを使用してConfigMapの詳細を表示できます: ```shell kubectl describe configmaps game-config ``` 出力結果は以下のようになります: ``` Name: game-config Namespace: default Labels: Annotations: Data ==== game.properties: ---- enemies=aliens lives=3 enemies.cheat=true enemies.cheat.level=noGoodRotten secret.code.passphrase=UUDDLRLRBABAS secret.code.allowed=true secret.code.lives=30 ui.properties: ---- color.good=purple color.bad=yellow allow.textmode=true how.nice.to.look=fairlyNice ``` `configure-pod-container/configmap/` ディレクトリの`game.properties` と `ui.properties` ファイルはConfigMapの`data`セクションに表示されます。 ```shell kubectl get configmaps game-config -o yaml ``` 出力結果は以下のようになります: ```yaml apiVersion: v1 kind: ConfigMap metadata: creationTimestamp: 2016-02-18T18:52:05Z name: game-config namespace: default resourceVersion: \"516\" uid: b4952dc3-d670-11e5-8cd0-68f728db1985 data: game.properties: | enemies=aliens lives=3 enemies.cheat=true enemies.cheat.level=noGoodRotten secret.code.passphrase=UUDDLRLRBABAS secret.code.allowed=true secret.code.lives=30 ui.properties: | color.good=purple color.bad=yellow allow.textmode=true how.nice.to.look=fairlyNice ``` #### ファイルからConfigMapを作成する{#create-configmaps-from-files} `kubectl create configmap`を使用して個別のファイルから、または複数のファイルからConfigMapを作成できます。 例えば、 ```shell kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties ``` は、以下のConfigMapを生成します: ```shell kubectl describe configmaps game-config-2 ``` 出力結果は以下のようになります: ``` Name: game-config-2 Namespace: default Labels: Annotations: Data ==== game.properties: ---- enemies=aliens lives=3 enemies.cheat=true enemies.cheat.level=noGoodRotten secret.code.passphrase=UUDDLRLRBABAS secret.code.allowed=true secret.code.lives=30 ``` `--from-file`引数を複数回渡し、ConfigMapを複数のデータソースから作成できます。 ```shell kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties --from-file=configure-pod-container/configmap/ui.properties ``` ConfigMap`game-config-2`の詳細を以下のコマンドを使用して表示できます: ```shell kubectl describe configmaps game-config-2 ``` 出力結果は以下のようになります: ``` Name: game-config-2 Namespace: default Labels: Annotations: Data ==== game.properties: ---- enemies=aliens lives=3 enemies.cheat=true enemies.cheat.level=noGoodRotten secret.code.passphrase=UUDDLRLRBABAS secret.code.allowed=true secret.code.lives=30 ui.properties: ---- color.good=purple color.bad=yellow allow.textmode=true how.nice.to.look=fairlyNice ``` `--from-env-file`オプションを利用してConfigMapをenv-fileから作成します。例えば: ```shell # Env-filesは環境編集のリストを含んでいます。 # 以下のシンタックスルールが適用されます: # envファイルの各行はVAR=VALの形式である必要がある。 # #で始まる行 (例えばコメント)は無視される。 # 空の行は無視される。 # クオーテーションマークは特別な扱いは処理をしない(例えばConfigMapの値になる). # `configure-pod-container/configmap/`ディレクトリにサンプルファイルをダウンロードします wget https://kubernetes.io/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties # env-file `game-env-file.properties`は以下のようになります cat configure-pod-container/configmap/game-env-file.properties enemies=aliens lives=3 allowed=\"true\" # このコメントと上記の空の行は無視されます ``` ```shell kubectl create configmap game-config-env-file --from-env-file=configure-pod-container/configmap/game-env-file.properties ``` 以下のConfigMapを表示します: ```shell kubectl get configmap game-config-env-file -o yaml ``` 出力結果は以下のようになります: ```yaml apiVersion: v1 kind: ConfigMap metadata: creationTimestamp: 2017-12-27T18:36:28Z name: game-config-env-file namespace: default resourceVersion: \"809965\" uid: d9d1ca5b-eb34-11e7-887b-42010a8002b8 data: allowed: '\"true\"' enemies: aliens lives: \"3\" ``` {{< caution >}} `--from-env-file`を複数回渡してConfigMapを複数のデータソースから作成する場合、最後のenv-fileのみが使用されます。 {{< /caution >}} `--from-env-file`を複数回渡す場合の挙動は以下のように示されます: ```shell # `configure-pod-container/configmap/`ディレクトリにサンブルファイルをダウンロードします wget https://kubernetes.io/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties # ConfigMapを作成します kubectl create configmap config-multi-env-files --from-env-file=configure-pod-container/configmap/game-env-file.properties --from-env-file=configure-pod-container/configmap/ui-env-file.properties ``` 以下のConfigMapを表示します: ```shell kubectl get configmap config-multi-env-files -o yaml ``` 出力結果は以下のようになります: ```yaml apiVersion: v1 kind: ConfigMap metadata: creationTimestamp: 2017-12-27T18:38:34Z name: config-multi-env-files namespace: default resourceVersion: \"810136\" uid: 252c4572-eb35-11e7-887b-42010a8002b8 data: color: purple how: fairlyNice textmode: \"true\" ``` #### ファイルからConfigMap作成する場合は使用するキーを定義する `--from-file`引数を使用する場合、ConfigMapの`data` セクションでキーにファイル名以外を定義できます: ```shell kubectl create configmap game-config-3 --from-file== ``` ``の部分はConfigMapで使うキー、`` はキーで表示したいデータソースファイルの場所です。 例えば: ```shell kubectl create configmap game-config-3 --from-file=game-special-key=configure-pod-container/configmap/game.properties ``` 以下のConfigMapを表示します: ``` kubectl get configmaps game-config-3 -o yaml ``` 出力結果は以下のようになります: ```yaml apiVersion: v1 kind: ConfigMap metadata: creationTimestamp: 2016-02-18T18:54:22Z name: game-config-3 namespace: default resourceVersion: \"530\" uid: 05f8da22-d671-11e5-8cd0-68f728db1985 data: game-special-key: | enemies=aliens lives=3 enemies.cheat=true enemies.cheat.level=noGoodRotten secret.code.passphrase=UUDDLRLRBABAS secret.code.allowed=true secret.code.lives=30 ``` #### リテラル値からConfigMapを作成する{#create-configmaps-from-literal-values} `kubectl create configmap`を`--from-literal`引数と使用してCLIからリテラル値を定義できます: ```shell kubectl create configmap special-config --from-literal=special.how=very --from-literal=special.type=charm ``` 複数のキーバリューペアを渡せます。CLIに提供された各ペアは、ConfigMapの`data`セクションで別のエントリーとして表示されます。 ```shell kubectl get configmaps special-config -o yaml ``` 出力結果は以下のようになります: ```yaml apiVersion: v1 kind: ConfigMap metadata: creationTimestamp: 2016-02-18T19:14:38Z name: special-config namespace: default resourceVersion: \"651\" uid: dadce046-d673-11e5-8cd0-68f728db1985 data: special.how: very special.type: charm ``` ### ジェネレータからConfigMapを作成する `kubectl`は`kustomization.yaml`を1.14からサポートしています。 ジェネレータからConfigMapを作成し、APIサーバー上でオブジェクトを作成できます。ジェネレータはディレクトリ内の`kustomization.yaml`で指定する必要があリます。 #### ファイルからConfigMapを生成する 例えば、ファイル`configure-pod-container/configmap/game.properties`からConfigMapを生成するには、 ```shell # ConfigMapGeneratorでkustomization.yamlファイルを作成する cat <./kustomization.yaml configMapGenerator: - name: game-config-4 files: - configure-pod-container/configmap/game.properties EOF ``` ConfigMapオブジェクトを作成する為にkustomizationディレクトリを適用して、 ```shell kubectl apply -k . configmap/game-config-4-m9dm2f92bt created ``` ConfigMapが作成されたことを以下のようにチェックできます: ```shell kubectl get configmap NAME DATA AGE game-config-4-m9dm2f92bt 1 37s kubectl describe configmaps/game-config-4-m9dm2f92bt Name: game-config-4-m9dm2f92bt Namespace: default Labels: Annotations: kubectl.kubernetes.io/last-applied-configuration: {\"apiVersion\":\"v1\",\"data\":{\"game.properties\":\"enemies=aliensnlives=3nenemies.cheat=truenenemies.cheat.level=noGoodRottennsecret.code.p... Data ==== game.properties: ---- enemies=aliens lives=3 enemies.cheat=true enemies.cheat.level=noGoodRotten secret.code.passphrase=UUDDLRLRBABAS secret.code.allowed=true secret.code.lives=30 Events: ``` 生成されたConfigMapの名前は、コンテンツをハッシュ化したサフィックスを持つことに注意してください。これにより、コンテンツが変更されるたびに新しいConfigMapが生成されます。 #### ファイルからConfigMapを生成する場合に使用するキーを定義する ConfigMapジェネレータで使用するキーはファイルの名前以外を定義できます。 例えば、ファイル`configure-pod-container/configmap/game.properties`とキー`game-special-key`を使用してConfigMapを作成する場合 ```shell # ConfigMapGeneratorでkustomization.yamlファイルを作成する cat <./kustomization.yaml configMapGenerator: - name: game-config-5 files: - game-special-key=configure-pod-container/configmap/game.properties EOF ``` kustomizationディレクトリを適用してConfigMapオブジェクトを作成します。 ```shell kubectl apply -k . configmap/game-config-5-m67dt67794 created ``` #### リテラルからConfigMapを作成する To generate a ConfigMap from literals `special.type=charm` and `special.how=very`, you can specify the ConfigMap generator in `kustomization.yaml` as ```shell # kustomization.yamlファイルをConfigMapGeneratorと作成します cat <./kustomization.yaml configMapGenerator: - name: special-config-2 literals: - special.how=very - special.type=charm EOF ``` kustomizationディレクトリを適用してConfigMapオブジェクトを作成します。 ```shell kubectl apply -k . configmap/special-config-2-c92b5mmcf2 created ``` ## ConfigMapデータを使用してコンテナ環境変数を定義する ### 単一のConfigMapのデータを使用してコンテナ環境変数を定義する 1. ConfigMapに環境変数をキーバリューペアとして定義します: ```shell kubectl create configmap special-config --from-literal=special.how=very ``` 2. ConfigMapに定義された値`special.how`をPod specificationの環境変数`SPECIAL_LEVEL_KEY`に割り当てます。 {{< codenew file=\"pods/pod-single-configmap-env-variable.yaml\" >}} Podを作成します: ```shell kubectl create -f https://kubernetes.io/examples/pods/pod-single-configmap-env-variable.yaml ``` すると、Podの出力結果に環境変数`SPECIAL_LEVEL_KEY=very`が含まれています。 ### 複数のConfigMapのデータを使用してコンテナ環境変数を定義する * 先ほどの例の通り、まずはConfigMapを作成します。 {{< codenew file=\"configmap/configmaps.yaml\" >}} ConfigMapを作成します: ```shell kubectl create -f https://kubernetes.io/examples/configmap/configmaps.yaml ``` * Pod specificationの環境変数を定義します {{< codenew file=\"pods/pod-multiple-configmap-env-variable.yaml\" >}} Podを作成します: ```shell kubectl create -f https://kubernetes.io/examples/pods/pod-multiple-configmap-env-variable.yaml ``` すると、Podの出力結果に環境変数`SPECIAL_LEVEL_KEY=very` and `LOG_LEVEL=INFO`が含まれています。 ## ConfigMapの全てのキーバリューペアをコンテナ環境変数として構成する {{< note >}} この機能はKubernetes v1.6以降で利用可能です。 {{< /note >}} * 複数のキーバリューペアを含むConfigMapを作成します。 {{< codenew file=\"configmap/configmap-multikeys.yaml\" >}} ConfigMapを作成します: ```shell kubectl create -f https://kubernetes.io/examples/configmap/configmap-multikeys.yaml ``` * `envFrom`を利用して全てのConfigMapのデータをコンテナ環境変数として定義します。ConfigMapからのキーがPodの環境変数名になります。 {{< codenew file=\"pods/pod-configmap-envFrom.yaml\" >}} Podを作成します: ```shell kubectl create -f https://kubernetes.io/examples/pods/pod-configmap-envFrom.yaml ``` すると、Podの出力結果は環境変数`SPECIAL_LEVEL=very`と`SPECIAL_TYPE=charm`が含まれています。 ## PodのコマンドでConfigMapに定義した環境変数を使用する ConfigMapに環境変数を定義し、Pod specificationの`command` セクションで`$(VAR_NAME)`Kubernetes置換構文を介して使用できます。 例えば以下のPod specificationは {{< codenew file=\"pods/pod-configmap-env-var-valueFrom.yaml\" >}} 以下コマンドの実行で作成され、 ```shell kubectl create -f https://kubernetes.io/examples/pods/pod-configmap-env-var-valueFrom.yaml ``` `test-container`コンテナで以下の出力結果を表示します: ```shell very charm ``` ## ボリュームにConfigMapデータを追加する [ファイルからConfigMapを作成する](#create-configmaps-from-files)で説明したように、``--from-file``を使用してConfigMapを作成する場合は、ファイル名がConfigMapの`data`セクションに保存されるキーになり、ファイルのコンテンツがキーの値になります。 このセクションの例は以下に示されているspecial-configと名付けれたConfigMapについて言及したものです。 {{< codenew file=\"configmap/configmap-multikeys.yaml\" >}} ConfigMapを作成します: ```shell kubectl create -f https://kubernetes.io/examples/configmap/configmap-multikeys.yaml ``` ### ConfigMapに保存されているデータをボリュームに入力する ConfigMap名をPod specificationの`volumes`セクション配下に追加します。 これによりConfigMapデータが`volumeMounts.mountPath`で指定されたディレクトリに追加されます (このケースでは、`/etc/config`に)。`command`セクションはConfigMapのキーに合致したディレクトリファイルを名前別でリスト表示します。 {{< codenew file=\"pods/pod-configmap-volume.yaml\" >}} Podを作成します: ```shell kubectl create -f https://kubernetes.io/examples/pods/pod-configmap-volume.yaml ``` Podが稼働していると、`ls /etc/config/`コマンドは以下の出力結果を表示します: ```shell SPECIAL_LEVEL SPECIAL_TYPE ``` {{< caution >}} `/etc/config/`ディレクトリに何かファイルがある場合、それらは削除されます。 {{< /caution >}} ### ConfigMapデータをボリュームの特定のパスに追加する `path`フィルドを利用して特定のConfigMapのアイテム向けに希望のファイルパスを指定します。 このケースでは`SPECIAL_LEVEL`アイテムが`/etc/config/keys`の`config-volume`ボリュームにマウントされます。 {{< codenew file=\"pods/pod-configmap-volume-specific-key.yaml\" >}} Podを作成します: ```shell kubectl create -f https://kubernetes.io/examples/pods/pod-configmap-volume-specific-key.yaml ``` Podが稼働していると、 `cat /etc/config/keys`コマンドは以下の出力結果を表示します: ```shell very ``` {{< caution >}} 先ほどのように、`/etc/config/` ディレクトリのこれまでのファイルは全て削除されます {{< /caution >}} ### キーを特定のパスとファイルアクセス許可に投影する キーをファイル単位で特定のパスとアクセス許可に投影できます。[Secrets](/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod)のユーザーガイドで構文が解説されています。 ### マウントされたConfigMapは自動的に更新される ボリュームで使用されているConfigMapが更新されている場合、投影されているキーも同じく結果的に更新されます。Kubeletは定期的な同期ごとにマウントされているConfigMapが更新されているかチェックします。しかし、これはローカルのttlを基にしたキャッシュでConfigMapの現在の値を取得しています。その結果、新しいキーがPodに投影されてからConfigMapに更新されるまでのトータルの遅延はkubeletで、kubeletの同期期間(デフォルトで1分) + ConfigMapキャッシュのttl(デフォルトで1分)の長さになる可能性があります。Podのアノテーションを1つ更新すると即時のリフレッシュをトリガーできます。 {{< note >}} ConfigMapを[subPath](/docs/concepts/storage/volumes/#using-subpath)ボリュームとして利用するコンテナはConfigMapの更新を受け取りません。 {{< /note >}} {{% /capture %}} {{% capture discussion %}} ## ConfigMapとPodsを理解する ConfigMap APIリソースは構成情報をキーバリューペアとして保存します。データはPodで利用したり、コントローラーなどのシステムコンポーネントに提供できます。ConfigMapは[Secrets](/docs/concepts/configuration/secret/)に似ていますが、機密情報を含まない文字列を含まない操作する手段を提供します。ユーザーとシステムコンポーネントはどちらも構成情報をConfigMapに保存できます。 {{< note >}} ConfigMapはプロパティファイルを参照するべきであり、置き換えるべきではありません。ConfigMapをLinuxの`/etc`ディレクトリとそのコンテンツのように捉えましょう。例えば、[Kubernetes Volume](/docs/concepts/storage/volumes/)をConfigMapから作成した場合、ConfigMapのデータアイテムはボリューム内で個別のファイルとして表示されます。 {{< /note >}} ConfigMapの`data`フィールドは構成情報を含みます。下記の例のようにシンプルに`--from-literal`を使用して個別のプロパティーを定義、または複雑に`--from-file`を使用して構成ファイルまたはJSON blobsで定義できます。 ```yaml apiVersion: v1 kind: ConfigMap metadata: creationTimestamp: 2016-02-18T19:14:38Z name: example-config namespace: default data: # --from-literalを使用してシンプルにプロパティーを定義する例 example.property.1: hello example.property.2: world # --from-fileを使用して複雑にプロパティーを定義する例 example.property.file: |- property.1=value-1 property.2=value-2 property.3=value-3 ``` ### 制限事項 - ConfigMapはPod specificationを参照させる前に作成する必要があります(ConfigMapを\"optional\"として設定しない限り)。存在しないConfigMapを参照させた場合、Podは起動しません。同様にConfigMapに存在しないキーを参照させた場合も、Podは起動しません。 - ConfigMapで`envFrom`を使用して環境変数を定義した場合、無効と判断されたキーはスキップされます。Podは起動されますが、無効な名前はイベントログに(`InvalidVariableNames`)と記録されます。ログメッセージはスキップされたキーごとにリスト表示されます。例えば: ```shell kubectl get events ``` 出力結果は以下のようになります: ``` LASTSEEN FIRSTSEEN COUNT NAME KIND SUBOBJECT TYPE REASON SOURCE MESSAGE 0s 0s 1 dapi-test-pod Pod Warning InvalidEnvironmentVariableNames {kubelet, 127.0.0.1} Keys [1badkey, 2alsobad] from the EnvFrom configMap default/myconfig were skipped since they are considered invalid environment variable names. ``` - ConfigMapは特定の{{< glossary_tooltip term_id=\"namespace\" >}}に属します。ConfigMap同じ名前空間に属するPodからのみ参照できます。 - {{< glossary_tooltip text=\"static pods\" term_id=\"static-pod\" >}}はKubeletがサポートしていない為、ConfigMapに使用できません。 {{% /capture %}} {{% capture whatsnext %}} * 実践例[Configuring Redis using a ConfigMap](/docs/tutorials/configuration/configure-redis-using-configmap/)を続けて読む。 {{% /capture %}} "} {"_id":"q-en-website-88926cd1aba1b784307bc35fa0e56b030fbfbe860f29d84a12becebf6777ed38","text":"### Scheduled by default scheduler --> ## 如何调度 Daemon Pods ## Daemon Pods 是如何被调度的 ### 通过默认调度器调度"} {"_id":"q-en-website-8a7237d3dbbd1f845fc933c2ec5134ceef1eaf6ad18d07ebe1082b286c7742a4","text":"other = \"后一篇 >>\" [layouts_case_studies_list_tell] other = \"分享您的故事\" other = \"分享你的故事\" [layouts_docs_glossary_aka] other = \"亦称作\""} {"_id":"q-en-website-8d1ef35196973d25b28f4a46dbb9481ef765f8c1261926bfa4da53c78a20a262","text":"[handbook-patch-release]: https://git.k8s.io/sig-release/release-engineering/role-handbooks/patch-release-team.md [k-sig-release-releases]: https://git.k8s.io/sig-release/releases [patches]: /patch-releases.md [src]: https://git.k8s.io/community/committee-product-security/README.md [src]: https://git.k8s.io/community/committee-security-response/README.md [release-team]: https://git.k8s.io/sig-release/release-team/README.md [security-release-process]: https://git.k8s.io/security/security-release-process.md"} {"_id":"q-en-website-8e6716756a6221ad868f3aa33a70e0951001a05f43da923a00ba5ea3dc404d9c","text":"```json { \"name\": \"k8s-pod-network\", \"cniVersion\": \"0.3.0\", \"cniVersion\": \"0.4.0\", \"plugins\": [ { \"type\": \"calico\","} {"_id":"q-en-website-8ecd19a0d11fa490f986f746e7a56e29a18e6ae66c22e5c5b09d450bda2e81d9","text":"| Feature | Description | CRDs | Aggregated API | | ------- | ----------- | ---- | -------------- | | Validation | Help users prevent errors and allow you to evolve your API independently of your clients. These features are most useful when there are many clients who can't all update at the same time. | Yes. Most validation can be specified in the CRD using [OpenAPI v3.0 validation](/docs/tasks/extend-kubernetes/extend-api-custom-resource-definitions/#validation). Any other validations supported by addition of a [Validating Webhook](/docs/reference/access-authn-authz/admission-controllers/#validatingadmissionwebhook-alpha-in-1-8-beta-in-1-9). | Yes, arbitrary validation checks | | Validation | Help users prevent errors and allow you to evolve your API independently of your clients. These features are most useful when there are many clients who can't all update at the same time. | Yes. Most validation can be specified in the CRD using [OpenAPI v3.0 validation](/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#validation). Any other validations supported by addition of a [Validating Webhook](/docs/reference/access-authn-authz/admission-controllers/#validatingadmissionwebhook-alpha-in-1-8-beta-in-1-9). | Yes, arbitrary validation checks | | Defaulting | See above | Yes, either via [OpenAPI v3.0 validation](/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#defaulting) `default` keyword (GA in 1.17), or via a [Mutating Webhook](/docs/reference/access-authn-authz/admission-controllers/#mutatingadmissionwebhook) (though this will not be run when reading from etcd for old objects). | Yes | | Multi-versioning | Allows serving the same object through two API versions. Can help ease API changes like renaming fields. Less important if you control your client versions. | [Yes](/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning) | Yes | | Custom Storage | If you need storage with a different performance mode (for example, a time-series database instead of key-value store) or isolation for security (for example, encryption of sensitive information, etc.) | No | Yes |"} {"_id":"q-en-website-90671e9b5ee6082be990c8bbd998ed0e0438a0d9496eedd4eda58aeb1c8fae43","text":"* A compatible Linux host. The Kubernetes project provides generic instructions for Linux distributions based on Debian and Red Hat, and those distributions without a package manager. * 2 GB or more of RAM per machine (any less will leave little room for your apps). * 2 CPUs or more. * 2 CPUs or more for control plane machines. * Full network connectivity between all machines in the cluster (public or private network is fine). * Unique hostname, MAC address, and product_uuid for every node. See [here](#verify-mac-address) for more details. * Certain ports are open on your machines. See [here](#check-required-ports) for more details."} {"_id":"q-en-website-90bbe112b72d0a0dd5753851dce50dbb9f1916bf1357fe0ca092057c5a659aff","text":"### 当使用 `kubeadm init`时的工作流程 当调用 `kubeadm init` 时,kubelet 的配置会被写入磁盘 `/var/lib/kubelet/config.yaml`, 并上传到集群 `kubee-system` 命名空间的 `kubelet-config` ConfigMap。 并上传到集群 `kube-system` 命名空间的 `kubelet-config` ConfigMap。 kubelet 配置信息也被写入 `/etc/kubernetes/kubelet.conf`,其中包含集群内所有 kubelet 的基线配置。 此配置文件指向允许 kubelet 与 API 服务器通信的客户端证书。 这解决了[将集群级配置传播到每个 kubelet](#propagating-cluster-level-configuration-to-each-kubelet) 的需求。"} {"_id":"q-en-website-91ad4a79a8a674753dcc15bfb1e87e36b1def78de8287e07d20df8200575ad36","text":"title: \"Production-Grade Container Orchestration\" abstract: \"Automated container deployment, scaling, and management\" cid: home sitemap: priority: 1.0 --- {{< blocks/section id=\"oceanNodes\" >}}"} {"_id":"q-en-website-94bf808b682dd1eb5c235444d94b27603d65ecf6c9d2373cd737f8a76ed40f14","text":"* The root filesystem of the Node will be mounted at `/host`. * The container runs in the host IPC, Network, and PID namespaces, although the pod isn't privileged, so reading some process information may fail, and `chroot /host` will fail. and `chroot /host` may fail. * If you need a privileged pod, create it manually. Don't forget to clean up the debugging Pod when you're finished with it:"} {"_id":"q-en-website-94d212b917b6b9c1ae9bdff5fff8b3b930bcdde54cb6f605f8914ff0482d0e21","text":"other = \"搜索\" [version_check_mustbe] other = \"您的 Kubernetes 服务器版本必须是 \" other = \"你的 Kubernetes 服务器版本必须是 \" [version_check_mustbeorlater] other = \"您的 Kubernetes 服务器版本必须不低于版本 \" other = \"你的 Kubernetes 服务器版本必须不低于版本 \" [version_check_tocheck] other = \"要获知版本信息,请输入 \""} {"_id":"q-en-website-9513b7f0fadec31b929984eeefcde9502f19bbb438beaa2b42c4c579e37b73a0","text":"It's possible to configure `kubeadm init` with a configuration file instead of command line flags, and some more advanced features may only be available as configuration file options. This file is passed with the `--config` option. configuration file options. This file is passed using the `--config` flag and it must contain a `ClusterConfiguration` structure and optionally more structures separated by `---n` Mixing `--config` with others flags may not be allowed in some cases. The default configuration can be printed out using the [kubeadm config print](/docs/reference/setup-tools/kubeadm/kubeadm-config/) command. It is **recommended** that you migrate your old `v1beta1` configuration to `v1beta2` using If your configuration is not using the latest version it is **recommended** that you migrate using the [kubeadm config migrate](/docs/reference/setup-tools/kubeadm/kubeadm-config/) command. For more details on each field in the `v1beta2` configuration you can navigate to our [API reference pages](https://godoc.org/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2). For more information on the fields and usage of the configuration you can navigate to our API reference page and pick a version from [the list](https://godoc.org/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm#pkg-subdirectories). ### Adding kube-proxy parameters {#kube-proxy}"} {"_id":"q-en-website-974860b3f4d049a539d48a11798ee9b5ffb7c6b3c1a32b5269d70c9c7bebe6ec","text":"{{ if .HasShortcode \"kat-button\" }}
{{ end }} {{ with .Site.Params.algolia_docsearch }} "} {"_id":"q-en-website-97b8d4a85829b49821eb3c3142cc331b7402421f55dcab9d9009548a48038bbd","text":"string

ontrolPlaneEndpoint sets a stable IP address or DNS name for the control plane;

controlPlaneEndpoint sets a stable IP address or DNS name for the control plane; It can be a valid IP address or a RFC-1123 DNS subdomain, both with optional TCP port. In case the controlPlaneEndpoint is not specified, the advertiseAddress + bindPort are used; in case the controlPlaneEndpoint is specified but without a TCP port,"} {"_id":"q-en-website-97d8e6217b20252a80d8ab86b282fa1f44e7feab4b7b90cc6b4e515346bada19","text":"``` ```shell kubectl get pods -l run=cattle -n=production kubectl get pods -l app=cattle -n=production ``` ``` NAME READY STATUS RESTARTS AGE"} {"_id":"q-en-website-98cdbfdbbe73a9be31c513203afc4d979832efc69521d6551f151296d5c06ecf","text":"| `AnyVolumeDataSource` | `false` | Alpha | 1.18 | 1.23 | | `AnyVolumeDataSource` | `true` | Beta | 1.24 | | | `AppArmor` | `true` | Beta | 1.4 | | | `CheckpointContainer` | `false` | Alpha | 1.25 | | | `ContainerCheckpoint` | `false` | Alpha | 1.25 | | | `CPUManager` | `false` | Alpha | 1.8 | 1.9 | | `CPUManager` | `true` | Beta | 1.10 | | | `CPUManagerPolicyAlphaOptions` | `false` | Alpha | 1.23 | |"} {"_id":"q-en-website-98fb08fe50644b9f8ccf8d736315609035e3adb2d798acc3334a2e5a5eb5bce6","text":"managing controller to process any [finalizer rules](/docs/concepts/overview/working-with-objects/finalizers/) for the resource. {{}} 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 correctly. For example, if you try to delete a [PersistentVolume](/docs/concepts/storage/persistent-volumes/) 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 Instead, the [volume](/docs/concepts/storage/volumes/) remains in the `Terminating` status until Kubernetes clears the finalizer, which only happens after the `PersistentVolume` is no longer bound to a Pod."} {"_id":"q-en-website-99f6b9b3840655a2e6a81b38cb3aa4d6bb02842743c8bb366cd3487b6668764e","text":"``` ```shell kubectl get pods -l run=snowflake kubectl get pods -l app=snowflake ``` ``` NAME READY STATUS RESTARTS AGE"} {"_id":"q-en-website-9c2e6002cb05a237403d0bf6073378fbc915d90aa8f6388bfb85bbba688aa126","text":" Stack Overflow. {{ T \"layouts_docs_partials_feedback_issue\" }} {{ T \"layouts_docs_partials_feedback_issue\" | markdownify }} {{ T \"layouts_docs_partials_feedback_problem\" }}"} {"_id":"q-en-website-9c3e2034783455f75b66dbed8900f423b3fae6c6051e2c0b790192fca8ede418","text":"## {{% heading \"prerequisites\" %}} Kubernetesの[コンテナランタイムの要件](/docs/setup/production-environment/container-runtimes)を熟知している必要があります。 Kubernetesの[コンテナランタイムの要件](/ja/docs/setup/production-environment/container-runtimes)を熟知している必要があります。 ## コンテナランタイムのcgroupドライバーの設定 [Container runtimes](/docs/setup/production-environment/container-runtimes)ページでは、kubeadmベースのセットアップでは`cgroupfs`ドライバーではなく、`systemd`ドライバーが推奨されると説明されています。 [コンテナランタイム](/ja/docs/setup/production-environment/container-runtimes)ページでは、kubeadmベースのセットアップでは`cgroupfs`ドライバーではなく、`systemd`ドライバーが推奨されると説明されています。 このページでは、デフォルトの`systemd`ドライバーを使用して多くの異なるコンテナランタイムをセットアップする方法についての詳細も説明されています。 ## kubelet cgroupドライバーの設定 ## kubelet cgroupドライバーの設定 {#configuring-the-kubelet-cgroup-driver} kubeadmでは、`kubeadm init`の際に`KubeletConfiguration`構造体を渡すことができます。"} {"_id":"q-en-website-9cf66b6a1cc71bbe282bb74915e2beab511c08e051d8d4ed0428337195e5a65c","text":" apiVersion: batch/v1 kind: Job metadata: name: 'indexed-job' spec: completions: 5 parallelism: 3 completionMode: Indexed template: spec: restartPolicy: Never containers: - name: 'worker' image: 'docker.io/library/busybox' command: - \"rev\" - \"/input/data.txt\" volumeMounts: - mountPath: /input name: input volumes: - name: input downwardAPI: items: - path: \"data.txt\" fieldRef: fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index'] No newline at end of file"} {"_id":"q-en-website-9d2e86857ff8114e6104dd0b92cae81ab9db0d27e0853a956ef46e2146d24020","text":" --- layout: blog title: \"Kueue 介绍\" date: 2022-10-04 slug: introducing-kueue --- **作者:** Abdullah Gharaibeh(谷歌),Aldo Culquicondor(谷歌) 无论是在本地还是在云端,集群都面临着资源使用、配额和成本管理方面的实际限制。 无论自动扩缩容能力如何,集群的容量都是有限的。 因此,用户需要一种简单的方法来公平有效地共享资源。 在本文中,我们介绍了 [Kueue](https://github.com/kubernetes-sigs/kueue/tree/main/docs#readme), 这是一个开源作业队列控制器,旨在将批处理作业作为一个单元进行管理。 Kueue 将 Pod 级编排留给 Kubernetes 现有的稳定组件。 Kueue 原生支持 Kubernetes [Job](/zh-cn/docs/concepts/workloads/controllers/job/) API, 并提供用于集成其他定制 API 以进行批处理作业的钩子。 ## 为什么是 Kueue? 作业队列是在本地和云环境中大规模运行批处理工作负载的关键功能。 作业队列的主要目标是管理对多个租户共享的有限资源池的访问。 作业排队决定了哪些作业应该等待,哪些可以立即启动,以及它们可以使用哪些资源。 一些最需要的作业队列要求包括: - 用配额和预算来控制谁可以使用什么以及达到什么限制。 这不仅在具有静态资源(如本地)的集群中需要,而且在云环境中也需要控制稀缺资源的支出或用量。 - 租户之间公平共享资源。 为了最大限度地利用可用资源,应允许活动租户公平共享那些分配给非活动租户的未使用配额。 - 根据可用性,在不同资源类型之间灵活放置作业。 这在具有异构资源的云环境中很重要,例如不同的架构(GPU 或 CPU 模型)和不同的供应模式(即用与按需)。 - 支持可按需配置资源的自动扩缩容环境。 普通的 Kubernetes 不能满足上述要求。 在正常情况下,一旦创建了 Job,Job 控制器会立即创建 Pod,并且 kube-scheduler 会不断尝试将 Pod 分配给节点。 大规模使用时,这种情况可能会使控制平面死机。 目前也没有好的办法在 Job 层面控制哪些 Job 应该先获得哪些资源,也没有办法标明顺序或公平共享。 当前的 ResourceQuota 模型不太适合这些需求,因为配额是在资源创建时强制执行的,并且没有请求排队。 ResourceQuotas 的目的是提供一种内置的可靠性机制,其中包含管理员所需的策略,以防止集群发生故障转移。 在 Kubernetes 生态系统中,Job 调度有多种解决方案。但是,我们发现这些替代方案存在以下一个或多个问题: - 它们取代了 Kubernetes 的现有稳定组件,例如 kube-scheduler 或 Job 控制器。 这不仅从操作的角度看是有问题的,而且重复的 Job API 也会导致生态系统的碎片化并降低可移植性。 - 它们没有集成自动扩缩容,或者 - 它们缺乏对资源灵活性的支持。 ## Kueue 的工作原理 {#overview} 借助 Kueue,我们决定采用不同的方法在 Kubernetes 上进行 Job 排队,该方法基于以下方面: - 不复制已建立的 Kubernetes 组件提供的用于 Pod 调度、自动扩缩容和 Job 生命周期管理的现有功能。 - 将缺少的关键特性添加到现有组件中。例如,我们投资了 Job API 以涵盖更多用例,像 [IndexedJob](/blog/2021/04/19/introducing-indexed-jobs), 并[修复了与 Pod 跟踪相关的长期存在的问题](/zh-cn/docs/concepts/workloads/controllers/job/#job-tracking-with-finalizers)。 虽然离特性落地还有很长一段路,但我们相信这是可持续的长期解决方案。 - 确保与具有弹性和异构性的计算资源云环境兼容。 为了使这种方法可行,Kueue 需要旋钮来影响那些已建立组件的行为,以便它可以有效地管理何时何地启动一个 Job。 我们以两个特性的方式将这些旋钮添加到 Job API: - [Suspend 字段](/zh-cn/docs/concepts/workloads/controllers/job/#suspending-a-job), 它允许在 Job 启动或停止时,Kueue 向 Job 控制器发出信号。 - [可变调度指令](/zh-cn/docs/concepts/workloads/controllers/job/#mutable-scheduling-directives), 允许在启动 Job 之前更新 Job 的 `.spec.template.spec.nodeSelector`。 这样,Kueue 可以控制 Pod 放置,同时仍将 Pod 到节点的实际调度委托给 kube-scheduler。 请注意,任何自定义的 Job API 都可以由 Kueue 管理,只要该 API 提供上述两种能力。 ### 资源模型 Kueue 定义了新的 API 来解决本文开头提到的需求。三个主要的 API 是: - ResourceFlavor:一个集群范围的 API,用于定义可供消费的资源模板,如 GPU 模型。 ResourceFlavor 的核心是一组标签,这些标签反映了提供这些资源的节点上的标签。 - ClusterQueue: 一种集群范围的 API,通过为一个或多个 ResourceFlavor 设置配额来定义资源池。 - LocalQueue: 用于分组和管理单租户 Jobs 的命名空间 API。 在最简单的形式中,LocalQueue 是指向集群队列的指针,租户(建模为命名空间)可以使用它来启动他们的 Jobs。 有关更多详细信息,请查看 [API 概念文档](https://sigs.k8s.io/kueue/docs/concepts)。 虽然这三个 API 看起来无法抗拒,但 Kueue 的大部分操作都以 ClusterQueue 为中心; ResourceFlavor 和 LocalQueue API 主要是组织包装器。 ### 用例样例 想象一下在云上的 Kubernetes 集群上运行批处理工作负载的以下设置: - 你在集群中安装了 [cluster-autoscaler](https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler) 以自动调整集群的大小。 - 有两种类型的自动缩放节点组,它们的供应策略不同:即用和按需。 分别对应标签:`instance-type=spot` 或者 `instance-type=ondemand`。 此外,并非所有作业都可以容忍在即用节点上运行,节点可以用 `spot=true:NoSchedule` 污染。 - 为了在成本和资源可用性之间取得平衡,假设你希望 Jobs 使用最多 1000 个核心按需节点,最多 2000 个核心即用节点。 作为批处理系统的管理员,你定义了两个 ResourceFlavor,它们代表两种类型的节点: ```yaml --- apiVersion: kueue.x-k8s.io/v1alpha2 kind: ResourceFlavor metadata: name: ondemand labels: instance-type: ondemand --- apiVersion: kueue.x-k8s.io/v1alpha2 kind: ResourceFlavor metadata: name: spot labels: instance-type: spot taints: - effect: NoSchedule key: spot value: \"true\" ``` 然后通过创建 ClusterQueue 来定义配额,如下所示: ```yaml apiVersion: kueue.x-k8s.io/v1alpha2 kind: ClusterQueue metadata: name: research-pool spec: namespaceSelector: {} resources: - name: \"cpu\" flavors: - name: ondemand quota: min: 1000 - name: spot quota: min: 2000 ``` 注意 ClusterQueue 资源中的模板顺序很重要:Kueue 将尝试根据该顺序为 Job 分配可用配额,除非这些 Job 与特定模板有明确的关联。 对于每个命名空间,定义一个指向上述 ClusterQueue 的 LocalQueue: ```yaml apiVersion: kueue.x-k8s.io/v1alpha2 kind: LocalQueue metadata: name: training namespace: team-ml spec: clusterQueue: research-pool ``` 管理员创建一次上述配置。批处理用户可以通过在他们的命名空间中列出 LocalQueues 来找到他们被允许提交的队列。 该命令类似于:`kubectl get -n my-namespace localqueues` 要提交作业,需要创建一个 Job 并设置 `kueue.x-k8s.io/queue-name` 注解,如下所示: ```yaml apiVersion: batch/v1 kind: Job metadata: generateName: sample-job- annotations: kueue.x-k8s.io/queue-name: training spec: parallelism: 3 completions: 3 template: spec: tolerations: - key: spot operator: \"Exists\" effect: \"NoSchedule\" containers: - name: example-batch-workload image: registry.example/batch/calculate-pi:3.14 args: [\"30s\"] resources: requests: cpu: 1 restartPolicy: Never ``` Kueue 在创建 Job 后立即进行干预以暂停 Job。 一旦 Job 位于 ClusterQueue 的头部,Kueue 就会通过检查 Job 请求的资源是否符合可用配额来评估它是否可以启动。 在上面的例子中,Job 容忍了 Spot 资源。如果之前承认的 Job 消耗了所有现有的按需配额, 但不是所有 Spot 配额,则 Kueue 承认使用 Spot 配额的 Job。Kueue 通过向 Job 对象发出单个更新来做到这一点: - 更改 `.spec.suspend` 标志位为 false - 将 `instance-type: spot` 添加到 Job 的 `.spec.template.spec.nodeSelector` 中, 以便在 Job 控制器创建 Pod 时,这些 Pod 只能调度到 Spot 节点上。 最后,如果有可用的空节点与节点选择器条件匹配,那么 kube-scheduler 将直接调度 Pod。 如果不是,那么 kube-scheduler 将 pod 初始化标记为不可调度,这将触发 cluster-autoscaler 配置新节点。 ## 未来工作以及参与方式 上面的示例提供了 Kueue 的一些功能简介,包括支持配额、资源灵活性以及与集群自动缩放器的集成。 Kueue 还支持公平共享、Job 优先级和不同的排队策略。 查看 [Kueue 文档](https://github.com/kubernetes-sigs/kueue/tree/main/docs)以了解这些特性以及如何使用 Kueue 的更多信息。 我们计划将许多特性添加到 Kueue 中,例如分层配额、预算和对动态大小 Job 的支持。 在不久的将来,我们将专注于增加对 Job 抢占的支持。 最新的 [Kueue 版本](https://github.com/kubernetes-sigs/kueue/releases)在 Github 上可用; 如果你在 Kubernetes 上运行批处理工作负载(需要 v1.22 或更高版本),可以尝试一下。 这个项目还处于早期阶段,我们正在搜集大大小小各个方面的反馈,请不要犹豫,快来联系我们吧! 无论是修复或报告错误,还是帮助添加新特性或编写文档,我们欢迎一切形式的贡献者。 你可以通过我们的[仓库](http://sigs.k8s.io/kueue)、[邮件列表](https://groups.google.com/a/kubernetes.io/g/wg-batch)或者 [Slack](https://kubernetes.slack.com/messages/wg-batch) 与我们联系。 最后是很重要的一点,感谢所有促使这个项目成为可能的[贡献者们](https://github.com/kubernetes-sigs/kueue/graphs/contributors)! "} {"_id":"q-en-website-9ddb684e33e6deb96047ed154b8e42b13bbb92264cc0f1585e2cf74ec987dad2","text":"## コンテナイメージ [コンテナイメージ](/docs/concepts/containers/images/)はすぐに実行可能なソフトウェアパッケージで、アプリケーションの実行に必要なものをすべて含んています。コードと必要なランタイム、アプリケーションとシステムのライブラリ、そして必須な設定項目のデフォルト値を含みます。 設計上、コンテナは不変で、既に実行中のコンテナのコードを変更することはできません。コンテナ化されたアプリケーションがあり変更したい場合は、変更を含んだ新しいコンテナをビルドし、コンテナを再作成して、更新されたイメージから起動する必要があります。 設計上、コンテナは不変で、既に実行中のコンテナのコードを変更することはできません。コンテナ化されたアプリケーションがあり変更したい場合は、変更を含んだ新しいイメージをビルドし、コンテナを再作成して、更新されたイメージから起動する必要があります。 ## コンテナランタイム"} {"_id":"q-en-website-9ea3515a7ca8d51e47974e1b02b6cbd060318cb2443aec2e8b6f44713dc65ad1","text":"kind: Ingress metadata: name: example-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: /$1 spec: ingressClassName: nginx rules:"} {"_id":"q-en-website-9eb7384720a978b3c3c84c04b61adbb274fca4b3ccbb2a6ffea1174f7c5be291","text":" --- title: Add-ons - (Complementos) id: addons date: 2023-07-20 full_link: /es/docs/concepts/cluster-administration/addons/ short_description: > Son recursos que amplían la funcionalidad de Kubernetes. aka: tags: - tool --- Son recursos que amplían la funcionalidad de Kubernetes. [Instalar complementos](/es/docs/concepts/cluster-administration/addons/) explica más sobre el uso de complementos con tu clúster y lista algunos complementos populares. "} {"_id":"q-en-website-9ec074be5f52ea3421ba8ce78bc94278fc1f9c4de34b94cac7d40a5016015f60","text":" Namespaces are easy to create and use but it’s also easy to deploy code inadvertently into the wrong namespace. Good DevOps hygiene suggests documenting and automating processes where possible and this will help. The other way to avoid using the wrong namespace is to set a [kubectl context](/docs/user-guide/kubectl/kubectl_config_set-context/).  Namespaces are easy to create and use but it’s also easy to deploy code inadvertently into the wrong namespace. Good DevOps hygiene suggests documenting and automating processes where possible and this will help. The other way to avoid using the wrong namespace is to set a [kubectl context](/docs/reference/generated/kubectl/kubectl-commands#-em-set-context-em-).  "} {"_id":"q-en-website-9ec4c8ea13c079d0de7e614ae4032de0e7f8c5b20237cebf760cb63a8400df0f","text":" apiVersion: v1 kind: Pod metadata: name: dapi-test-pod spec: containers: - name: test-container image: k8s.gcr.io/busybox command: [ \"/bin/sh\", \"-c\", \"ls /etc/config/\" ] volumeMounts: - name: config-volume mountPath: /etc/config volumes: - name: config-volume configMap: # コンテナに追加するファイルを含むConfigMapの名前を提供する name: special-config restartPolicy: Never "} {"_id":"q-en-website-a28500645a802890cfe604d84670960ad8ebe06fa74f4fc9d0498d836ccbbe2e","text":"* agents on a node (e.g. system daemons, kubelet) can communicate with all pods on that node Note: For those platforms that support `Pods` running in the host network (e.g. Linux), when pods are attached to the host network of a node they can still communicate with all pods on all nodes without NAT. {{< note >}} For those platforms that support `Pods` running in the host network (such as Linux), when pods are attached to the host network of a node they can still communicate with all pods on all nodes without NAT. {{< /note >}} This model is not only less complex overall, but it is principally compatible with the desire for Kubernetes to enable low-friction porting of apps from VMs"} {"_id":"q-en-website-a29441e4d6b4b0d0cd01ed1139e3154061bee82e67b2265637a79ee3e8d60030","text":" ### 卷快照 如果 etcd 运行在支持备份的存储卷(如 Amazon Elastic Block 存储)上,则可以通过获取存储卷的快照来备份 etcd 数据。 ### 使用 etcdctl 选项的快照 我们还可以使用 etcdctl 提供的各种选项来拍摄快照。例如: ```shell ETCDCTL_API=3 etcdctl -h ``` 列出 etcdctl 可用的各种选项。例如,你可以通过指定端点,证书等来拍摄快照,如下所示: ```shell ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 --cacert= --cert= --key= snapshot save ``` 可以从 etcd Pod 的描述中获得 `trusted-ca-file`, `cert-file` 和 `key-file` 。 ## 扩展 etcd 集群 通过交换性能,扩展 etcd 集群可以提高可用性。缩放不会提高集群性能和能力。一般情况下不要扩大或缩小 etcd 集群的集合。不要为 etcd 集群配置任何自动缩放组。强烈建议始终在任何官方支持的规模上运行生产 Kubernetes 集群时使用静态的五成员 etcd 集群。 通过交换性能,扩展 etcd 集群可以提高可用性。缩放不会提高集群性能和能力。 一般情况下不要扩大或缩小 etcd 集群的集合。不要为 etcd 集群配置任何自动缩放组。 强烈建议始终在任何官方支持的规模上运行生产 Kubernetes 集群时使用静态的五成员 etcd 集群。 合理的扩展是在需要更高可靠性的情况下,将三成员集群升级为五成员集群。请参阅 [etcd 重新配置文档](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/runtime-configuration.md#remove-a-member)以了解如何将成员添加到现有集群中的信息。 合理的扩展是在需要更高可靠性的情况下,将三成员集群升级为五成员集群。 请参阅 [etcd 重新配置文档](https://etcd.io/docs/current/op-guide/runtime-configuration/#remove-a-member) 以了解如何将成员添加到现有集群中的信息。 ## 恢复 etcd 集群 etcd 支持从 [major.minor](http://semver.org/) 或其他不同 patch 版本的 etcd 进程中获取的快照进行恢复。还原操作用于恢复失败的集群的数据。 etcd 支持从 [major.minor](http://semver.org/) 或其他不同 patch 版本的 etcd 进程中获取的快照进行恢复。 还原操作用于恢复失败的集群的数据。 在启动还原操作之前,必须有一个快照文件。它可以是来自以前备份操作的快照文件,也可以是来自剩余[数据目录](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/configuration.md#--data-dir)的快照文件。 有关从快照文件还原集群的详细信息和示例,请参阅 [etcd 灾难恢复文档](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/recovery.md#restoring-a-cluster)。 在启动还原操作之前,必须有一个快照文件。它可以是来自以前备份操作的快照文件, 也可以是来自剩余[数据目录]( https://etcd.io/docs/current/op-guide/configuration/#--data-dir)的快照文件。 例如: ```shell ETCDCTL_API=3 etcdctl --endpoints 10.2.0.9:2379 snapshot restore snapshotdb ``` 有关从快照文件还原集群的详细信息和示例,请参阅 [etcd 灾难恢复文档](https://etcd.io/docs/current/op-guide/recovery/#restoring-a-cluster)。 如果还原的集群的访问 URL 与前一个集群不同,则必须相应地重新配置 Kubernetes API 服务器。 在本例中,使用参数 `--etcd-servers=$NEW_ETCD_CLUSTER` 而不是参数 `--etcd-servers=$OLD_ETCD_CLUSTER` 重新启动 Kubernetes API 服务器。"} {"_id":"q-en-website-a2d13b3d3435fea8745fa7c21f3e84a5b2b315fc2f6f1b3bfd234c5ab51e69d9","text":"If this is a documentation issue, please re-open this issue. ``` ### Squashing As an approver, when you review pull requests (PRs), there are various cases where you might do the following: - Advise the contributor to squash their commits. - Squash the commits for the contributor. - Advise the contributor not to squash yet. - Prevent squashing. **Advising contributors to squash**: A new contributor might not know that they should squash commits in their pull requests (PRs). If this is the case, advise them to do so, provide links to useful information, and offer to arrange help if they need it. Some useful links: - [Opening pull requests and squashing your commits](/docs/contribute/new-content/open-a-pr#squashing-commits) for documentation contributors. - [GitHub Workflow](https://www.k8s.dev/docs/guide/github-workflow/), including diagrams, for developers. **Squashing commits for contributors**: If a contributor might have difficulty squashing commits or there is time pressure to merge a PR, you can perform the squash for them: - The kubernetes/website repo is [configured to allow squashing for pull request merges](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/configuring-commit-squashing-for-pull-requests). Simply select the *Squash commits* button. - In the PR, if the contributor enables maintainers to manage the PR, you can squash their commits and update their fork with the result. Before you squash, advise them to save and push their latest changes to the PR. After you squash, advise them to pull the squashed commit to their local clone. - You can get GitHub to squash the commits by using a label so that Tide / GitHub performs the squash or by clicking the *Squash commits* button when you merge the PR. **Advise contributors to avoid squashing** - If one commit does something broken or unwise, and the last commit reverts this error, don't squash the commits. Even though the \"Files changed\" tab in the PR on GitHub and the Netlify preview will both look OK, merging this PR might create rebase or merge conflicts for other folks. Intervene as you see fit to avoid that risk to other contributors. **Never squash** - If you're launching a localization or releasing the docs for a new version, you are merging in a branch that's not from a user's fork, _never squash the commits_. Not squashing is essential because you must maintain the commit history for those files. "} {"_id":"q-en-website-a3c7b0ec363f8449eecce67e7ddd53b26170e1234136c4f4b0843179066d05de","text":"## Formato do _secret_ dos tokens de inicialização Cada token válido possui um _secret_ no namespace `kube-system`. Você pode encontrar a documentação completa [aqui](https://github.com/kubernetes/community/blob/{{< param \"githubbranch\" >}}/contributors/design-proposals/cluster-lifecycle/bootstrap-discovery.md). encontrar a documentação completa [aqui](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/cluster-lifecycle/bootstrap-discovery.md). Um _secret_ de token se parece com o exemplo abaixo:"} {"_id":"q-en-website-a51f952f95a6156b4ed3bf01bfc46025ba2418195439761d33d6766e07ca2634","text":"Arguments to consider: - If following the HTTPS security approach: - `--api-servers=https://$MASTER_IP` - `--kubeconfig=/var/lib/kubelet/kubeconfig` - Otherwise, if taking the firewall-based security approach - `--api-servers=http://$MASTER_IP` - `--config=/etc/kubernetes/manifests` - `--cluster-dns=` to the address of the DNS server you will setup (see [Starting Cluster Services](#starting-cluster-services).) - `--cluster-domain=` to the dns domain prefix to use for cluster DNS addresses."} {"_id":"q-en-website-a5788e12bbb2808d05cea6d80a90008328d1d27ae8f239af2c06d318c001e5f5","text":"This tutorial assumes that you have already set up `minikube`. See [minikube start](https://minikube.sigs.k8s.io/docs/start/) for installation instructions. See __Step 1__ in [minikube start](https://minikube.sigs.k8s.io/docs/start/) for installation instructions. {{< note >}} Only execute the instructions in __Step 1, Installation__. The rest is covered on this page. {{< /note >}} You also need to install `kubectl`. See [Install tools](/docs/tasks/tools/#kubectl) for installation instructions."} {"_id":"q-en-website-a7c6625f4e803f217a118e2b73cad57e01284ee6f66f2cac3c47be270df4685d","text":"* 确保不发生资源不足。 集群的性能和稳定性对网络和磁盘 IO 非常敏感。任何资源匮乏都会导致心跳超时,从而导致集群的不稳定。不稳定的情况表明没有选出任何主节点。在这种情况下,集群不能对其当前状态进行任何更改,这意味着不能调度新的 pod。 集群的性能和稳定性对网络和磁盘 I/O 非常敏感。任何资源匮乏都会导致心跳超时, 从而导致集群的不稳定。不稳定的情况表明没有选出任何主节点。 在这种情况下,集群不能对其当前状态进行任何更改,这意味着不能调度新的 pod。 * 保持稳定的 etcd 集群对 Kubernetes 集群的稳定性至关重要。因此,请在专用机器或隔离环境上运行 etcd 集群,以满足[所需资源需求](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/hardware.md#hardware-recommendations)。 * 保持 etcd 集群的稳定对 Kubernetes 集群的稳定性至关重要。 因此,请在专用机器或隔离环境上运行 etcd 集群,以满足 [所需资源需求](https://etcd.io/docs/current/op-guide/hardware/)。 * 在生产中运行的 etcd 的最低推荐版本是 `3.2.10+`。 詳細については、[CRI](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-node/container-runtime-interface.md)のAPIと仕様をご覧ください。 "} {"_id":"q-en-website-aac87edd6631ec18acac851bb2b796f56cf62c158325ddb8c484eb8d5dfc74b6","text":"dalam bentuk _file-file_ `./username.txt` dan `./password.txt`. ```shell # Buatlah file yang selanjutnya akan digunakan pada contoh-contoh selanjutnya # Buatlah berkas yang selanjutnya akan digunakan pada contoh-contoh selanjutnya echo -n 'admin' > ./username.txt echo -n '1f2d1e2e67df' > ./password.txt ```"} {"_id":"q-en-website-acd9cc77d7e57a625b5cee82b6a8eaaaa4ca28be488c6185b87b874343c54776","text":" --- layout: blog title: \"免费的 Katacoda Kubernetes 教程即将关闭\" date: 2023-02-14 slug: kubernetes-katacoda-tutorials-stop-from-2023-03-31 evergreen: true --- **作者**:Natali Vlatko,Kubernetes SIG Docs 联合主席 **译者**:Michael Yao (DaoCloud) [Katacoda](https://katacoda.com/kubernetes) 是 O’Reilly 开设的热门学习平台, 帮助人们学习 Java、Docker、Kubernetes、Python、Go、C++ 和其他更多内容, 这个学习平台于 [2022 年 6 月停止对公众开放](https://www.oreilly.com/online-learning/leveraging-katacoda-technology.html)。 但是,从 Kubernetes 网站为相关项目用户和贡献者关联的 Kubernetes 专门教程在那次变更后仍然可用并处于活跃状态。 遗憾的是,接下来情况将发生变化,Katacoda 上有关学习 Kubernetes 的教程将在 2023 年 3 月 31 日之后彻底关闭。 Kubernetes 项目感谢 O'Reilly Media 多年来通过 Katacoda 学习平台对 Kubernetes 社区的支持。 你可以在 O'Reilly 自有的网站上阅读 [the decision to shutter katacoda.com](https://www.oreilly.com/online-learning/leveraging-katacoda-technology.html) 有关的更多信息。此次变更之后,我们将专注于移除指向 Katacoda 各种教程的链接。 我们通过 [Issue #33936](https://github.com/kubernetes/website/issues/33936) 和 [GitHub 讨论](https://github.com/kubernetes/website/discussions/38878)跟踪此主题相关的常规问题。 我们也有兴趣调研其他哪些学习平台可能对 Kubernetes 社区有益,尝试将 Katacoda 链接替换为具有类似用户体验的平台或服务。 然而,这项调研需要时间,因此我们正在积极寻觅志愿者来协助完成这项工作。 如果找到替代的平台,需要得到 Kubernetes 领导层的支持,特别是 SIG Contributor Experience、SIG Docs 和 Kubernetes Steering Committee。 Katacoda 的关闭会影响 25 个英文教程页面、对应的多语言页面以及 Katacoda Scenario仓库: [github.com/katacoda-scenarios/kubernetes-bootcamp-scenarios](https://github.com/katacoda-scenarios/kubernetes-bootcamp-scenarios)。 我们建议你立即更新指向 Katacoda 学习平台的所有链接、指南或文档,以反映这一变化。 虽然我们还没有找到替代这个学习平台的解决方案,但 Kubernetes 网站本身就包含了大量有用的文档可助你继续学习和成长。 你可以在 https://k8s.io/docs/tutorials/ 找到所有可用的 Kubernetes 文档教程。 如果你对 Katacoda 关闭或后续从 Kubernetes 教程页面移除相关链接有任何疑问, 请在 [general issue tracking the shutdown](https://github.com/kubernetes/website/issues/33936) 上发表评论,或加入 Kubernetes Slack 的 #sig-docs 频道。 "} {"_id":"q-en-website-ad0a16495027dbecda941c750d47938025a35a48181bb7f95ea3a5f926a7e971","text":"* 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). No newline at end of file * Read the API reference for [object metadata](/docs/reference/kubernetes-api/common-definitions/object-meta/#System). "} {"_id":"q-en-website-ad6c6c2872b47c3314f6f5d4e531f64237764e1a28961639daa8196e1e7f3783","text":"``` ```shell kubectl get pods -l run=cattle kubectl get pods -l app=cattle ``` ``` NAME READY STATUS RESTARTS AGE"} {"_id":"q-en-website-ae55f3423bdb1462202967161eedf2af4d769275b72232b45cc706a23e52bdf5","text":"The exact versions for below mapping table are for docker cli v1.40 and crictl v1.19.0. Please note that the list is not exhaustive. For example, it doesn't include experimental commands of docker cli. {{< note >}} Warn: the output format of CRICTL is similar to Docker CLI, despite some missing columns for some CLI. Make sure to check output for the specific command if your script output parsing. {{< /note >}} ### Retrieve Debugging Information"} {"_id":"q-en-website-aef9218f55e1f01656427cf0467b290107701d72d936bd50e70e083d0bfc4518","text":"### Default deny all ingress traffic You can create a \"default\" isolation policy for a namespace by creating a NetworkPolicy that selects all pods but does not allow any ingress traffic to those pods. You can create a \"default\" ingress isolation policy for a namespace by creating a NetworkPolicy that selects all pods but does not allow any ingress traffic to those pods. {{< codenew file=\"service/networking/network-policy-default-deny-ingress.yaml\" >}} This ensures that even pods that aren't selected by any other NetworkPolicy will still be isolated. This policy does not change the default egress isolation behavior. This ensures that even pods that aren't selected by any other NetworkPolicy will still be isolated for ingress. This policy does not affect isolation for egress from any pod. ### Default allow all ingress traffic ### Allow all ingress traffic If you want to allow all traffic to all pods in a namespace (even if policies are added that cause some pods to be treated as \"isolated\"), you can create a policy that explicitly allows all traffic in that namespace. If you want to allow all incoming connections to all pods in a namespace, you can create a policy that explicitly allows that. {{< codenew file=\"service/networking/network-policy-allow-all-ingress.yaml\" >}} With this policy in place, no additional policy or policies can cause any incoming connection to those pods to be denied. This policy has no effect on isolation for egress from any pod. ### Default deny all egress traffic You can create a \"default\" egress isolation policy for a namespace by creating a NetworkPolicy that selects all pods but does not allow any egress traffic from those pods."} {"_id":"q-en-website-af05112643ac0ef5f58c9637a747806f19e0ae1a34b9095ce738c0b09235b95b","text":" --- title: CRI-O id: cri-o date: 2019-05-14 full_link: https://cri-o.io/#what-is-cri-o short_description: > Kubernetesに特化した軽量コンテナランタイム aka: tags: - tool --- Kubernetes CRIと一緒にOCIコンテナランタイムを使うためのツールです。 CRI-OはOpen Container Initiative (OCI) [runtime spec](https://www.github.com/opencontainers/runtime-spec)と互換性がある{{< glossary_tooltip text=\"コンテナ\" term_id=\"container\" >}}ランタイムを使用できるようにするための{{< glossary_tooltip term_id=\"cri\" >}}の実装の1つです。 CRI-Oのデプロイによって、Kubernetesは任意のOCI準拠のランタイムを、{{< glossary_tooltip text=\"Pod\" term_id=\"pod\" >}}を実行するためのコンテナランタイムとして利用することと、リモートレジストリからOCIコンテナイメージを取得することができるようになります。 "} {"_id":"q-en-website-b07cafa3ee2d776c1575239ca7616756a94346821679bf9277b3e0ab2cc825f4","text":"### Dead link issues Depending on where the dead link is reported, different actions are required to resolve the issue. Dead links in the API and Kubectl docs are automation issues and should be assigned a P1 until the problem can be fully understood. All other dead links are issues that need to be manually fixed and can be assigned a P3. ### Support requests or code bug reports Some issues that are opened for docs are actually issues with the underlying code, or requests for assistance when something (such as a tutorial) didn't work. Since these issues aren't related to documentation requests or problems, it is appropriate to respond directing the requester to potential support avenues, and if relevant, where an appropriate issue can be filed if the problem is a bug report. - example support request response ``` Thank you for this report, This sounds more like a request for support and less like an issue specifically for docs. I encourage you to bring your question to the `#kubernetes-users` channel in [Kubernetes slack](http://slack.k8s.io/). You can also search resources like [Stack Overflow](http://stackoverflow.com/questions/tagged/kubernetes) for answers to similar questions. You can also open issues for Kubernetes functionality in https://github.com/kubernetes/kubernetes. If this is a documentation issue, please re-open this issue. ``` - example code bug report response ``` Thank you for this report, This sounds more like an issue with the code than an issue with the documentation. Please open an issue at https://github.com/kubernetes/kubernetes/issues. If this is a documentation issue, please re-open this issue. ``` {% endcapture %}"} {"_id":"q-en-website-b11935756d0f21174a5bfcad5dac09f60714f08d1371eda4a2631ecadd62866b","text":" --- title: Hello Minikube content_template: templates/tutorial weight: 5 menu: main: title: \"Cominciamo!\" weight: 10 post: >

Sei pronto a cominciare con Kubernetes? Crea un Kubernetes cluster ed esegui un'appliczione di esempio.

card: name: tutorials weight: 10 --- {{% capture overview %}} Questo tutorial mostra come eseguire una semplice applicazione in Kubernetes utilizzando [Minikube](/docs/setup/learning-environment/minikube) e Katacoda. Katacoda permette di operare su un'installazione di Kubernetes dal tuo browser. {{< note >}} Come alternativa, è possibile eseguire questo tutorial [installando minikube](/docs/tasks/tools/install-minikube/) localmente. {{< /note >}} {{% /capture %}} {{% capture objectives %}} * Rilasciare una semplice applicazione su Minikube. * Eseguire l'applicazione. * Visualizzare i log dell'applicazione. {{% /capture %}} {{% capture prerequisites %}} Questo tutorial fornisce una container image che utilizza NGINX per risponde a tutte le richieste con un echo che visualizza i dati della richiesta stessa. {{% /capture %}} {{% capture lessoncontent %}} ## Crea un Minikube cluster 1. Click **Launch Terminal** {{< kat-button >}} {{< note >}}Se hai installato Minikube localmente, esegui `minikube start`.{{< /note >}} 2. Apri la console di Kubernetes nel browser: ```shell minikube dashboard ``` 3. Katacoda environment only: In alto alla finestra del terminale, fai click segno più, e a seguire click su **Select port to view on Host 1**. 4. Katacoda environment only: Inserisci `30000`, a seguire click su **Display Port**. ## Crea un Deployment Un Kubernetes [*Pod*](/docs/concepts/workloads/pods/pod/) è un gruppo di uno o più Containers, che sono uniti tra loro dal punto di vista amministrativo e che condividono lo stesso network. Il Pod in questo tutorial ha un solo Container. Un Kubernetes [*Deployment*](/docs/concepts/workloads/controllers/deployment/) monitora lo stato del Pod ed eventualmente provvedere a farlo ripartire nel caso questo termini. L'uso dei Deployments è la modalità raccomandata per gestire la creazione e lo scaling dei Pods. 1. Usa il comando `kubectl create` per creare un Deployment che gestisce un singolo Pod. Il Pod eseguirà un Container basato sulla Docker image specificata. ```shell kubectl create deployment hello-node --image=k8s.gcr.io/echoserver:1.4 ``` 2. Visualizza il Deployment: ```shell kubectl get deployments ``` L'output del comando è simile a: ``` NAME READY UP-TO-DATE AVAILABLE AGE hello-node 1/1 1 1 1m ``` 3. Visualizza il Pod creato dal Deployment: ```shell kubectl get pods ``` L'output del comando è simile a: ``` NAME READY STATUS RESTARTS AGE hello-node-5f76cf6ccf-br9b5 1/1 Running 0 1m ``` 4. Visualizza gli eventi del cluster Kubernetes: ```shell kubectl get events ``` 5. Visualizza la configurazione di `kubectl`: ```shell kubectl config view ``` {{< note >}}Per maggiori informazioni sui comandi di `kubectl`, vedi [kubectl overview](/docs/user-guide/kubectl-overview/).{{< /note >}} ## Crea un Service Con le impostazioni di default, un Pod è accessibile solamente dagli indirizzi IP interni al Kubernetes cluster. Per far si che il Container `hello-node` sia accessibile dall'esterno del Kubernetes virtual network, è necessario esporre il Pod utilizzando un Kubernetes [*Service*](/docs/concepts/services-networking/service/). 1. Esponi il Pod su internet untilizzando il comando `kubectl expose`: ```shell kubectl expose deployment hello-node --type=LoadBalancer --port=8080 ``` Il flag `--type=LoadBalancer` indica la volontà di esporre il Service all'esterno del Kubernetes cluster. 2. Visualizza il Servizio appena creato: ```shell kubectl get services ``` L'output del comando è simile a: ``` NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE hello-node LoadBalancer 10.108.144.78 8080:30369/TCP 21s kubernetes ClusterIP 10.96.0.1 443/TCP 23m ``` Nei cloud providers che supportano i servizi di tipo load balancers, viene fornito un indirizzo IP pubblico per permettere l'acesso al Service. Su Minikube, il service type `LoadBalancer` rende il Service accessibile attraverso il comando `minikube service`. 3. Esegui il comando: ```shell minikube service hello-node ``` 4. Katacoda environment only: Fai click segno più, e a seguire click su **Select port to view on Host 1**. 5. Katacoda environment only: Fai attenzione al numero di 5 cifre visualizzato a fianco di `8080` nell'output del comando. Questo port number è generato casualmente e può essere diverso nel tuo caso. Inserisci il tuo port number nella textbox, e a seguire fai click su Display Port. Nell'esempio precedente, avresti scritto `30369`. Questo apre un finestra nel browser dove l'applicazione visuallizza l'echo delle richieste ricevute. ## Attiva gli addons Minikube include un set {{< glossary_tooltip text=\"addons\" term_id=\"addons\" >}} che possono essere attivati, disattivati o eseguti nel ambiente Kubernetes locale. 1. Elenca gli addons disponibili: ```shell minikube addons list ``` L'output del comando è simile a: ``` addon-manager: enabled dashboard: enabled default-storageclass: enabled efk: disabled freshpod: disabled gvisor: disabled helm-tiller: disabled ingress: disabled ingress-dns: disabled logviewer: disabled metrics-server: disabled nvidia-driver-installer: disabled nvidia-gpu-device-plugin: disabled registry: disabled registry-creds: disabled storage-provisioner: enabled storage-provisioner-gluster: disabled ``` 2. Attiva un addon, per esempio, `metrics-server`: ```shell minikube addons enable metrics-server ``` L'output del comando è simile a: ``` metrics-server was successfully enabled ``` 3. Visualizza i Pods ed i Service creati in precedenza: ```shell kubectl get pod,svc -n kube-system ``` L'output del comando è simile a: ``` NAME READY STATUS RESTARTS AGE pod/coredns-5644d7b6d9-mh9ll 1/1 Running 0 34m pod/coredns-5644d7b6d9-pqd2t 1/1 Running 0 34m pod/metrics-server-67fb648c5 1/1 Running 0 26s pod/etcd-minikube 1/1 Running 0 34m pod/influxdb-grafana-b29w8 2/2 Running 0 26s pod/kube-addon-manager-minikube 1/1 Running 0 34m pod/kube-apiserver-minikube 1/1 Running 0 34m pod/kube-controller-manager-minikube 1/1 Running 0 34m pod/kube-proxy-rnlps 1/1 Running 0 34m pod/kube-scheduler-minikube 1/1 Running 0 34m pod/storage-provisioner 1/1 Running 0 34m NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/metrics-server ClusterIP 10.96.241.45 80/TCP 26s service/kube-dns ClusterIP 10.96.0.10 53/UDP,53/TCP 34m service/monitoring-grafana NodePort 10.99.24.54 80:30002/TCP 26s service/monitoring-influxdb ClusterIP 10.111.169.94 8083/TCP,8086/TCP 26s ``` 4. Disabilita `metrics-server`: ```shell minikube addons disable metrics-server ``` L'output del comando è simile a: ``` metrics-server was successfully disabled ``` ## Clean up Adesso puoi procedere a fare clean up delle risorse che hai creato nel tuo cluster: ```shell kubectl delete service hello-node kubectl delete deployment hello-node ``` Eventualmente, puoi stoppare la Minikube virtual machine (VM): ```shell minikube stop ``` Eventualmente, puoi cancellare la Minikube VM: ```shell minikube delete ``` {{% /capture %}} {{% capture whatsnext %}} * Approfondisci la tua conoscenza dei [Deployments](/docs/concepts/workloads/controllers/deployment/). * Approfondisci la tua conoscenza di [Rilasciare applicazioni](/docs/tasks/run-application/run-stateless-application-deployment/). * Approfondisci la tua conoscenza dei [Services](/docs/concepts/services-networking/service/). {{% /capture %}} "} {"_id":"q-en-website-b143ce6d392da22a5fce48d2ffda09be4f7186166f18e5852f00bf06abc7af61","text":" apiVersion: batch/v1 kind: Job metadata: name: 'indexed-job' spec: completions: 5 parallelism: 3 completionMode: Indexed template: spec: restartPolicy: Never initContainers: - name: 'input' image: 'docker.io/library/bash' command: - \"bash\" - \"-c\" - | items=(foo bar baz qux xyz) echo ${items[$JOB_COMPLETION_INDEX]} > /input/data.txt volumeMounts: - mountPath: /input name: input containers: - name: 'worker' image: 'docker.io/library/busybox' command: - \"rev\" - \"/input/data.txt\" volumeMounts: - mountPath: /input name: input volumes: - name: input emptyDir: {} "} {"_id":"q-en-website-b1ff40d596806422812db70a8a3b363c0d90a7a30d68053e4392db33a7a3e784","text":"For more information about `kubeadm init` arguments, see the [kubeadm reference guide](/docs/reference/setup-tools/kubeadm/kubeadm/). For a complete list of configuration options, see the [configuration file documentation](/docs/reference/setup-tools/kubeadm/kubeadm-init/#config-file). To configure `kubeadm init` with a configuration file see [Using kubeadm init with a configuration file](/docs/reference/setup-tools/kubeadm/kubeadm-init/#config-file). To customize control plane components, including optional IPv6 assignment to liveness probe for control plane components and etcd server, provide extra arguments to each component as documented in [custom arguments](/docs/setup/production-environment/tools/kubeadm/control-plane-flags/)."} {"_id":"q-en-website-b21fd92949d47ffc35d12de5b58770c712c114e4d61da4d08c5a60fcb3d9ed75","text":" --- title: 在 Linux 系统中安装并设置 kubectl content_type: task weight: 10 card: name: tasks weight: 20 title: 在 Linux 系统中安装 kubectl --- ## {{% heading \"prerequisites\" %}} kubectl 版本和集群版本之间的差异必须在一个小版本号内。 例如:v1.2 版本的客户端只能与 v1.1、v1.2 和 v1.3 版本的集群一起工作。 用最新版的 kubectl 有助于避免不可预见的问题。 ## 在 Linux 系统中安装 kubectl {#install-kubectl-on-linux} 在 Linux 系统中安装 kubectl 有如下几种方法: - [{{% heading \"prerequisites\" %}}](#{{% heading \"prerequisites\" %}}) - [在 Linux 系统中安装 kubectl](#install-kubectl-on-linux) - [用 curl 在 Linux 系统中安装 kubectl](#install-kubectl-binary-with-curl-on-linux) - [用原生包管理工具安装](#install-using-native-package-management) - [用其他包管理工具安装](#install-using-other-package-management) - [作为谷歌云 SDK 的一部分,在 Linux 中安装](#install-on-linux-as-part-of-the-google-cloud-sdk) - [验证 kubectl 配置](#verify-kubectl-configration) - [可选的 kubectl 配置](#optional-kubectl-configurations) - [启用 shell 自动补全功能](#enable-shell-autocompletion) - [{{% heading \"whatsnext\" %}}](#{{% heading \"whatsnext\" %}}) ### 用 curl 在 Linux 系统中安装 kubectl {#install-kubectl-binary-with-curl-on-linux} 1. 用以下命令下载最新发行版: ```bash curl -LO \"https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl\" ``` {{< note >}} 如需下载某个指定的版本,请用指定版本号替换该命令的这一部分: `$(curl -L -s https://dl.k8s.io/release/stable.txt)`。 例如,要在 Linux 中下载 {{< param \"fullversion\" >}} 版本,请输入: ```bash curl -LO https://dl.k8s.io/release/{{< param \"fullversion\" >}}/bin/linux/amd64/kubectl ``` {{< /note >}} 1. 验证该可执行文件(可选步骤) 下载 kubectl 校验和文件: ```bash curl -LO \"https://dl.k8s.io/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256\" ``` 基于校验和文件,验证 kubectl 的可执行文件: ```bash echo \"$( 验证通过时,输出为: ```console kubectl: OK ``` 验证失败时,`sha256` 将以非零值退出,并打印如下输出: ```bash kubectl: FAILED sha256sum: WARNING: 1 computed checksum did NOT match ``` {{< note >}} 下载的 kubectl 与校验和文件版本必须相同。 {{< /note >}} 1. 安装 kubectl ```bash sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl ``` {{< note >}} 即使你没有目标系统的 root 权限,仍然可以将 kubectl 安装到目录 `~/.local/bin` 中: ```bash mkdir -p ~/.local/bin/kubectl mv ./kubectl ~/.local/bin/kubectl # and then add ~/.local/bin/kubectl to $PATH ``` {{< /note >}} 1. 执行测试,以保障你安装的版本是最新的: ```bash kubectl version --client ``` ### 用原生包管理工具安装 {#install-using-native-package-management} {{< tabs name=\"kubectl_install\" >}} {{< tab name=\"Ubuntu、Debian 或 HypriotOS\" codelang=\"bash\" >}} sudo apt-get update && sudo apt-get install -y apt-transport-https gnupg2 curl curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - echo \"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 install -y kubectl {{< /tab >}} {{< tab name=\"CentOS、RHEL 或 Fedora\" codelang=\"bash\" >}}cat < /etc/yum.repos.d/kubernetes.repo [kubernetes] name=Kubernetes baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64 enabled=1 gpgcheck=1 repo_gpgcheck=1 gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg EOF yum install -y kubectl {{< /tab >}} {{< /tabs >}} ### 用其他包管理工具安装 {#install-using-other-package-management} {{< tabs name=\"other_kubectl_install\" >}} {{% tab name=\"Snap\" %}} 如果你使用的 Ubuntu 或其他 Linux 发行版,内建支持 [snap](https://snapcraft.io/docs/core/install) 包管理工具, 则可用 [snap](https://snapcraft.io/) 命令安装 kubectl。 ```shell snap install kubectl --classic kubectl version --client ``` {{% /tab %}} {{% tab name=\"Homebrew\" %}} 如果你使用 Linux 系统,并且装了 [Homebrew](https://docs.brew.sh/Homebrew-on-Linux) 包管理工具, 则可以使用这种方式[安装](https://docs.brew.sh/Homebrew-on-Linux#install) kubectl。 ```shell brew install kubectl kubectl version --client ``` {{% /tab %}} {{< /tabs >}} ### 作为谷歌云 SDK 的一部分,在 Linux 上安装 {#install-on-linux-as-part-of-the-google-cloud-sdk} {{< include \"included/install-kubectl-gcloud.md\" >}} ## 验证 kubectl 配置 {#verify-kubectl-configration} {{< include \"included/verify-kubectl.md\" >}} ## kubectl 的可选配置 {#optional-kubectl-configurations} ### 启用 shell 自动补全功能 {#enable-shell-autocompletion} kubectl 为 Bash 和 Zsh 提供自动补全功能,可以减轻许多输入的负担。 下面是为 Bash 和 Zsh 设置自动补全功能的操作步骤。 {{< tabs name=\"kubectl_autocompletion\" >}} {{< tab name=\"Bash\" include=\"included/optional-kubectl-configs-bash-linux.md\" />}} {{< tab name=\"Zsh\" include=\"included/optional-kubectl-configs-zsh.md\" />}} {{< /tabs >}} ## {{% heading \"whatsnext\" %}} {{< include \"included/kubectl-whats-next.md\" >}} "} {"_id":"q-en-website-b277ef21e2260f88dcfca6769b80b1e54cfc2058dcdbfbf1276affa51fb7ab27","text":"title: Code Contributor id: code-contributor date: 2018-04-12 full_link: /docs/community/devel/ full_link: https://github.com/kubernetes/community/tree/master/contributors/devel short_description: > A person who develops and contributes code to the Kubernetes open source codebase."} {"_id":"q-en-website-b320e13f48873f51013bb03cbc307d686045c93910d9c3496131d3f4040622dd","text":"--> DaemonSet 确保所有符合条件的节点都运行该 Pod 的一个副本。 通常,运行 Pod 的节点由 Kubernetes 调度器选择。 不过,DaemonSet pods 由 DaemonSet 控制器创建和调度。这就带来了以下问题: 不过,DaemonSet Pods 由 DaemonSet 控制器创建和调度。这就带来了以下问题: * Pod 行为的不一致性:正常 Pod 在被创建后等待调度时处于 `Pending` 状态, DaemonSet Pods 创建后不会处于 `Pending` 状态下。这使用户感到困惑。"} {"_id":"q-en-website-b34b4398468a24aaba59d8538a59e0cca93d6949773e1622e2a0cad2b2f35959","text":" 基于 YAML 文件创建 DaemonSet: 基于 YAML 文件创建 DaemonSet: ``` kubectl apply -f https://k8s.io/examples/controllers/daemonset.yaml"} {"_id":"q-en-website-b37ecd689010504b75b506897770f881f6d022622c93936e8716ddad0925f2ce","text":"other = \"报告问题\" [layouts_docs_partials_feedback_thanks] other = \"感谢反馈。如果您有一个关于如何使用 Kubernetes 的特定的、需要答案的问题,可以访问\" other = \"感谢反馈。如果你有一个关于如何使用 Kubernetes 的具体问题需要答案,可以访问\" [layouts_docs_search_fetching] other = \"检索结果中..\""} {"_id":"q-en-website-b59ba0f5c3514b77769d7484e813a6875f966d238a28b274adabe1ae8e001d3f","text":"

The Master is responsible for managing the cluster. The master coordinates all activities in your cluster, such as scheduling applications, maintaining applications' desired state, scaling applications, and rolling out new updates.

A node is a VM or a physical computer that serves as a worker machine in a Kubernetes cluster. Each node has a Kubelet, which is an agent for managing the node and communicating with the Kubernetes master. The node should also have tools for handling container operations, such as containerd or Docker. A Kubernetes cluster that handles production traffic should have a minimum of three nodes.

The Control Plane is responsible for managing the cluster. The Control Plane coordinates all activities in your cluster, such as scheduling applications, maintaining applications' desired state, scaling applications, and rolling out new updates.

A node is a VM or a physical computer that serves as a worker machine in a Kubernetes cluster. Each node has a Kubelet, which is an agent for managing the node and communicating with the Kubernetes control plane. The node should also have tools for handling container operations, such as containerd or Docker. A Kubernetes cluster that handles production traffic should have a minimum of three nodes.

Masters manage the cluster and the nodes that are used to host the running applications.

Control Planes manage the cluster and the nodes that are used to host the running applications.

When you deploy applications on Kubernetes, you tell the master to start the application containers. The master schedules the containers to run on the cluster's nodes. The nodes communicate with the master using the Kubernetes API, which the master exposes. End users can also use the Kubernetes API directly to interact with the cluster.

When you deploy applications on Kubernetes, you tell the control plane to start the application containers. The control plane schedules the containers to run on the cluster's nodes. The nodes communicate with the control plane using the Kubernetes API, which the control plane exposes. End users can also use the Kubernetes API directly to interact with the cluster.

A Kubernetes cluster can be deployed on either physical or virtual machines. To get started with Kubernetes development, you can use Minikube. Minikube is a lightweight Kubernetes implementation that creates a VM on your local machine and deploys a simple cluster containing only one node. Minikube is available for Linux, macOS, and Windows systems. The Minikube CLI provides basic bootstrapping operations for working with your cluster, including start, stop, status, and delete. For this tutorial, however, you'll use a provided online terminal with Minikube pre-installed.

A Kubernetes cluster can be deployed on either physical or virtual machines. To get started with Kubernetes development, you can use Minikube. Minikube is a lightweight Kubernetes implementation that creates a VM on your local machine and deploys a simple cluster containing only one node. Minikube is available for Linux, macOS, and Windows systems. The Minikube CLI provides basic bootstrapping operations for working with your cluster, including start, stop, status, and delete. For this tutorial, however, you'll use a provided online terminal with Minikube pre-installed.

Now that you know what Kubernetes is, let's go to the online tutorial and start our first cluster!

"} {"_id":"q-en-website-b85afb64325e3f0116ea277a82f1658d7ef76d2756b7ca08068f208e404d350a","text":"- protocol: TCP port: 80 targetPort: 9376 nodePort: 30061 clusterIP: 10.0.171.239 loadBalancerIP: 78.11.24.19 type: LoadBalancer"} {"_id":"q-en-website-b9628a3bd1342af729fc0d415e4e77aa188dfc1b94be571ff6d2e0b68dec0154","text":"You can renew your certificates manually at any time with the `kubeadm certs renew` command. This command performs the renewal using CA (or front-proxy-CA) certificate and key stored in `/etc/kubernetes/pki`. This command performs the renewal using CA (or front-proxy-CA) certificate and key stored in `/etc/kubernetes/pki`. After running the command you should restart the control plane Pods. This is required since dynamic certificate reload is currently not supported for all components and certificates. [Static Pods](/docs/tasks/configure-pod-containerstatic-pod/) are managed by the local kubelet and not by the API Server, thus kubectl cannot be used to delete and restart them. To restart a static Pod you can temporarily remove its manifest file from `/etc/kubernetes/manifests/` and wait for 20 seconds (see the `fileCheckFrequency` value in [KubeletConfiguration struct](/docs/ reference/config-api/kubelet-config.v1beta1/). The kubelet will terminate the Pod if it's no longer in the manifest directory. You can then move the file back and after another `fileCheckFrequency` period, the kubelet will recreate the Pod and the certificate renewal for the component can complete. {{< warning >}} If you are running an HA cluster, this command needs to be executed on all the control-plane nodes."} {"_id":"q-en-website-b9b307977bd0b1ffb2682e2a24e9d3423404301c1b6b260d9ce702b6cd63be3e","text":"- `token-secret`: A random 16 character string as the actual token secret. Required. - `description`: A human-readable string that describes what the token is used for. Optional. - `expiration`: An absolute UTC time using RFC3339 specifying when the token - `expiration`: An absolute UTC time using [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339) specifying when the token should be expired. Optional. - `usage-bootstrap-`: A boolean flag indicating additional usage for the bootstrap token."} {"_id":"q-en-website-b9d15ed0a224da430e4aca4f64497af6b94cae361237ffc753c041af8e65893a","text":"> __Important!__ A volume can only be mounted using one access mode at a time, even if it supports many. For example, a GCEPersistentDisk can be mounted as ReadWriteOnce by a single node or ReadOnlyMany by many nodes, but not at the same time. | Volume Plugin | ReadWriteOnce| ReadOnlyMany| ReadWriteMany| | :--- | :---: | :---: | :---: | | AWSElasticBlockStore | x | - | - | | AzureFile | x | x | x | | CephFS | x | x | x | | Cinder | x | - | - | | FC | x | x | - | | FlexVolume | x | x | - | | GCEPersistentDisk | x | x | - | | Glusterfs | x | x | x | | HostPath | x | - | - | | iSCSI | x | x | - | | NFS | x | x | x | | RDB | x | x | - | | VsphereVolume | x | - | - | ### Recycling Policy Current recycling policies are:"} {"_id":"q-en-website-ba2fc98989c9410b49475f59606c7ea23c932263f04b01e6199323ea548a5535","text":"## {{% heading \"prerequisites\" %}} You must use a kubectl version that is within one minor version difference of your cluster. For example, a v1.2 client should work with v1.1, v1.2, and v1.3 master. You must use a kubectl version that is within one minor version difference of your cluster. For example, a v{{< skew latestVersion >}} client can communicate with v{{< skew prevMinorVersion >}}, v{{< skew latestVersion >}}, and v{{< skew nextMinorVersion >}} control planes. Using the latest version of kubectl helps avoid unforeseen issues. ## Install kubectl on Linux"} {"_id":"q-en-website-bd0d58f185f822043c2497ea4c599cf45097cc099de36017bb4c464ef7e7abd7","text":" --- title: 名前空間レベルでのPodセキュリティの標準の適用 content_type: チュートリアル weight: 20 --- {{% alert title=\"Note\" %}} このチュートリアルは、新しいクラスターにのみ適用されます。 {{% /alert %}} Podセキュリティアドミッション(PSA)は、[ベータへ進み](/blog/2021/12/09/pod-security-admission-beta/)、v1.23以降でデフォルトで有効になっています。 Podセキュリティアドミッションは、Podが作成される際に、[Podセキュリティの標準](/ja/docs/concepts/security/pod-security-standards/)の適用の認可を制御するものです。 このチュートリアルでは、一度に1つの名前空間で`baseline` Podセキュリティ標準を強制します。 Podセキュリティの標準を複数の名前空間に一度にクラスターレベルで適用することもできます。やり方については[クラスターレベルでのPodセキュリティの標準の適用](/docs/tutorials/security/cluster-level-pss/)を参照してください。 ## {{% heading \"prerequisites\" %}} ワークステーションに以下をインストールしてください: - [KinD](https://kind.sigs.k8s.io/docs/user/quick-start/#installation) - [kubectl](/ja/docs/tasks/tools/) ## クラスターの作成 1. 以下のように`KinD`クラスターを作成します。 ```shell kind create cluster --name psa-ns-level ``` 出力は次のようになります: ``` Creating cluster \"psa-ns-level\" ... ✓ Ensuring node image (kindest/node:v{{< skew currentPatchVersion >}}) 🖼 ✓ Preparing nodes 📦 ✓ Writing configuration 📜 ✓ Starting control-plane 🕹️ ✓ Installing CNI 🔌 ✓ Installing StorageClass 💾 Set kubectl context to \"kind-psa-ns-level\" You can now use your cluster with: kubectl cluster-info --context kind-psa-ns-level Not sure what to do next? 😅 Check out https://kind.sigs.k8s.io/docs/user/quick-start/ ``` 1. kubectl のコンテキストを新しいクラスターにセットします: ```shell kubectl cluster-info --context kind-psa-ns-level ``` 出力は次のようになります: ``` Kubernetes control plane is running at https://127.0.0.1:50996 CoreDNS is running at https://127.0.0.1:50996/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'. ``` ## 名前空間の作成 `example`と呼ぶ新しい名前空間を作成します: ```shell kubectl create ns example ``` 出力は次のようになります: ``` namespace/example created ``` ## 名前空間へのPodセキュリティの標準チェックの有効化 1. ビルトインのPod Security Admissionでサポートされているラベルを使って、この名前空間のPodセキュリティの標準を有効にします。 このステップでは、_baseline_ Podセキュリティの標準の最新バージョンに合わないPodについて警告するチェックを設定します。 ```shell kubectl label --overwrite ns example pod-security.kubernetes.io/warn=baseline pod-security.kubernetes.io/warn-version=latest ``` 2. ラベルを使って、任意の名前空間に対して複数のPodセキュリティの標準チェックを設定できます。 以下のコマンドは、`baseline` Podセキュリティの標準を`enforce`(強制)としますが、`restricted` Podセキュリティの標準には最新バージョンに準じて`warn`(警告)および`audit`(監査)とします(デフォルト値)。 ```shell kubectl label --overwrite ns example pod-security.kubernetes.io/enforce=baseline pod-security.kubernetes.io/enforce-version=latest pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/warn-version=latest pod-security.kubernetes.io/audit=restricted pod-security.kubernetes.io/audit-version=latest ``` ## Podセキュリティの標準の強制の実証 1. `example`名前空間内に`baseline` Podを作成します: ```shell kubectl apply -n example -f https://k8s.io/examples/security/example-baseline-pod.yaml ``` Podは正常に起動しますが、出力には警告が含まれています。例えば: ``` Warning: would violate PodSecurity \"restricted:latest\": allowPrivilegeEscalation != false (container \"nginx\" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container \"nginx\" must set securityContext.capabilities.drop=[\"ALL\"]), runAsNonRoot != true (pod or container \"nginx\" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container \"nginx\" must set securityContext.seccompProfile.type to \"RuntimeDefault\" or \"Localhost\") pod/nginx created ``` 1. `default`名前空間内に`baseline` Podを作成します: ```shell kubectl apply -n default -f https://k8s.io/examples/security/example-baseline-pod.yaml ``` 出力は次のようになります: ``` pod/nginx created ``` `example`名前空間にだけ、Podセキュリティの標準のenforceと警告の設定が適用されました。 `default`名前空間内では、警告なしに同じPodを作成できました。 ## 後片付け では、上記で作成したクラスターを、以下のコマンドを実行して削除します: ```shell kind delete cluster --name psa-ns-level ``` ## {{% heading \"whatsnext\" %}} - 前出の一連の手順を一度に全て行うために[シェルスクリプト](/examples/security/kind-with-namespace-level-baseline-pod-security.sh)を実行します。 1. KinDクラスターを作成します。 2. 新しい名前空間を作成します。 3. `enforce`モードでは`baseline` Podセキュリティの標準を適用し、`warn`および`audit`モードでは`restricted` Podセキュリティの標準を適用します。 4. これらのPodセキュリティの標準を適用した新しいPodを作成します。 - [Podのセキュリティアドミッション](/ja/docs/concepts/security/pod-security-admission/) - [Podセキュリティの標準](/ja/docs/concepts/security/pod-security-standards/) - [クラスターレベルでのPodセキュリティの標準の適用](/ja/docs/tutorials/security/cluster-level-pss/) "} {"_id":"q-en-website-bd2d75a6133d16aa5bec18d47e00f77e2e8da1b0041daf2bc373a76d89895e47","text":"title: Picking the Right Solution --- Kubernetes can run on various platforms: from your laptop, to VMs on a cloud provider, to rack of Kubernetes can run on various platforms: from your laptop, to VMs on a cloud provider, to a rack of bare metal servers. The effort required to set up a cluster varies from running a single command to crafting your own customized cluster. Use this guide to choose a solution that fits your needs."} {"_id":"q-en-website-bd6602592ecec530901c3b2e0cbdad52693ec2508d2853e7cde497ae3d08d4a4","text":"} body.cid-community #videos { width: 100vw; width: 100%; max-width: initial; padding: 0.5em 5vw 5% 5vw; /* fallback in case calc() fails */ background-color: #eeeeee;"} {"_id":"q-en-website-bd90c49c87069ceed86fa2dd2800d44790a239ccd07498847f28a77dad4abca6","text":"

For your first Deployment, you'll use a Node.js application packaged in a Docker container. (If you didn't already try creating a Node.js application and deploying it using a container, you can do that first by following the instructions from the Hello Minikube tutorial). For your first Deployment, you'll use a hello-node application packaged in a Docker container that uses NGINX to echo back all the requests. (If you didn't already try creating a hello-node application and deploying it using a container, you can do that first by following the instructions from the Hello Minikube tutorial).

Now that you know what Deployments are, let's go to the online tutorial and deploy our first app!

"} {"_id":"q-en-website-bdaaa114f28ebe42c86be3a594e61738a82200b3c8f16cfa8e2d1e3ffe258de3","text":"{{% capture whatsnext %}} - [Learn about how to use `kubectl` for application introspection and debugging.](/docs/tasks/debug-application-cluster/debug-application-introspection/) - [Configuration Best Practices and Tips](/docs/concepts/configuration/overview/) - Learn about [how to use `kubectl` for application introspection and debugging](/docs/tasks/debug-application-cluster/debug-application-introspection/). - See [Configuration Best Practices and Tips](/docs/concepts/configuration/overview/). {{% /capture %}}"} {"_id":"q-en-website-bdb4e23e1852a402612c81650e179c958922462c60413a46564ce8d5f79a7b82","text":"{{% /tab %}} {{% tab name=\"URL copy and paste\" %}} If you don't want minikube to open a web browser for you, run the dashboard command with the If you don't want minikube to open a web browser for you, run the `dashboard` subcommand with the `--url` flag. `minikube` outputs a URL that you can open in the browser you prefer. Open a **new** terminal, and run:"} {"_id":"q-en-website-c13a4e120cb07800f9ceced0ca25bb2ceda919416167cacad9e2a6697f832e2b","text":"Histogram Admission controller latency histogram in seconds, identified by name and broken out for each operation and API resource and type (validate or admit).
name
operation
rejected
type
None apiserver_admission_step_admission_duration_seconds STABLE Histogram Admission sub-step latency histogram in seconds, broken out for each operation and API resource and step type (validate or admit).
operation
rejected
type
None apiserver_admission_webhook_admission_duration_seconds STABLE Histogram Admission webhook latency histogram in seconds, identified by name and broken out for each operation and API resource and type (validate or admit).
name
operation
rejected
type
None apiserver_current_inflight_requests STABLE Gauge Maximal number of currently used inflight request limit of this apiserver per request kind in last second.
request_kind
None apiserver_longrunning_requests STABLE Gauge Gauge of all active long-running apiserver requests broken out by verb, group, version, resource, scope and component. Not all requests are tracked this way.
component
group
resource
scope
subresource
verb
version
None apiserver_request_duration_seconds STABLE Histogram Response latency distribution in seconds for each verb, dry run value, group, version, resource, subresource, scope and component.
component
dry_run
group
resource
scope
subresource
verb
version
None apiserver_request_total STABLE Counter Counter of apiserver requests broken out for each verb, dry run value, group, version, resource, scope, component, and HTTP response code.
code
component
dry_run
group
resource
scope
subresource
verb
version
None apiserver_requested_deprecated_apis STABLE Gauge Gauge of deprecated APIs that have been requested, broken out by API group, version, resource, subresource, and removed_release.
group
removed_release
resource
subresource
version
None apiserver_response_sizes STABLE Histogram Response size distribution in bytes for each group, version, verb, resource, subresource, scope and component.
component
group
resource
scope
subresource
verb
version
None apiserver_storage_objects STABLE Gauge Number of stored objects at the time of last check split by kind.
resource
cronjob_controller_job_creation_skew_duration_seconds STABLE Histogram Time between when a cronjob is scheduled to be run, and when the corresponding job is created job_controller_job_pods_finished_total STABLE Counter The number of finished Pods that are fully tracked
completion_mode
result
job_controller_job_sync_duration_seconds STABLE Histogram The time it took to sync a job
action
completion_mode
result
job_controller_job_syncs_total STABLE Counter The number of job syncs
action
completion_mode
result
job_controller_jobs_finished_total STABLE Counter The number of finished jobs
completion_mode
reason
result
None node_collector_evictions_total STABLE Counter Number of Node evictions that happened since current instance of NodeController started.
zone
None scheduler_framework_extension_point_duration_seconds STABLE Histogram Latency for running all plugins of a specific extension point.
extension_point
profile
status
None scheduler_pending_pods STABLE Gauge Number of pending pods, by the queue type. 'active' means number of pods in activeQ; 'backoff' means number of pods in backoffQ; 'unschedulable' means number of pods in unschedulablePods that the scheduler attempted to schedule and failed; 'gated' is the number of unschedulable pods that the scheduler never attempted to schedule because they are gated. Number of pending pods, by the queue type. 'active' means number of pods in activeQ; 'backoff' means number of pods in backoffQ; 'unschedulable' means number of pods in unschedulablePods.
queue
None scheduler_pod_scheduling_attempts STABLE Histogram Number of attempts to successfully schedule a pod. None None scheduler_pod_scheduling_duration_seconds STABLE Histogram E2e latency for a pod being scheduled which may include multiple scheduling attempts.
attempts
None scheduler_preemption_attempts_total STABLE Counter Total preemption attempts in the cluster till now None None scheduler_preemption_victims STABLE Histogram Number of selected preemption victims None None scheduler_queue_incoming_pods_total STABLE Counter Number of pods added to scheduling queues by event and queue type.
event
queue
None scheduler_schedule_attempts_total STABLE Counter Number of attempts to schedule pods, by the result. 'unschedulable' means a pod could not be scheduled, while 'error' means an internal scheduler problem.
profile
result
None scheduler_scheduling_attempt_duration_seconds STABLE Histogram Scheduling attempt latency in seconds (scheduling algorithm + binding)
profile
result
None "} {"_id":"q-en-website-c22c649eb4f55c4638b0490f37d2b7d5fcbc4d50f3f6e9282256006cebb24cbb","text":"{{% /capture %}} ## インストールの確認 ハイパーバイザーとMinikube両方のインストール成功を確認するため、以下のコマンドをローカルKubernetesクラスターを起動するために実行してください: {{< note >}} `minikube start`で`--vm-driver`の設定をするため、次の``の部分では、インストールしたハイパーバイザーの名前を小文字で入力してください。`--vm-driver`値のすべてのリストは、[specifying the VM driver documentation](https://kubernetes.io/docs/setup/learning-environment/minikube/#specifying-the-vm-driver)で確認できます。 {{< /note >}} ```shell minikube start --vm-driver= ``` `minikube start`が完了した場合、次のコマンドを実行してクラスターの状態を確認します。 ```shell minikube status ``` クラスターが起動していると、`minikube status`の出力はこのようになります。 ``` host: Running kubelet: Running apiserver: Running kubeconfig: Configured ``` 選択したハイパーバイザーでMinikubeが動作しているか確認した後は、そのままMinikubeを使い続けることもできます。また、クラスターを停止することもできます。クラスターを停止するためには、次を実行してください。 ```shell minikube stop ``` ## ローカル状態のクリーンアップ {#cleanup-local-state} もし以前に Minikubeをインストールしていたら、以下のコマンドを実行します。"} {"_id":"q-en-website-c2e9b39fbd7cb0e261ca6ba95abc746ee2aa4f15f77d3d600f9a893022473581","text":" --- title: Node Affinityを利用してPodをノードに割り当てる min-kubernetes-server-version: v1.10 content_type: task weight: 120 --- このページでは、Node Affinityを利用して、PodをKubernetesクラスター内の特定のノードに割り当てる方法を説明します。 ## {{% heading \"prerequisites\" %}} {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} ## ノードにラベルを追加する 1. クラスター内のノードを一覧表示して、ラベルを確認します。 ```shell kubectl get nodes --show-labels ``` 出力は次のようになります。 ```shell NAME STATUS ROLES AGE VERSION LABELS worker0 Ready 1d v1.13.0 ...,kubernetes.io/hostname=worker0 worker1 Ready 1d v1.13.0 ...,kubernetes.io/hostname=worker1 worker2 Ready 1d v1.13.0 ...,kubernetes.io/hostname=worker2 ``` 1. ノードを選択して、ラベルを追加します。 ```shell kubectl label nodes disktype=ssd ``` ここで、``は選択したノードの名前で置換します。 1. 選択したノードに`disktype=ssd`ラベルがあることを確認します。 ```shell kubectl get nodes --show-labels ``` 出力は次のようになります。 ``` NAME STATUS ROLES AGE VERSION LABELS worker0 Ready 1d v1.13.0 ...,disktype=ssd,kubernetes.io/hostname=worker0 worker1 Ready 1d v1.13.0 ...,kubernetes.io/hostname=worker1 worker2 Ready 1d v1.13.0 ...,kubernetes.io/hostname=worker2 ``` この出力を見ると、`worker0`ノードに`disktype=ssd`というラベルが追加されたことがわかります。 ## required node affinityを使用してPodをスケジューリングする 以下に示すマニフェストには、`requiredDuringSchedulingIgnoredDuringExecution`に`disktype: ssd`というnode affinityを使用したPodが書かれています。このように書くと、Podは`disktype=ssd`というラベルを持つノードにだけスケジューリングされるようになります。 {{< codenew file=\"pods/pod-nginx-required-affinity.yaml\" >}} 1. マニフェストを適用して、選択したノード上にスケジューリングされるPodを作成します。 ```shell kubectl apply -f https://k8s.io/examples/pods/pod-nginx-required-affinity.yaml ``` 1. Podが選択したノード上で実行されていることを確認します。 ```shell kubectl get pods --output=wide ``` 出力は次のようになります。 ``` NAME READY STATUS RESTARTS AGE IP NODE nginx 1/1 Running 0 13s 10.200.0.4 worker0 ``` ## preferred node affinityを使用してPodをスケジューリングする 以下に示すマニフェストには、`preferredDuringSchedulingIgnoredDuringExecution`に`disktype: ssd`というnode affinityを使用したPodが書かれています。このように書くと、Podは`disktype=ssd`というラベルを持つノードに優先的にスケジューリングされるようになります。 {{< codenew file=\"pods/pod-nginx-preferred-affinity.yaml\" >}} 1. マニフェストを適用して、選択したノード上にスケジューリングされるPodを作成します。 ```shell kubectl apply -f https://k8s.io/examples/pods/pod-nginx-preferred-affinity.yaml ``` 1. Podが選択したノード上で実行されていることを確認します。 ```shell kubectl get pods --output=wide ``` 出力は次のようになります。 ``` NAME READY STATUS RESTARTS AGE IP NODE nginx 1/1 Running 0 13s 10.200.0.4 worker0 ``` ## {{% heading \"whatsnext\" %}} [Node Affinity](/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity)についてさらに学ぶ。 "} {"_id":"q-en-website-c3d6f6124d8688cf8f4c9675543ea7899639d47d52ba970e0625e1393c75ecdb","text":" --- layout: blog title: \"聚焦 SIG Usability\" date: 2021-07-15 slug: sig-usability-spotlight-2021 --- **作者:** Kunal Kushwaha、Civo ## 介绍 你是否有兴趣了解 [SIG Usability](https://github.com/kubernetes/community/tree/master/sig-usability) 做什么? 你是否想知道如何参与?那你来对地方了。 SIG Usability 旨在让 Kubernetes 更易于触达新的伙伴,其主要活动是针对社区实施用户调研。 在本博客中,我们总结了与 Gaby Moreno 的对话, 他向我们介绍了成为 SIG 成员的各个方面,并分享了一些关于其他人如何参与的见解。 Gaby 是 SIG Usability 的联合负责人。 她在 IBM 担任产品设计师, 喜欢研究 Kubernetes、OpenShift、Terraform 和 Cloud Foundry 等开放式混合云技术的用户体验。 ## 我们谈话的摘要 ### 问:你能告诉我们一些关于 SIG Usability 的事情吗? 答:简单而言,启动 SIG Usability 的原因是那时 Kubernetes 没有专门的用户体验团队。 SIG Usability 的关注领域集中在为 Kubernetes 项目最终客户提供的易用性上。 主要活动是社区的用户调研,包括对 Kubernetes 用户宣讲。 所涉及的包括用户体验和可访问性等方面。 SIG 的目标是确保 Kubernetes 项目能够最大限度地被具有各类不同基础和能力的人使用, 例如引入文档的国际化并确保其开放性。 ### 问:为什么新的和现有的贡献者应该考虑加入 SIG Usability? 答:新的贡献者可以在很多领域着手。例如: - 用户研究项目可以让人们帮助了解最终用户体验的可用性,包括错误消息、端到端任务等。 - Kubernetes 社区组件的可访问性指南,包括:文档的国际化、色盲人群的颜色选择、 确保与屏幕阅读器技术的兼容性、核心 UI 组件的用户界面设计等等。 ### 问:如何帮助新的贡献者入门? 答:新的贡献者们刚开始可以旁观参与其中一个用户访谈,浏览用户访谈记录,分析这些记录并设计调查过程。 SIG Usability 也对新的项目想法持开放态度。 如果你有想法,我们将尽我们所能支持它。 我们有定期的 SIG 会议,人们可以现场提问。 这些会议也会录制会议视频,方便那些可能无法参会的人。 与往常一样,你也可以在 Slack 上与我们联系。 ### 问:调查包括什么? 答:简单来说,调查会收集人们如何使用 Kubernetes 的信息, 例如学习部署新系统的趋势、他们收到的错误消息和工作流程。 我们的目标之一是根据需要对反馈进行标准化。 最终目标是分析那些需求没有得到满足的重要用户故事的调查反馈。 ### 问:招募贡献者时你希望他们具备什么特别的技能吗?SIG Usability 的贡献者可能要学习哪些技能? 答:虽然为 SIG Usability 做贡献没有任何先决条件, 但用户研究、定性研究的经验或之前如何进行访谈的经验将是很好的加分项。 定量研究,如调查设计和筛选,也很有帮助,也是我们希望贡献者学习的东西。 ### 问:您在哪些方面获得了积极的反馈,以及 SIG Usability 接下来会发生什么? 答:我们一直有新成员加入并经常参加月度会议,并表现出对成为贡献者和帮助社区的兴趣。 我们也有很多人通过 Slack 与我们联系,表达他们对 SIG 的兴趣。 目前,我们正专注于完成我们[演讲](https://www.youtube.com/watch?v=Byn0N_ZstE0)中提到的调研, 也是我们今年的项目。我们总是很高兴有新的贡献者加入我们。 ### 问:在结束之前,你还有什么想法/资源要分享吗? 答:我们喜欢结识新的贡献者并帮助他们研究不同的 Kubernetes 项目领域。 我们将与其他 SIG 合作,以促进与最终用户的互动,开展调研,并帮助他们将可访问的设计实践整合到他们的开发实践中。 这里有一些资源供你入门: - [GitHub](https://github.com/kubernetes/community/tree/master/sig-usability) - [邮件列表](https://groups.google.com/g/kubernetes-sig-usability) - [Open Community Issues/PRs](https://github.com/kubernetes/community/labels/sig%2Fusability) - [Slack](https://slack.k8s.io/) - [Slack 频道 #sig-usability](https://kubernetes.slack.com/archives/CLC5EF63T) ## 总结 SIG Usability 举办了一个关于调研 Kubernetes 用户体验的 [KubeCon 演讲](https://www.youtube.com/watch?v=Byn0N_ZstE0)。 演讲的重点是用户调研项目的更新,了解谁在使用 Kubernetes、他们试图实现什么、项目如何满足他们的需求、以及我们需要改进项目和客户体验的地方。 欢迎加入 SIG 的更新,了解最新的调研成果、来年的计划以及如何作为贡献者参与上游可用性团队! "} {"_id":"q-en-website-c3e619d0b635e09e1054df80f5abbd874b16965fb487089a3c33fc157b78640a","text":"## {{% heading \"prerequisites\" %}} You must use a kubectl version that is within one minor version difference of your cluster. For example, a v1.2 client should work with v1.1, v1.2, and v1.3 master. You must use a kubectl version that is within one minor version difference of your cluster. For example, a v{{< skew latestVersion >}} client can communicate with v{{< skew prevMinorVersion >}}, v{{< skew latestVersion >}}, and v{{< skew nextMinorVersion >}} control planes. Using the latest version of kubectl helps avoid unforeseen issues. ## Install kubectl on Windows"} {"_id":"q-en-website-c52a2752aa977c2270d68086b1a25d10b0422da61573db78afc83a34f3173bcc","text":"RELEASE=\"$(curl -sSL https://dl.k8s.io/release/stable.txt)\" ARCH=\"amd64\" cd $DOWNLOAD_DIR sudo curl -L --remote-name-all https://storage.googleapis.com/kubernetes-release/release/${RELEASE}/bin/linux/${ARCH}/{kubeadm,kubelet,kubectl} sudo curl -L --remote-name-all https://dl.k8s.io/release/${RELEASE}/bin/linux/${ARCH}/{kubeadm,kubelet,kubectl} sudo chmod +x {kubeadm,kubelet,kubectl} RELEASE_VERSION=\"v0.4.0\""} {"_id":"q-en-website-c70f63b7715a3dd86a77ed60205725b603b27cf12b218ddd4cba180ff60be170","text":" --- title: 分散システムコーディネーターZooKeeperの実行 content_type: tutorial weight: 40 --- このチュートリアルでは、[StatefulSet](/ja/docs/concepts/workloads/controllers/statefulset/)、[PodDisruptionBudgets](/docs/concepts/workloads/pods/disruptions/#pod-disruption-budget)、[Podアンチアフィニティ](/ja/docs/concepts/scheduling-eviction/assign-pod-node/#affinity-and-anti-affinity)を使って、Kubernetes上での[Apache Zookeeper](https://zookeeper.apache.org)の実行をデモンストレーションします。 ## {{% heading \"prerequisites\" %}} このチュートリアルを始める前に、以下のKubernetesの概念について理解しておく必要があります。 - [Pod](/ja/docs/concepts/workloads/pods/) - [クラスターDNS](/ja/docs/concepts/services-networking/dns-pod-service/) - [Headless Service](/ja/docs/concepts/services-networking/service/#headless-service) - [PersistentVolume](/ja/docs/concepts/storage/volumes/) - [PersistentVolume Provisioning](https://github.com/kubernetes/examples/tree/master/staging/persistent-volume-provisioning/) - [StatefulSet](/ja/docs/concepts/workloads/controllers/statefulset/) - [PodDisruptionBudgets](/docs/concepts/workloads/pods/disruptions/#pod-disruption-budget) - [Podアンチアフィニティ](/ja/docs/concepts/scheduling-eviction/assign-pod-node/#affinity-and-anti-affinity) - [kubectl CLI](/docs/reference/kubectl/kubectl/) 少なくとも4つのノードのクラスターが必要で、各ノードは少なくとも2つのCPUと4GiBのメモリが必須です。このチュートリアルでは、クラスターのノードをcordonおよびdrainします。 **つまり、クラスターがそのノードの全てのPodを終了して退去させ、ノードが一時的にスケジュールできなくなる、ということです。** このチュートリアル専用のクラスターを使うか、起こした破壊がほかのテナントに干渉しない確証を得ることをお勧めします。 このチュートリアルでは、クラスターがPersistentVolumeの動的なプロビジョニングが行われるように設定されていることを前提としています。 クラスターがそのように設定されていない場合、チュートリアルを始める前に20GiBのボリュームを3つ、手動でプロビジョニングする必要があります。 ## {{% heading \"objectives\" %}} このチュートリアルを終えると、以下の知識を得られます。 - StatefulSetを使ってZooKeeperアンサンブルをデプロイする方法。 - アンサンブルを一貫して設定する方法。 - ZooKeeperサーバーのデプロイをアンサンブルに広げる方法。 - 計画されたメンテナンス中もサービスが利用可能であることを保証するためにPodDisruptionBudgetsを使う方法。 ### ZooKeeper [Apache ZooKeeper](https://zookeeper.apache.org/doc/current/)は、分散アプリケーションのための、分散型オープンソースコーディネーションサービスです。 ZooKeeperでは、データの読み書き、および更新の監視ができます。 データは階層化されてファイルシステム内に編成され、アンサンブル(ZooKeeperサーバーのセット)内の全てのZooKeeperサーバーに複製されます。 データへの全ての操作はアトミックかつ逐次的に一貫性を持ちます。 ZooKeeperは、アンサンブル内の全てのサーバー間でステートマシンを複製するために[Zab](https://pdfs.semanticscholar.org/b02c/6b00bd5dbdbd951fddb00b906c82fa80f0b3.pdf)合意プロトコルを使ってこれを保証します。 アンサンブルはリーダーを選出するのにZabプロトコルを使い、選出が完了するまでデータを書き出しません。 完了すると、アンサンブルは複製するのにZabを使い、書き込みが承認されてクライアントに可視化されるより前に、全ての書き込みをクォーラムに複製することを保証します。 重み付けされたクォーラムでなければ、クォーラムは現在のリーダーを含むアンサンブルの多数を占めるコンポーネントです。 例えばアンサンブルが3つのサーバーを持つ時、リーダーとそれ以外のもう1つのサーバーを含むコンポーネントが、クォーラムを構成します。 アンサンブルがクォーラムに達しない場合、アンサンブルはデータを書き出せません。 ZooKeeperサーバー群はそれらの全てのステートマシンをメモリに保持し、それぞれの変化をストレージメディア上の永続的なWAL(Write Ahead Log)に書き出します。 サーバーがクラッシュした時には、WALをリプレーすることで以前のステートに回復できます。 WALを際限のない増加から防ぐために、ZooKeeperサーバーは、メモリステートにあるものをストレージメディアに定期的にスナップショットします。 これらのスナップショットはメモリに直接読み込むことができ、スナップショットより前の全てのWALエントリは破棄され得ます。 ## ZooKeeperアンサンブルの作成 以下のマニフェストは[Headless Service](/ja/docs/concepts/services-networking/service/#headless-services)、[Service](/ja/docs/concepts/services-networking/service/)、[PodDisruptionBudget](/docs/concepts/workloads/pods/disruptions/#pod-disruption-budgets)、[StatefulSet](/ja/docs/concepts/workloads/controllers/statefulset/)を含んでいます。 {{< codenew file=\"application/zookeeper/zookeeper.yaml\" >}} ターミナルを開き、マニフェストを作成するために [`kubectl apply`](/docs/reference/generated/kubectl/kubectl-commands/#apply)コマンドを使います。 ```shell kubectl apply -f https://k8s.io/examples/application/zookeeper/zookeeper.yaml ``` これは`zk-hs` Headless Service、`zk-cs` Service、`zk-pdb` PodDisruptionBudget、 `zk` StatefulSetを作成します。 ``` service/zk-hs created service/zk-cs created poddisruptionbudget.policy/zk-pdb created statefulset.apps/zk created ``` StatefulSetのPodを作成するStatefulSetコントローラーを監視するため、[`kubectl get`](/docs/reference/generated/kubectl/kubectl-commands/#get)を使います。 ```shell kubectl get pods -w -l app=zk ``` `zk-2` PodがRunningおよびReadyになったら、`CTRL-C`でkubectlを終了してください。 ``` NAME READY STATUS RESTARTS AGE zk-0 0/1 Pending 0 0s zk-0 0/1 Pending 0 0s zk-0 0/1 ContainerCreating 0 0s zk-0 0/1 Running 0 19s zk-0 1/1 Running 0 40s zk-1 0/1 Pending 0 0s zk-1 0/1 Pending 0 0s zk-1 0/1 ContainerCreating 0 0s zk-1 0/1 Running 0 18s zk-1 1/1 Running 0 40s zk-2 0/1 Pending 0 0s zk-2 0/1 Pending 0 0s zk-2 0/1 ContainerCreating 0 0s zk-2 0/1 Running 0 19s zk-2 1/1 Running 0 40s ``` StatefulSetコントローラーが3つのPodを作成し、各Podは[ZooKeeper](https://archive.apache.org/dist/zookeeper/stable/)サーバー付きのコンテナを持ちます。 ### リーダーの選出のファシリテート {#facilitating-leader-election} 匿名のネットワークにおいてリーダー選出を終了するアルゴリズムがないので、Zabはリーダー選出のための明示的なメンバーシップ設定を要します。 アンサンブルの各サーバーはユニーク識別子を持つ必要があり、全てのサーバーは識別子のグローバルセットを知っている必要があり、各識別子はネットワークアドレスと関連付けられている必要があります。 `zk` StatefulSetのPodのホスト名を取得するために[`kubectl exec`](/docs/reference/generated/kubectl/kubectl-commands/#exec)を使います。 ```shell for i in 0 1 2; do kubectl exec zk-$i -- hostname; done ``` StatefulSetコントローラーは各Podに、その順序インデックスに基づくユニークなホスト名を提供します。 ホスト名は`-<順序インデックス>`という形をとります。 `zk` StatefulSetの`replicas`フィールドが`3`にセットされているので、このセットのコントローラーは、ホスト名にそれぞれ`zk-0`、`zk-1`、`zk-2`が付いた3つのPodを作成します。 ``` zk-0 zk-1 zk-2 ``` ZooKeeperアンサンブルのサーバーは、ユニーク識別子として自然数を使い、それぞれのサーバーの識別子をサーバーのデータディレクトリ内の`myid`というファイルに格納します。 各サーバーの`myid`ファイルの内容を調べるには、以下のコマンドを使います。 ```shell for i in 0 1 2; do echo \"myid zk-$i\";kubectl exec zk-$i -- cat /var/lib/zookeeper/data/myid; done ``` 識別子が自然数で順序インデックスは正の整数なので、順序に1を加算することで識別子を生成できます。 ``` myid zk-0 1 myid zk-1 2 myid zk-2 3 ``` `zk` StatefulSet内の各Podの完全修飾ドメイン名(FQDN)を取得するには、以下のコマンドを使います。 ```shell for i in 0 1 2; do kubectl exec zk-$i -- hostname -f; done ``` `zk-hs` Serviceは、全Podのためのドメイン`zk-hs.default.svc.cluster.local`を作成します。 ``` zk-0.zk-hs.default.svc.cluster.local zk-1.zk-hs.default.svc.cluster.local zk-2.zk-hs.default.svc.cluster.local ``` [Kubernetes DNS](/ja/docs/concepts/services-networking/dns-pod-service/)のAレコードは、FQDNをPodのIPアドレスに解決します。 KubernetesがPodを再スケジュールした場合、AレコードはPodの新しいIPアドレスに更新されますが、Aレコードの名前は変更されません。 ZooKeeperはそのアプリケーション設定を`zoo.cfg`という名前のファイルに格納します。 `zk-0` Pod内の`zoo.cfg`ファイルの内容を見るには、`kubectl exec`を使います。 ```shell kubectl exec zk-0 -- cat /opt/zookeeper/conf/zoo.cfg ``` ファイル末尾にある`server.1`、`server.2`、`server.3`のプロパティの、`1`、`2`、`3`はZooKeeperサーバーの`myid`ファイル内の識別子に対応します。 これらは`zk` StatefulSet内のPodのFQDNにセットされます。 ``` clientPort=2181 dataDir=/var/lib/zookeeper/data dataLogDir=/var/lib/zookeeper/log tickTime=2000 initLimit=10 syncLimit=2000 maxClientCnxns=60 minSessionTimeout= 4000 maxSessionTimeout= 40000 autopurge.snapRetainCount=3 autopurge.purgeInterval=0 server.1=zk-0.zk-hs.default.svc.cluster.local:2888:3888 server.2=zk-1.zk-hs.default.svc.cluster.local:2888:3888 server.3=zk-2.zk-hs.default.svc.cluster.local:2888:3888 ``` ### 合意形成 {#achieving-consensus} 合意(consensus)プロトコルは、各参加者の識別子がユニークであることを要件としています。 Zabプロトコル内で同じユニーク識別子を主張する2つの参加者はないものとします。 これは、システム内のプロセスが、どのプロセスがどのデータをコミットしたかを同意できるようにするために必須です。 2つのPodが同じ順序値で起動されたなら、2つのZooKeeperサーバーはどちらもそれら自身を同じサーバーとして認識してしまうでしょう。 ```shell kubectl get pods -w -l app=zk ``` ``` NAME READY STATUS RESTARTS AGE zk-0 0/1 Pending 0 0s zk-0 0/1 Pending 0 0s zk-0 0/1 ContainerCreating 0 0s zk-0 0/1 Running 0 19s zk-0 1/1 Running 0 40s zk-1 0/1 Pending 0 0s zk-1 0/1 Pending 0 0s zk-1 0/1 ContainerCreating 0 0s zk-1 0/1 Running 0 18s zk-1 1/1 Running 0 40s zk-2 0/1 Pending 0 0s zk-2 0/1 Pending 0 0s zk-2 0/1 ContainerCreating 0 0s zk-2 0/1 Running 0 19s zk-2 1/1 Running 0 40s ``` 各PodのAレコードは、PodがReadyになった時に記入されます。そのため、ZooKeeperサーバー群のFQDNはある1つのエンドポイント、すなわち`myid`ファイルで設定された識別子を主張するユニークなZooKeeperサーバーに解決されます。 ``` zk-0.zk-hs.default.svc.cluster.local zk-1.zk-hs.default.svc.cluster.local zk-2.zk-hs.default.svc.cluster.local ``` これは、ZooKeeperの`zzo.cfg`ファイル内の`servers`プロパティが正しく設定されたアンサンブルを表していることを保証します。 ``` server.1=zk-0.zk-hs.default.svc.cluster.local:2888:3888 server.2=zk-1.zk-hs.default.svc.cluster.local:2888:3888 server.3=zk-2.zk-hs.default.svc.cluster.local:2888:3888 ``` サーバーが値のコミットを試みるためにZabプロトコルを使う時、(リーダー選出が成功していて、少なくともPodのうちの2つがRunningおよびReadyならば)それぞれのサーバーは双方の合意をとって値をコミット、あるいは、(もし双方の状態が合わなければ)それを行うことに失敗します。 あるサーバーが別のサーバーを代行して書き込みを承認する状態は発生しません。 ### アンサンブルの健全性テスト {#sanity-testing-the-ensemble} 最も基本的な健全性テストは、データを1つのZooKeeperサーバーに書き込み、そのデータを別のサーバーで読み取ることです。 以下のコマンドは、`world`をアンサンブル内の`zk-0` Podのパス`/hello`に書き込むのに、`zkCli.sh`スクリプトを実行します。 ```shell kubectl exec zk-0 -- zkCli.sh create /hello world ``` ``` WATCHER:: WatchedEvent state:SyncConnected type:None path:null Created /hello ``` `zk-1` Podからデータを取得するには、以下のコマンドを使います。 ```shell kubectl exec zk-1 -- zkCli.sh get /hello ``` `zk-0`に作成したデータは、アンサンブル内の全てのサーバーで利用できます。 ``` WATCHER:: WatchedEvent state:SyncConnected type:None path:null world cZxid = 0x100000002 ctime = Thu Dec 08 15:13:30 UTC 2016 mZxid = 0x100000002 mtime = Thu Dec 08 15:13:30 UTC 2016 pZxid = 0x100000002 cversion = 0 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 5 numChildren = 0 ``` ### 永続的なストレージの提供 [ZooKeeperの概要](#zookeeper)のセクションで言及したように、 ZooKeeperは全てのエントリを永続的なWALにコミットし、定期的にメモリ状態のスナップショットをストレージメディアに書き出します。 永続性を提供するためにWALを使用するのは、複製されたステートマシンを立てるために合意プロトコルを使うアプリケーションでよくあるテクニックです。 `zk` StatefulSetを削除するために、[`kubectl delete`](/docs/reference/generated/kubectl/kubectl-commands/#delete)コマンドを使います。 ```shell kubectl delete statefulset zk ``` ``` statefulset.apps \"zk\" deleted ``` StatefulSet内のPodの終了を観察します。 ```shell kubectl get pods -w -l app=zk ``` `zk-0`が完全に終了したら、`CTRL-C`でkubectlを終了します。 ``` zk-2 1/1 Terminating 0 9m zk-0 1/1 Terminating 0 11m zk-1 1/1 Terminating 0 10m zk-2 0/1 Terminating 0 9m zk-2 0/1 Terminating 0 9m zk-2 0/1 Terminating 0 9m zk-1 0/1 Terminating 0 10m zk-1 0/1 Terminating 0 10m zk-1 0/1 Terminating 0 10m zk-0 0/1 Terminating 0 11m zk-0 0/1 Terminating 0 11m zk-0 0/1 Terminating 0 11m ``` `zookeeper.yaml`のマニフェストを再適用します。 ```shell kubectl apply -f https://k8s.io/examples/application/zookeeper/zookeeper.yaml ``` これは`zk` StatefulSetオブジェクトを作成しますが、マニフェストのその他のAPIオブジェクトはすでに存在しているので変更されません。 StatefulSetコントローラーがStatefulSetのPodを再作成するのを見てみます。 ```shell kubectl get pods -w -l app=zk ``` `zk-2` PodがRunningおよびReadyになったら、`CTRL-C`でkubectlを終了します。 ``` NAME READY STATUS RESTARTS AGE zk-0 0/1 Pending 0 0s zk-0 0/1 Pending 0 0s zk-0 0/1 ContainerCreating 0 0s zk-0 0/1 Running 0 19s zk-0 1/1 Running 0 40s zk-1 0/1 Pending 0 0s zk-1 0/1 Pending 0 0s zk-1 0/1 ContainerCreating 0 0s zk-1 0/1 Running 0 18s zk-1 1/1 Running 0 40s zk-2 0/1 Pending 0 0s zk-2 0/1 Pending 0 0s zk-2 0/1 ContainerCreating 0 0s zk-2 0/1 Running 0 19s zk-2 1/1 Running 0 40s ``` [健全性テスト](#sanity-testing-the-ensemble)で入力した値を`zk-2` Podから取得するには、以下のコマンドを使います。 ```shell kubectl exec zk-2 zkCli.sh get /hello ``` `zk` StatefulSet内の全てのPodを終了して再作成したにもかかわらず、アンサンブルは元の値をなおも供給します。 ``` WATCHER:: WatchedEvent state:SyncConnected type:None path:null world cZxid = 0x100000002 ctime = Thu Dec 08 15:13:30 UTC 2016 mZxid = 0x100000002 mtime = Thu Dec 08 15:13:30 UTC 2016 pZxid = 0x100000002 cversion = 0 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 5 numChildren = 0 ``` `zk` StatefulSetの`spec`の`volumeClaimTemplates`フィールドは、各PodにプロビジョニングされるPersistentVolumeを指定します。 ```yaml volumeClaimTemplates: - metadata: name: datadir annotations: volume.alpha.kubernetes.io/storage-class: anything spec: accessModes: [ \"ReadWriteOnce\" ] resources: requests: storage: 20Gi ``` `StatefulSet`コントローラーは、`StatefulSet`内の各Podのために`PersistentVolumeClaim`を生成します。 `StatefulSet`の`PersistentVolumeClaims`を取得するために、以下のコマンドを使います。 ```shell kubectl get pvc -l app=zk ``` `StatefulSet`がそのPodを再作成した時、`StatefulSet`はPodのPersistentVolumeを再マウントします。 ``` NAME STATUS VOLUME CAPACITY ACCESSMODES AGE datadir-zk-0 Bound pvc-bed742cd-bcb1-11e6-994f-42010a800002 20Gi RWO 1h datadir-zk-1 Bound pvc-bedd27d2-bcb1-11e6-994f-42010a800002 20Gi RWO 1h datadir-zk-2 Bound pvc-bee0817e-bcb1-11e6-994f-42010a800002 20Gi RWO 1h ``` `StatefulSet`のコンテナ`template`の`volumeMounts`セクションは、ZooKeeperサーバーのデータディレクトリにあるPersistentVolumeをマウントします。 ```yaml volumeMounts: - name: datadir mountPath: /var/lib/zookeeper ``` `zk` `StatefulSet`内のPodが(再)スケジュールされると、ZooKeeperサーバーのデータディレクトリにマウントされた同じ`PersistentVolume`を常に得ます。 Podが再スケジュールされたとしても、全ての書き込みはZooKeeperサーバーのWALおよび全スナップショットに行われ、永続性は残ります。 ## 一貫性のある設定の保証 [リーダーの選出のファシリテート](#facilitating-leader-election)および[合意形成](#achieving-consensus)のセクションで記したように、ZooKeeperのアンサンブル内のサーバー群は、リーダーを選出しクォーラムを形成するための一貫性のある設定を必要とします。 また、プロトコルがネットワーク越しで正しく動作するために、Zabプロトコルの一貫性のある設定も必要です。 この例では、設定を直接マニフェストに埋め込むことで一貫性のある設定を達成します。 `zk` StatefulSetを取得しましょう。 ```shell kubectl get sts zk -o yaml ``` ``` … command: - sh - -c - \"start-zookeeper --servers=3 --data_dir=/var/lib/zookeeper/data --data_log_dir=/var/lib/zookeeper/data/log --conf_dir=/opt/zookeeper/conf --client_port=2181 --election_port=3888 --server_port=2888 --tick_time=2000 --init_limit=10 --sync_limit=5 --heap=512M --max_client_cnxns=60 --snap_retain_count=3 --purge_interval=12 --max_session_timeout=40000 --min_session_timeout=4000 --log_level=INFO\" … ``` このcommandでは、ZooKeeperサーバーを開始するためにコマンドラインパラメータで設定を渡しています。 設定をアンサンブルへ渡すのには環境変数を使うこともできます。 ### ログの設定 `zkGenConfig.sh`スクリプトで生成されたファイルの1つは、ZooKeeperのログを制御します。 ZooKeeperは[Log4j](https://logging.apache.org/log4j/2.x/)を使い、デフォルトではログの設定に基づいて、ログ設定に時間およびサイズベースでのローリングファイルアペンダー(ログのローテーション)を使用します。 `zk` `StatefulSet`内のPodの1つからログ設定を取得するには、以下のコマンドを使います。 ```shell kubectl exec zk-0 cat /usr/etc/zookeeper/log4j.properties ``` 以下のログ設定は、ZooKeeperにログの全てを標準出力ファイルストリームに書き出す処理をさせます。 ``` zookeeper.root.logger=CONSOLE zookeeper.console.threshold=INFO log4j.rootLogger=${zookeeper.root.logger} log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.Threshold=${zookeeper.console.threshold} log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} [myid:%X{myid}] - %-5p [%t:%C{1}@%L] - %m%n ``` これはログコンテナ内のログを安全にとるための、最もシンプルと思われる方法です。 アプリケーションはログを標準出力に書き出し、Kubernetesがログのローテーションを処理してくれます。 Kubernetesは、標準出力と標準エラー出力に書き出されるアプリケーションのログがローカルストレージメディアを使い尽くさないことを保証する、健全維持ポリシーも実装しています。 Podの1つから末尾20行を取得するために、[`kubectl logs`](/docs/reference/generated/kubectl/kubectl-commands/#logs)を使ってみます。 ```shell kubectl logs zk-0 --tail 20 ``` `kubectl logs`を利用するか、Kubernetes Dashboardから、標準出力または標準エラーに書き出されたアプリケーションログを参照できます。 ``` 2016-12-06 19:34:16,236 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@827] - Processing ruok command from /127.0.0.1:52740 2016-12-06 19:34:16,237 [myid:1] - INFO [Thread-1136:NIOServerCnxn@1008] - Closed socket connection for client /127.0.0.1:52740 (no session established for client) 2016-12-06 19:34:26,155 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /127.0.0.1:52749 2016-12-06 19:34:26,155 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@827] - Processing ruok command from /127.0.0.1:52749 2016-12-06 19:34:26,156 [myid:1] - INFO [Thread-1137:NIOServerCnxn@1008] - Closed socket connection for client /127.0.0.1:52749 (no session established for client) 2016-12-06 19:34:26,222 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /127.0.0.1:52750 2016-12-06 19:34:26,222 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@827] - Processing ruok command from /127.0.0.1:52750 2016-12-06 19:34:26,226 [myid:1] - INFO [Thread-1138:NIOServerCnxn@1008] - Closed socket connection for client /127.0.0.1:52750 (no session established for client) 2016-12-06 19:34:36,151 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /127.0.0.1:52760 2016-12-06 19:34:36,152 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@827] - Processing ruok command from /127.0.0.1:52760 2016-12-06 19:34:36,152 [myid:1] - INFO [Thread-1139:NIOServerCnxn@1008] - Closed socket connection for client /127.0.0.1:52760 (no session established for client) 2016-12-06 19:34:36,230 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /127.0.0.1:52761 2016-12-06 19:34:36,231 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@827] - Processing ruok command from /127.0.0.1:52761 2016-12-06 19:34:36,231 [myid:1] - INFO [Thread-1140:NIOServerCnxn@1008] - Closed socket connection for client /127.0.0.1:52761 (no session established for client) 2016-12-06 19:34:46,149 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /127.0.0.1:52767 2016-12-06 19:34:46,149 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@827] - Processing ruok command from /127.0.0.1:52767 2016-12-06 19:34:46,149 [myid:1] - INFO [Thread-1141:NIOServerCnxn@1008] - Closed socket connection for client /127.0.0.1:52767 (no session established for client) 2016-12-06 19:34:46,230 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@192] - Accepted socket connection from /127.0.0.1:52768 2016-12-06 19:34:46,230 [myid:1] - INFO [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@827] - Processing ruok command from /127.0.0.1:52768 2016-12-06 19:34:46,230 [myid:1] - INFO [Thread-1142:NIOServerCnxn@1008] - Closed socket connection for client /127.0.0.1:52768 (no session established for client) ``` Kubernetesは多くのログソリューションを統合しています。 クラスターおよびアプリケーションに最も適合するログソリューションを選べます。 クラスターレベルのロギングとアグリゲーションとして、ログをローテートおよび輸送するための[サイドカーコンテナ](/ja/docs/concepts/cluster-administration/logging#sidecar-container-with-logging-agent)をデプロイすることを検討してください。 ### 非特権ユーザーの設定 コンテナ内で特権ユーザーとしての実行をアプリケーションに許可するベストプラクティスは、議論の的です。 アプリケーションが非特権ユーザーとして動作することを組織で必須としているなら、エントリポイントがそのユーザーとして実行できるユーザーを制御する[セキュリティコンテキスト](/ja/docs/tasks/configure-pod-container/security-context/)を利用できます。 `zk` `StatefulSet`のPod `template`は、`SecurityContext`を含んでいます。 ```yaml securityContext: runAsUser: 1000 fsGroup: 1000 ``` Podのコンテナ内で、UID 1000はzookeeperユーザーに、GID 1000はzookeeperグループにそれぞれ相当します。 `zk-0` PodからのZooKeeperプロセス情報を取得してみましょう。 ```shell kubectl exec zk-0 -- ps -elf ``` `securityContext`オブジェクトの`runAsUser`フィールドが1000にセットされているとおり、ZooKeeperプロセスは、rootとして実行される代わりにzookeeperユーザーとして実行されています。 ``` F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD 4 S zookeep+ 1 0 0 80 0 - 1127 - 20:46 ? 00:00:00 sh -c zkGenConfig.sh && zkServer.sh start-foreground 0 S zookeep+ 27 1 0 80 0 - 1155556 - 20:46 ? 00:00:19 /usr/lib/jvm/java-8-openjdk-amd64/bin/java -Dzookeeper.log.dir=/var/log/zookeeper -Dzookeeper.root.logger=INFO,CONSOLE -cp /usr/bin/../build/classes:/usr/bin/../build/lib/*.jar:/usr/bin/../share/zookeeper/zookeeper-3.4.9.jar:/usr/bin/../share/zookeeper/slf4j-log4j12-1.6.1.jar:/usr/bin/../share/zookeeper/slf4j-api-1.6.1.jar:/usr/bin/../share/zookeeper/netty-3.10.5.Final.jar:/usr/bin/../share/zookeeper/log4j-1.2.16.jar:/usr/bin/../share/zookeeper/jline-0.9.94.jar:/usr/bin/../src/java/lib/*.jar:/usr/bin/../etc/zookeeper: -Xmx2G -Xms2G -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false org.apache.zookeeper.server.quorum.QuorumPeerMain /usr/bin/../etc/zookeeper/zoo.cfg ``` デフォルトでは、PodのPersistentVolumeがZooKeeperサーバーのデータディレクトリにマウントされている時、rootユーザーのみがそこにアクセス可能です。 この設定はZooKeeperのプロセスがそのWALに書き込んだりスナップショットに格納したりするのを妨げることになります。 `zk-0` PodのZooKeeperデータディレクトリのファイルパーミッションを取得するには、以下のコマンドを使います。 ```shell kubectl exec -ti zk-0 -- ls -ld /var/lib/zookeeper/data ``` `securityContext`オブジェクトの`fsGroup`フィールドが1000にセットされているので、PodのPersistentVolumeの所有権はzookeeperグループにセットされ、ZooKeeperのプロセスがそのデータを読み書きできるようになります。 ``` drwxr-sr-x 3 zookeeper zookeeper 4096 Dec 5 20:45 /var/lib/zookeeper/data ``` ## ZooKeeperプロセスの管理 [ZooKeeperドキュメント](https://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_supervision)では、「You will want to have a supervisory process that manages each of your ZooKeeper server processes (JVM).(各ZooKeeperサーバープロセス(JVM)を管理する監督プロセスを持ちたくなります)」と述べています。 分散型システム内で失敗したプロセスを再起動するのにwatchdog(監督プロセス)を使うのは、典型的パターンです。 アプリケーションをKubernetesにデプロイする時には、監督プロセスのような外部ユーティリティを使うよりもむしろ、アプリケーションのwatchdogとしてKubernetesを使うべきです。 ### アンサンブルのアップデート `zk` `StatefulSet`は`RollingUpdate`アップデート戦略を使うように設定されています。 サーバーに割り当てられる`cpus`の数を更新するのに、`kubectl patch`を利用できます。 ```shell kubectl patch sts zk --type='json' -p='[{\"op\": \"replace\", \"path\": \"/spec/template/spec/containers/0/resources/requests/cpu\", \"value\":\"0.3\"}]' ``` ``` statefulset.apps/zk patched ``` 更新の状況を見るには、`kubectl rollout status`を使います。 ```shell kubectl rollout status sts/zk ``` ``` waiting for statefulset rolling update to complete 0 pods at revision zk-5db4499664... Waiting for 1 pods to be ready... Waiting for 1 pods to be ready... waiting for statefulset rolling update to complete 1 pods at revision zk-5db4499664... Waiting for 1 pods to be ready... Waiting for 1 pods to be ready... waiting for statefulset rolling update to complete 2 pods at revision zk-5db4499664... Waiting for 1 pods to be ready... Waiting for 1 pods to be ready... statefulset rolling update complete 3 pods at revision zk-5db4499664... ``` これはPod群を終了し、逆の順番で1つずつそれらを新しい設定で再作成します。 これはクォーラムがローリングアップデート中に維持されることを保証します。 履歴や過去の設定を見るには、`kubectl rollout history`コマンドを使います。 ```shell kubectl rollout history sts/zk ``` 出力は次のようになります: ``` statefulsets \"zk\" REVISION 1 2 ``` 変更をロールバックするには、`kubectl rollout undo`コマンドを使います。 ```shell kubectl rollout undo sts/zk ``` 出力は次のようになります: ``` statefulset.apps/zk rolled back ``` ### プロセスの失敗の取り扱い [再起動ポリシー](/ja/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy)は、Pod内のコンテナのエントリポイントへのプロセスの失敗をKubernetesがどのように取り扱うかを制御します。 `StatefulSet`内のPodにおいて唯一妥当な`RestartPolicy`はAlwaysで、これはデフォルト値です。 ステートフルなアプリケーションでは、このデフォルトポリシーの上書きは**絶対にすべきではありません**。 `zk-0` Pod内で実行されているZooKeeperサーバーのプロセスツリーを調査するには、以下のコマンドを使います。 ```shell kubectl exec zk-0 -- ps -ef ``` コンテナのエントリポイントとして使われるコマンドはPID 1、エントリポイントの子であるZooKeeperプロセスはPID 27となっています。 ``` UID PID PPID C STIME TTY TIME CMD zookeep+ 1 0 0 15:03 ? 00:00:00 sh -c zkGenConfig.sh && zkServer.sh start-foreground zookeep+ 27 1 0 15:03 ? 00:00:03 /usr/lib/jvm/java-8-openjdk-amd64/bin/java -Dzookeeper.log.dir=/var/log/zookeeper -Dzookeeper.root.logger=INFO,CONSOLE -cp /usr/bin/../build/classes:/usr/bin/../build/lib/*.jar:/usr/bin/../share/zookeeper/zookeeper-3.4.9.jar:/usr/bin/../share/zookeeper/slf4j-log4j12-1.6.1.jar:/usr/bin/../share/zookeeper/slf4j-api-1.6.1.jar:/usr/bin/../share/zookeeper/netty-3.10.5.Final.jar:/usr/bin/../share/zookeeper/log4j-1.2.16.jar:/usr/bin/../share/zookeeper/jline-0.9.94.jar:/usr/bin/../src/java/lib/*.jar:/usr/bin/../etc/zookeeper: -Xmx2G -Xms2G -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false org.apache.zookeeper.server.quorum.QuorumPeerMain /usr/bin/../etc/zookeeper/zoo.cfg ``` 別のターミナルで、以下のコマンドを使って`zk` `StatefulSet`内のPodを見てみます。 ```shell kubectl get pod -w -l app=zk ``` 別のターミナルで、以下のコマンドを使ってPod `zk-0`内のZooKeeperプロセスを終了します。 ```shell kubectl exec zk-0 -- pkill java ``` ZooKeeperプロセスの終了は、その親プロセスの終了を引き起こします。 コンテナの`RestartPolicy`はAlwaysなので、親プロセスが再起動(restart)されます。 ``` NAME READY STATUS RESTARTS AGE zk-0 1/1 Running 0 21m zk-1 1/1 Running 0 20m zk-2 1/1 Running 0 19m NAME READY STATUS RESTARTS AGE zk-0 0/1 Error 0 29m zk-0 0/1 Running 1 29m zk-0 1/1 Running 1 29m ``` アプリケーションが、そのビジネスロジックを実装するプロセスを立ち上げるのにスクリプト(`zkServer.sh`など)を使っている場合、スクリプトは子プロセスとともに終了する必要があります。 これは、Kubernetesがアプリケーションのコンテナを、そのビジネスロジックを実装しているプロセスが失敗した時に再起動することを保証します。 ### 生存性テスト 失敗したプロセスを再起動するための設定をアプリケーションに施すのは、分散型システムの健全さを保つのに十分ではありません。 システムのプロセスが生きていることもあれば無反応なこともあり、あるいはそうでなく不健全という状況もあります。 アプリケーションのプロセスが不健全で再起動すべきであることをKubernetesに通知するには、liveness probeを使うのがよいでしょう。 `zk` `StatefulSet`のPod `template`でliveness probeを指定します。 ```yaml livenessProbe: exec: command: - sh - -c - \"zookeeper-ready 2181\" initialDelaySeconds: 15 timeoutSeconds: 5 ``` プローブはサーバーの健全さをテストするのに、ZooKeeperの`ruok` 4文字コマンドを使うbashスクリプトを呼び出します。 ``` OK=$(echo ruok | nc 127.0.0.1 $1) if [ \"$OK\" == \"imok\" ]; then exit 0 else exit 1 fi ``` ターミナルウィンドウで、`zk` StatefulSet内のPodを見るのに以下のコマンドを使います。 ```shell kubectl get pod -w -l app=zk ``` 別のウィンドウで、Pod `zk-0`のファイルシステムから`zookeeper-ready`スクリプトを削除するために以下のコマンドを使います。 ```shell kubectl exec zk-0 -- rm /opt/zookeeper/bin/zookeeper-ready ``` ZooKeeperプロセスの失敗のためにliveness probeを使う時、アンサンブル内の不健全なプロセスが再起動されることを保証するために、Kubernetesは自動的にプロセスを再起動します。 ```shell kubectl get pod -w -l app=zk ``` ``` NAME READY STATUS RESTARTS AGE zk-0 1/1 Running 0 1h zk-1 1/1 Running 0 1h zk-2 1/1 Running 0 1h NAME READY STATUS RESTARTS AGE zk-0 0/1 Running 0 1h zk-0 0/1 Running 1 1h zk-0 1/1 Running 1 1h ``` ### 準備性テスト 準備性は生存性と同じではありません。 プロセスが生きているのであれば、スケジュールされ健全です。 プロセスの準備ができたら、入力を処理できます。 生存性はなくてはならないものですが、準備性の状態には十分ではありません。 プロセスは生きてはいるが準備はできていない時、特に初期化および終了の間がそのケースに相当します。 準備性プローブを指定するとKubernetesは、準備性チェックに合格するまで、アプリケーションのプロセスがネットワークトラフィックを受け取らないことを保証します。 ZooKeeperサーバーにとって、健全性は準備性を意味します。 そのため、`zookeeper.yaml`マニフェストからの準備性プローブは、生存プローブと同一です。 ```yaml readinessProbe: exec: command: - sh - -c - \"zookeeper-ready 2181\" initialDelaySeconds: 15 timeoutSeconds: 5 ``` 健全性プローブと準備性プローブが同一だとしても、両方を指定することが重要です。 これは、ZooKeeperアンサンブル内の健全なサーバーだけがネットワークトラフィックを受け取ることを保証します。 ## ノードの失敗の許容 ZooKeeperはデータの変更を正しくコミットするのにサーバーのクォーラムを必要とします。 3つのサーバーのアンサンブルにおいては、書き込みの成功のために2つのサーバーは健全でなければなりません。 クォーラムベースのシステムにおいて、可用性を保証するために、メンバーは障害ドメインにデプロイされます。 個々のマシンを失ってしまうので、故障を避けるためのベストプラクティスは、同じマシン上でアプリケーションの複数のインスタンスがコロケート(同じ場所に配置)されないようにすることです。 デフォルトでKubernetesは、同じノードの`StatefulSet`にPodをコロケートします。 3つのサーバーアンサンブルを作成していたとして、2つのサーバーが同じノードにあり、そのノードが障害を起こした場合、ZooKeeperサービスのクライアントは、少なくともPodの1つが再スケジュールされるまで障害に見舞われることになります。 クリティカルシステムのプロセスがノードの失敗イベントで再スケジュールできるよう、追加のキャパシティを常にプロビジョンしておくべきです。 そうしておけば、障害は単にKubernetesのスケジューラーがZooKeeperのサーバーの1つを再スケジュールするまでの辛抱です。 ただし、ダウンタイムなしでノードの障害への耐性をサービスに持たせたいなら、`podAntiAffinity`をセットすべきです。 `zk` `StatefulSet`内のPodのノードを取得するには、以下のコマンドを使います。 ```shell for i in 0 1 2; do kubectl get pod zk-$i --template {{.spec.nodeName}}; echo \"\"; done ``` `zk` `StatefulSet`内の全てのPodは、別々のノードにデプロイされます。 ``` kubernetes-node-cxpk kubernetes-node-a5aq kubernetes-node-2g2d ``` これは`zk` `StatefulSet`内のPodに`PodAntiAffinity`の指定があるからです。 ```yaml affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: \"app\" operator: In values: - zk topologyKey: \"kubernetes.io/hostname\" ``` `requiredDuringSchedulingIgnoredDuringExecution`フィールドは、`topologyKey`で定義されたドメイン内で`app`ラベルの値が`zk`の2つのPodが絶対にコロケートすべきでないことを、Kubernetes Schedulerに指示します。 `topologyKey`の`kubernetes.io/hostname`は、ドメインが固有ノードであることを示しています。 異なるルール、ラベル、セレクターを使って、物理・ネットワーク・電源といった障害ドメイン全体に広がるアンサンブルにこのテクニックを広げることができます。 ## メンテナンスの存続 このセクションでは、ノードをcordon(スケジュール不可化)およびdorain(解放)します。もし共有クラスターでこのチュートリアルを試しているのであれば、これがほかのテナントに有害な影響を及ぼさないことを確認してください。 前のセクションでは、計画外のノード障害に備えてどのようにPodをノード全体に広げるかを示しましたが、計画されたメンテナンスのため引き起こされる一時的なノード障害に対して計画する必要もあります。 クラスター内のノードを取得するために、以下のコマンドを使います。 ```shell kubectl get nodes ``` このチュートリアルでは、4つのノードのあるクラスターを仮定しています。 クラスターが4つよりも多くある場合には、4つのノード以外全てをcordonするために[`kubectl cordon`](/docs/reference/generated/kubectl/kubectl-commands/#cordon)を使ってください。 ノードを4つに制約することで、以下のメンテナンスシミュレーションにおいてzookeeper Podをスケジュールした時に、KubernetesがアフィニティとPodDisruptionBudget制約に遭遇することを保証します。 ```shell kubectl cordon <ノード名> ``` `zk-pdb`の`PodDisruptionBudget`を取得するために、以下のコマンドを使います。 ```shell kubectl get pdb zk-pdb ``` `max-unavailable`フィールドは、`zk` `StatefulSet`の最大で1つのPodがいつでも利用できなくなる可能性があるということを、Kubernetesに指示します。 ``` NAME MIN-AVAILABLE MAX-UNAVAILABLE ALLOWED-DISRUPTIONS AGE zk-pdb N/A 1 1 ``` 1つ目のターミナルで、`zk` `StatefulSet`内のPodを見るのに以下のコマンドを使います。 ```shell kubectl get pods -w -l app=zk ``` 次に別のターミナルで、Podが現在スケジュールされているノードを取得するために、以下のコマンドを使います。 ```shell for i in 0 1 2; do kubectl get pod zk-$i --template {{.spec.nodeName}}; echo \"\"; done ``` 出力は次のようになります: ``` kubernetes-node-pb41 kubernetes-node-ixsl kubernetes-node-i4c4 ``` `zk-0` Podがスケジュールされているノードをcordonおよびdrainするには、[`kubectl drain`](/docs/reference/generated/kubectl/kubectl-commands/#drain)を使います。 ```shell kubectl drain $(kubectl get pod zk-0 --template {{.spec.nodeName}}) --ignore-daemonsets --force --delete-emptydir-data ``` 出力は次のようになります: ``` node \"kubernetes-node-pb41\" cordoned WARNING: Deleting pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet: fluentd-cloud-logging-kubernetes-node-pb41, kube-proxy-kubernetes-node-pb41; Ignoring DaemonSet-managed pods: node-problem-detector-v0.1-o5elz pod \"zk-0\" deleted node \"kubernetes-node-pb41\" drained ``` クラスターに4つのノードがあるので、`kubectl drain`は成功し、`zk-0`が別のノードに再スケジュールされます。 ``` NAME READY STATUS RESTARTS AGE zk-0 1/1 Running 2 1h zk-1 1/1 Running 0 1h zk-2 1/1 Running 0 1h NAME READY STATUS RESTARTS AGE zk-0 1/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Pending 0 0s zk-0 0/1 Pending 0 0s zk-0 0/1 ContainerCreating 0 0s zk-0 0/1 Running 0 51s zk-0 1/1 Running 0 1m ``` 最初のターミナルで`StatefulSet`のPodを見守り、`zk-1`がスケジュールされたノードをdrainします。 ```shell kubectl drain $(kubectl get pod zk-1 --template {{.spec.nodeName}}) --ignore-daemonsets --force --delete-emptydir-data ``` 出力は次のようになります: ``` \"kubernetes-node-ixsl\" cordoned WARNING: Deleting pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet: fluentd-cloud-logging-kubernetes-node-ixsl, kube-proxy-kubernetes-node-ixsl; Ignoring DaemonSet-managed pods: node-problem-detector-v0.1-voc74 pod \"zk-1\" deleted node \"kubernetes-node-ixsl\" drained ``` `zk` `StatefulSet`がPodのコロケーションを抑止する`PodAntiAffinity`ルールを含んでいるので、`zk-1` Podはスケジュールされず、またスケジュール可能なのは2つのノードだけなので、PodはPendingの状態のままになっています。 ```shell kubectl get pods -w -l app=zk ``` 出力は次のようになります: ``` NAME READY STATUS RESTARTS AGE zk-0 1/1 Running 2 1h zk-1 1/1 Running 0 1h zk-2 1/1 Running 0 1h NAME READY STATUS RESTARTS AGE zk-0 1/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Pending 0 0s zk-0 0/1 Pending 0 0s zk-0 0/1 ContainerCreating 0 0s zk-0 0/1 Running 0 51s zk-0 1/1 Running 0 1m zk-1 1/1 Terminating 0 2h zk-1 0/1 Terminating 0 2h zk-1 0/1 Terminating 0 2h zk-1 0/1 Terminating 0 2h zk-1 0/1 Pending 0 0s zk-1 0/1 Pending 0 0s ``` StatefulSetのPodを見続け、`zk-2`がスケジュールされているノードをdrainします。 ```shell kubectl drain $(kubectl get pod zk-2 --template {{.spec.nodeName}}) --ignore-daemonsets --force --delete-emptydir-data ``` 出力は次のようになります: ``` node \"kubernetes-node-i4c4\" cordoned WARNING: Deleting pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet: fluentd-cloud-logging-kubernetes-node-i4c4, kube-proxy-kubernetes-node-i4c4; Ignoring DaemonSet-managed pods: node-problem-detector-v0.1-dyrog WARNING: Ignoring DaemonSet-managed pods: node-problem-detector-v0.1-dyrog; Deleting pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet: fluentd-cloud-logging-kubernetes-node-i4c4, kube-proxy-kubernetes-node-i4c4 There are pending pods when an error occurred: Cannot evict pod as it would violate the pod's disruption budget. pod/zk-2 ``` kubectlを終了するために`CTRL-C`を押します。 `zk-2`を退去させると`zk-budget`違反になってしまうので、3つ目のノードはdrainできません。ただし、ノードはcordonされたままとなります。 健全性テスト中に入力した値を`zk-0`から取得するには、`zkCli.sh`を使います。 ```shell kubectl exec zk-0 zkCli.sh get /hello ``` `PodDisruptionBudget`が遵守されているので、サービスはまだ利用可能です。 ``` WatchedEvent state:SyncConnected type:None path:null world cZxid = 0x200000002 ctime = Wed Dec 07 00:08:59 UTC 2016 mZxid = 0x200000002 mtime = Wed Dec 07 00:08:59 UTC 2016 pZxid = 0x200000002 cversion = 0 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 5 numChildren = 0 ``` 最初のノードをuncordon(スケジュール可能化)するには、[`kubectl uncordon`](/docs/reference/generated/kubectl/kubectl-commands/#uncordon)を使います。 ```shell kubectl uncordon kubernetes-node-pb41 ``` 出力は次のようになります: ``` node \"kubernetes-node-pb41\" uncordoned ``` `zk-1`はこのノードで再スケジュールされます。`zk-1`がRunningおよびReadyになるまで待ちます。 ```shell kubectl get pods -w -l app=zk ``` 出力は次のようになります: ``` NAME READY STATUS RESTARTS AGE zk-0 1/1 Running 2 1h zk-1 1/1 Running 0 1h zk-2 1/1 Running 0 1h NAME READY STATUS RESTARTS AGE zk-0 1/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Terminating 2 2h zk-0 0/1 Pending 0 0s zk-0 0/1 Pending 0 0s zk-0 0/1 ContainerCreating 0 0s zk-0 0/1 Running 0 51s zk-0 1/1 Running 0 1m zk-1 1/1 Terminating 0 2h zk-1 0/1 Terminating 0 2h zk-1 0/1 Terminating 0 2h zk-1 0/1 Terminating 0 2h zk-1 0/1 Pending 0 0s zk-1 0/1 Pending 0 0s zk-1 0/1 Pending 0 12m zk-1 0/1 ContainerCreating 0 12m zk-1 0/1 Running 0 13m zk-1 1/1 Running 0 13m ``` 試しに`zk-2`がスケジュールされているノードをdrainしてみます。 ```shell kubectl drain $(kubectl get pod zk-2 --template {{.spec.nodeName}}) --ignore-daemonsets --force --delete-emptydir-data ``` 出力は次のようになります: ``` node \"kubernetes-node-i4c4\" already cordoned WARNING: Deleting pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet: fluentd-cloud-logging-kubernetes-node-i4c4, kube-proxy-kubernetes-node-i4c4; Ignoring DaemonSet-managed pods: node-problem-detector-v0.1-dyrog pod \"heapster-v1.2.0-2604621511-wht1r\" deleted pod \"zk-2\" deleted node \"kubernetes-node-i4c4\" drained ``` 今度は`kubectl drain`は成功しました。 `zk-2`の再スケジュールができるように、2つ目のノードをuncordonします。 ```shell kubectl uncordon kubernetes-node-ixsl ``` 出力は次のようになります: ``` node \"kubernetes-node-ixsl\" uncordoned ``` サービスがメンテナンス中も利用可能なままであることを保証するために、`PodDisruptionBudgets`とあわせて`kubectl drain`を利用できます。 メンテナンスでノードがオフラインになる前にノードをcordonして、Podを退去させるのにdrainが使われている場合、Disruption Budget(停止状態の予算)を表すサービスは遵守すべきバジェットを持ちます。 クリティカルサービスでは、Podをすぐに再スケジュールできるよう、追加のキャパティを常に割り当てておくべきです。 ## {{% heading \"cleanup\" %}} - クラスターの全てのノードをuncordonするために、`kubectl uncordon`を実行してください。 - このチュートリアルで使ったPersistentVolumeの永続的なストレージメディアを削除する必要があります。 全てのストレージが回収されたことを確実とするために、お使いの環境、ストレージ設定、プロビジョニング方法に基いて必要な手順に従ってください。 "} {"_id":"q-en-website-c77ebe17685638eb982feb01a843832e16c20ed70b9627a275ce971f73651556","text":" apiVersion: v1 kind: Pod metadata: name: dapi-test-pod spec: containers: - name: test-container image: k8s.gcr.io/busybox command: [ \"/bin/sh\", \"-c\", \"env\" ] env: - name: SPECIAL_LEVEL_KEY valueFrom: configMapKeyRef: name: special-config key: special.how - name: LOG_LEVEL valueFrom: configMapKeyRef: name: env-config key: log_level restartPolicy: Never "} {"_id":"q-en-website-c7c8b52687c51747c453ccefdfad239801d18a131eddb678839c70b0f7df16a4","text":"401: Unauthorized 404: Not Found (if the `CheckpointContainer` feature gate is disabled) 404: Not Found (if the `ContainerCheckpoint` feature gate is disabled) 404: Not Found (if the specified `namespace`, `pod` or `container` cannot be found)"} {"_id":"q-en-website-c7dcb257e64df6dfebc583420129bab2ebfd26c28f0e3dd28ec7e47d36afc2a7","text":" kubeadmを使用して、コントロールプレーンとワーカーノード{{< glossary_tooltip text=\"ワーカーノード\" term_id=\"node\" >}}コンポーネントの両方をインストールできます。 kubeadmを使用して、コントロールプレーンと{{< glossary_tooltip text=\"ワーカーノード\" term_id=\"node\" >}}コンポーネントの両方をインストールできます。 "} {"_id":"q-en-website-c8f7f8dfca78f2636877f6559136a8ced6a0606a7f93dba45abb1b0ef23dcbbf","text":" --- title: Autoscaling Workloads description: >- With autoscaling, you can automatically update your workloads in one way or another. This allows your cluster to react to changes in resource demand more elastically and efficiently. content_type: concept weight: 40 --- In Kubernetes, you can _scale_ a workload depending on the current demand of resources. This allows your cluster to react to changes in resource demand more elastically and efficiently. When you scale a workload, you can either increase or decrease the number of replicas managed by the workload, or adjust the resources available to the replicas in-place. The first approach is referred to as _horizontal scaling_, while the second is referred to as _vertical scaling_. There are manual and automatic ways to scale your workloads, depending on your use case. ## Scaling workloads manually Kubernetes supports _manual scaling_ of workloads. Horizontal scaling can be done using the `kubectl` CLI. For vertical scaling, you need to _patch_ the resource definition of your workload. See below for examples of both strategies. - **Horizontal scaling**: [Running multiple instances of your app](/docs/tutorials/kubernetes-basics/scale/scale-intro/) - **Vertical scaling**: [Resizing CPU and memory resources assigned to containers](/docs/tasks/configure-pod-container/resize-container-resources) ## Scaling workloads automatically Kubernetes also supports _automatic scaling_ of workloads, which is the focus of this page. The concept of _Autoscaling_ in Kubernetes refers to the ability to automatically update an object that manages a set of Pods (for example a {{< glossary_tooltip text=\"Deployment\" term_id=\"deployment\" >}}. ### Scaling workloads horizontally In Kubernetes, you can automatically scale a workload horizontally using a _HorizontalPodAutoscaler_ (HPA). It is implemented as a Kubernetes API resource and a {{< glossary_tooltip text=\"controller\" term_id=\"controller\" >}} and periodically adjusts the number of {{< glossary_tooltip text=\"replicas\" term_id=\"replica\" >}} in a workload to match observed resource utilization such as CPU or memory usage. There is a [walkthrough tutorial](/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough) of configuring a HorizontalPodAutoscaler for a Deployment. ### Scaling workloads vertically {{< feature-state for_k8s_version=\"v1.25\" state=\"stable\" >}} You can automatically scale a workload vertically using a _VerticalPodAutoscaler_ (VPA). Different to the HPA, the VPA doesn't come with Kubernetes by default, but is a separate project that can be found [on GitHub](https://github.com/kubernetes/autoscaler/tree/9f87b78df0f1d6e142234bb32e8acbd71295585a/vertical-pod-autoscaler). Once installed, it allows you to create {{< glossary_tooltip text=\"CustomResourceDefinitions\" term_id=\"customresourcedefinition\" >}} (CRDs) for your workloads which define _how_ and _when_ to scale the resources of the managed replicas. {{< note >}} You will need to have the [Metrics Server](https://github.com/kubernetes-sigs/metrics-server) installed to your cluster for the HPA to work. {{< /note >}} At the moment, the VPA can operate in four different modes: {{< table caption=\"Different modes of the VPA\" >}} Mode | Description :----|:----------- `Auto` | Currently `Recreate`, might change to in-place updates in the future `Recreate` | The VPA assigns resource requests on pod creation as well as updates them on existing pods by evicting them when the requested resources differ significantly from the new recommendation `Initial` | The VPA only assigns resource requests on pod creation and never changes them later. `Off` | The VPA does not automatically change the resource requirements of the pods. The recommendations are calculated and can be inspected in the VPA object. {{< /table >}} #### Requirements for in-place resizing {{< feature-state for_k8s_version=\"v1.27\" state=\"alpha\" >}} Resizing a workload in-place **without** restarting the {{< glossary_tooltip text=\"Pods\" term_id=\"pod\" >}} or its {{< glossary_tooltip text=\"Containers\" term_id=\"container\" >}} requires Kubernetes version 1.27 or later.
Additionally, the `InPlaceVerticalScaling` feature gate needs to be enabled. {{< feature-gate-description name=\"InPlacePodVerticalScaling\" >}} ### Autoscaling based on cluster size For workloads that need to be scaled based on the size of the cluster (for example `cluster-dns` or other system components), you can use the _Cluster Proportional Autoscaler_.
Just like the VPA, it is not part of the Kubernetes core, but hosted in its own repository [on GitHub](https://github.com/kubernetes-sigs/cluster-proportional-autoscaler). The Cluster Proportional Autoscaler watches the number of schedulable {{< glossary_tooltip text=\"nodes\" term_id=\"node\" >}} and cores and scales the number of replicas of the target workload accordingly. ### Event driven Autoscaling It is also possible to scale workloads based on events, for example using the [_Kubernetes Event Driven Autoscaler_ (**KEDA**)](https://keda.sh/). KEDA is a CNCF graduated enabling you to scale your workloads based on the number of events to be processed, for example the amount of messages in a queue. There exists a wide range of adapters for different event sources to choose from. ### Autoscaling based on schedules Another strategy for scaling your workloads is to **schedule** the scaling operations, for example in order to reduce resource consumption during off-peak hours. Similar to event driven autoscaling, such behavior can be achieved using KEDA in conjunction with its [`Cron` scaler](https://keda.sh/docs/2.13/scalers/cron/). The `Cron` scaler allows you to define schedules (and time zones) for scaling your workloads in or out. ## Scaling cluster infrastructure If scaling workloads isn't enough to meet your needs, you can also scale your cluster infrastructure itself. Scaling the cluster infrastructure normally means adding or removing {{< glossary_tooltip text=\"nodes\" term_id=\"node\" >}}. This can be done using one of two available autoscalers: - [**Cluster Autoscaler**](https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler) - [**Karpenter**](https://github.com/kubernetes-sigs/karpenter?tab=readme-ov-file) Both scalers work by watching for pods marked as _unschedulable_ or _underutilized_ nodes and then adding or removing nodes as needed. ## {{% heading \"whatsnext\" %}} - Learn more about scaling horizontally - [Scale a StatefulSet](/docs/tasks/run-application/scale-stateful-set/) - [HorizontalPodAutoscaler Walkthrough](/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/) - [Resize Container Resources In-Place](/docs/tasks/configure-pod-container/resize-container-resources/) - [Autoscale the DNS Service in a Cluster](/docs/tasks/administer-cluster/dns-horizontal-autoscaling/)
"} {"_id":"q-en-website-c956b156c05d16947fdf0808d5d7721dd83a2f8726a2ae944620df0a20d9a9b7","text":"The list of phases can be obtained with the kubeadm init --help command. The flag "--skip-phases" takes precedence over this field.

-->

skipPhases 是命令执行过程中药略过的阶段(Phases)。

skipPhases 是命令执行过程中要略过的阶段(Phases)。 通过执行命令 kubeadm init --help 可以获得阶段的列表。 参数标志 "--skip-phases" 优先于此字段的设置。

"} {"_id":"q-en-website-ca50688297b52ef07865828c9a438e894f7aae3d2396fe518acaafdff55aebc8","text":" --- # reviewers: # - enisoc # - erictune # - foxish # - janetkuo # - kow3ns # - smarterclayton title: 복제 스테이트풀 애플리케이션 실행하기 content_type: tutorial weight: 30 --- 이 페이지에서는 {{< glossary_tooltip term_id=\"statefulset\" >}} 으로 복제 스테이트풀 애플리케이션을 실행하는 방법에 대해 소개한다. 이 애플리케이션은 복제 MySQL 데이터베이스이다. 이 예제의 토폴로지는 단일 주 서버와 여러 복제 서버로 이루어져있으며, row-based 비동기 복제 방식을 사용한다. {{< note >}} **해당 설정은 프로덕션 설정이 아니다**. 쿠버네티스에서 스테이트풀한 애플리케이션을 실행하기 위한 일반적인 패턴에 집중하기 위해 MySQL 세팅이 안전하지 않은 기본 설정으로 되어 있다. {{< /note >}} ## {{% heading \"prerequisites\" %}} * {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} * {{< include \"default-storage-class-prereqs.md\" >}} * 이 튜토리얼은 [퍼시스턴트볼륨](/ko/docs/concepts/storage/persistent-volumes/) 그리고 [스테이트풀셋](/ko/docs/concepts/workloads/controllers/statefulset/), [파드](/ko/docs/concepts/workloads/pods/), [서비스](/ko/docs/concepts/services-networking/service/), [컨피그맵(ConfigMap)](/docs/tasks/configure-pod-container/configure-pod-configmap/)와 같은 핵심 개념들에 대해 알고 있다고 가정한다. * MySQL에 대한 지식이 있으면 도움이 되지만, 이 튜토리얼은 다른 시스템을 활용하였을 때도 도움이 되는 일반적인 패턴을 다루는데 중점을 둔다. * default 네임스페이스를 사용하거나, 다른 오브젝트들과 충돌이 나지 않는 다른 네임스페이스를 사용한다. ## {{% heading \"objectives\" %}} * 스테이트풀셋을 이용한 복제 MySQL 토폴로지를 배포한다. * MySQL 클라이언트에게 트래픽을 보낸다. * 다운타임에 대한 저항력을 관찰한다. * 스테이트풀셋을 확장/축소한다. ## MySQL 배포하기 MySQL 디플로이먼트 예시는 컨피그맵과, 2개의 서비스, 그리고 스테이트풀셋으로 구성되어 있다. ### 컨피그맵 생성하기 {#configmap} 다음 YAML 설정 파일로부터 컨피그맵을 생성한다. {{< codenew file=\"application/mysql/mysql-configmap.yaml\" >}} ```shell kubectl apply -f https://k8s.io/examples/application/mysql/mysql-configmap.yaml ``` 이 컨피그맵은 당신이 독립적으로 주 MySQL 서버와 레플리카들의 설정을 컨트롤할 수 있도록 `my.cnf` 을 오버라이드한다. 이 경우에는, 주 서버는 복제 로그를 레플리카들에게 제공하고 레플리카들은 복제를 통한 쓰기가 아닌 다른 쓰기들은 거부하도록 할 것이다. 컨피그맵 자체가 다른 파드들에 서로 다른 설정 영역이 적용되도록 하는 것이 아니다. 스테이트풀셋 컨트롤러가 제공해주는 정보에 따라서, 각 파드들은 초기화되면서 설정 영역을 참조할지 결정한다. ### 서비스 생성하기 {#services} 다음 YAML 설정 파일로부터 서비스를 생성한다. {{< codenew file=\"application/mysql/mysql-services.yaml\" >}} ```shell kubectl apply -f https://k8s.io/examples/application/mysql/mysql-services.yaml ``` 헤드리스 서비스는 스테이트풀셋 {{< glossary_tooltip text=\"컨트롤러\" term_id=\"controller\" >}}가 집합의 일부분인 파드들을 위해 생성한 DNS 엔트리들(entries)의 위한 거점이 된다. 헤드리스 서비스의 이름이 `mysql`이므로, 파드들은 같은 쿠버네티스 클러스터나 네임스페이스에 존재하는 다른 파드들에게 `.mysql`라는 이름으로 접근될 수 있다. `mysql-read`라고 불리우는 클라이언트 서비스는 고유의 클러스터 IP를 가지며, Ready 상태인 모든 MySQL 파드들에게 커넥션을 분배하는 일반적인 서비스이다. 잠재적인 엔드포인트들의 집합은 주 MySQL 서버와 해당 레플리카들을 포함한다. 오직 읽기 쿼리들만 로드-밸런싱된 클라이언트 서비스를 이용할 수 있다는 사실에 주목하자. 하나의 주 MySQL 서버만이 존재하기 떄문에, 클라이언트들은 쓰기 작업을 실행하기 위해서 주 MySQL 파드에 (헤드리스 서비스 안에 존재하는 DNS 엔트리를 통해) 직접 접근해야 한다. ### 스테이트풀셋 생성하기 {#statefulset} 마지막으로, 다음 YAML 설정 파일로부터 스테이트풀셋을 생성한다. {{< codenew file=\"application/mysql/mysql-statefulset.yaml\" >}} ```shell kubectl apply -f https://k8s.io/examples/application/mysql/mysql-statefulset.yaml ``` 다음을 실행하여, 초기화되는 프로세스들을 확인할 수 있다. ```shell kubectl get pods -l app=mysql --watch ``` 잠시 뒤에, 3개의 파드들이 `Running` 상태가 되는 것을 볼 수 있다. ``` NAME READY STATUS RESTARTS AGE mysql-0 2/2 Running 0 2m mysql-1 2/2 Running 0 1m mysql-2 2/2 Running 0 1m ``` **Ctrl+C**를 입력하여 watch를 종료하자. {{< note >}} 만약 아무 진행 상황도 보이지 않는다면, [시작하기 전에](#before-you-begin) 에 언급된 동적 퍼시스턴트볼륨 프로비저너(provisioner)가 활성화되어 있는지 확인한다. {{< /note >}} 해당 메니페스트에는 스테이트풀셋의 일부분인 스테이트풀 파드들을 관리하기 위한 다양한 기법들이 적용되어 있다. 다음 섹션에서는 스테트풀셋이 파드들을 생성할 때 일어나는 일들을 이해할 수 있도록 일부 기법들을 강조하여 설명한다. ## 스테이트풀 파드 초기화 이해하기 스테이트풀셋 컨트롤러는 파드들의 인덱스에 따라 순차적으로 시작시킨다. 컨트롤러는 다음 파드 생성 이전에 각 파드가 Ready 상태가 되었다고 알려줄 때까지 기다린다. 추가적으로, 컨트롤러는 각 파드들에게 `<스테이트풀셋 이름>-<순차적 인덱스>` 형태의 고유하고 안정적인 이름을 부여하는데, 결과적으로 파드들은 `mysql-0`, `mysql-1`, 그리고 `mysql-2` 라는 이름을 가지게 된다. 스테이트풀셋 매니페스트의 파드 템플릿은 해당 속성들을 통해 순차적인 MySQL 복제의 시작을 수행한다. ### 설정 생성하기 파드 스펙의 컨테이너를 시작하기 전에, 파드는 순서가 정의되어 있는 [초기화 컨테이너](/ko/docs/concepts/workloads/pods/init-containers/)들을 먼저 실행시킨다. `init-mysql`라는 이름의 첫 번째 초기화 컨테이너는, 인덱스에 따라 특별한 MySQL 설정 파일을 생성한다. 스크립트는 인덱스를 `hostname` 명령으로 반환되는 파드 이름의 마지막 부분에서 추출하여 결정한다. 그리고 인덱스(이미 사용된 값들을 피하기 위한 오프셋 숫자와 함께)를 MySQL의 `conf.d` 디렉토리의 `server-id.cnf` 파일에 저장한다. 이는 스테이트풀셋에게서 제공된 고유하고, 안정적인 신원을 같은 속성을 필요로 하는 MySQL 서버 ID의 형태로 바꾸어준다. 또한 `init-mysql` 컨테이너의 스크립트는 컨피그맵을 `conf.d`로 복사하여, `primary.cnf` 또는 `replica.cnf`을 적용한다. 이 예제의 토폴로지가 하나의 주 MySQL 서버와 일정 수의 레플리카들로 이루어져 있기 때문에, 스크립트는 `0` 인덱스를 주 서버로, 그리고 나머지 값들은 레플리카로 지정한다. 스테이트풀셋 컨트롤러의 [디플로이먼트와 스케일링 보증](/ko/docs/concepts/workloads/controllers/statefulset/#디플로이먼트와-스케일링-보증)과 합쳐지면, 복제를 위한 레플리카들을 생성하기 전에 주 MySQL 서버가 Ready 상태가 되도록 보장할 수 있다. ### 기존 데이터 복제(cloning) 일반적으로, 레플리카에 새로운 파드가 추가되는 경우, 주 MySQL 서버가 이미 데이터를 가지고 있다고 가정해야 한다. 또한 복제 로그가 첫 시작점부터의 로그들을 다 가지고 있지는 않을 수 있다고 가정해야 한다. 이러한 보수적인 가정들은 스테이트풀셋이 초기 크기로 고정되어 있는 것보다, 시간에 따라 확장/축소하게 할 수 있도록 하는 중요한 열쇠가 된다. `clone-mysql`라는 이름의 두 번째 초기화 컨테이너는, 퍼시스턴트볼륨에서 처음 초기화된 레플리카 파드에 복제 작업을 수행한다. 이 말은 다른 실행 중인 파드로부터 모든 데이터들을 복제하기 때문에, 로컬의 상태가 충분히 일관성을 유지하고 있어서 주 서버에서부터 복제를 시작할 수 있다는 의미이다. MySQL 자체가 이러한 메커니즘을 제공해주지는 않기 때문에, 이 예제에서는 XtraBackup이라는 유명한 오픈소스 도구를 사용한다. 복제 중에는, 복제 대상 MySQL 서버가 성능 저하를 겪을 수 있다. 주 MySQL 서버의 이러한 충격을 최소화하기 위해, 스크립트는 각 파드가 자신의 인덱스보다 하나 작은 파드로부터 복제하도록 지시한다. 이것이 정상적으로 동작하는 이유는 스테이트풀셋 컨트롤러가 파드 `N+1`을 실행하기 전에 항상 파드 `N`이 Ready 상태라는 것을 보장하기 때문이다. ### 복제(replication) 시작하기 초기화 컨테이너들의 성공적으로 완료되면, 일반적인 컨테이너가 실행된다. MySQL 파드는 `mysqld` 서버를 구동하는 `mysql` 컨테이너로 구성되어 있으며, `xtrabackup` 컨테이너는 [사이드카(sidecar)](/blog/2015/06/the-distributed-system-toolkit-patterns)로서 작동한다. `xtrabackup` 사이드카는 복제된 데이터 파일들을 보고 레플리카에 MySQL 복제를 시작해야 할 필요가 있는지 결정한다. 만약 그렇다면, `mysqld`이 준비될 때까지 기다린 후 `CHANGE MASTER TO`, 그리고 `START SLAVE`를 XtraBackup 복제(clone) 파일들에서 추출한 복제(replication) 파라미터들과 함께 실행시킨다. 레플리카가 복제를 시작하면, 먼저 주 MySQL 서버를 기억하고, 서버가 재시작되거나 커넥션이 끊어지면 다시 연결한다. 또한 레플리카들은 주 서버를 안정된 DNS 이름 (`mysql-0.mysql`)으로 찾기 때문에, 주 서버가 리스케쥴링에 의해 새로운 파드 IP를 받아도 주 서버를 자동으로 찾는다. 마지막으로, 복제를 시작한 후에는, `xtrabackup` 컨테이너는 데이터 복제를 요청하는 다른 파드들의 커넥션을 리스닝한다. 이 서버는 스테이트풀셋이 확장하거나, 다음 파드가 퍼시스턴트볼륨클레임을 잃어서 다시 복제를 수행해햐 할 경우를 대비하여 독립적으로 존재해야 한다. ## 클라이언트 트래픽 보내기 임시 컨테이너를 `mysql:5.7` 이미지로 실행하고 `mysql` 클라이언트 바이너리를 실행하는 것으로 테스트 쿼리를 주 MySQL 서버(`mysql-0.mysql` 호스트네임)로 보낼 수 있다. ```shell kubectl run mysql-client --image=mysql:5.7 -i --rm --restart=Never -- mysql -h mysql-0.mysql <`를 이전 단계에서 찾았던 노드의 이름으로 바꾸자. {{< caution >}} 노드 드레인은 해당 노드에서 실행 중인 다른 워크로드와 애플리케이션들에게 영향을 줄 수 있다. 테스트 클러스터에만 다음 단계를 수행하자. {{< /caution >}} ```shell # 위에 명시된 다른 워크로드들이 받는 영향에 대한 주의사항을 확인한다. kubectl drain --force --delete-emptydir-data --ignore-daemonsets ``` 이제 파드가 다른 노드에 리스케줄링되는 것을 관찰할 수 있다. ```shell kubectl get pod mysql-2 -o wide --watch ``` 출력은 다음과 비슷할 것이다. ``` NAME READY STATUS RESTARTS AGE IP NODE mysql-2 2/2 Terminating 0 15m 10.244.1.56 kubernetes-node-9l2t [...] mysql-2 0/2 Pending 0 0s kubernetes-node-fjlm mysql-2 0/2 Init:0/2 0 0s kubernetes-node-fjlm mysql-2 0/2 Init:1/2 0 20s 10.244.5.32 kubernetes-node-fjlm mysql-2 0/2 PodInitializing 0 21s 10.244.5.32 kubernetes-node-fjlm mysql-2 1/2 Running 0 22s 10.244.5.32 kubernetes-node-fjlm mysql-2 2/2 Running 0 30s 10.244.5.32 kubernetes-node-fjlm ``` 그리고, 서버 ID `102`가 `SELECT @@server_id` 루프 출력에서 잠시 사라진 후 다시 보이는 것을 확인할 수 있을 것이다. 이제 노드의 스케줄 방지를 다시 해제(uncordon)해서 정상으로 돌아가도록 조치한다. ```shell kubectl uncordon ``` ## 레플리카 스케일링하기 MySQL 레플리케이션을 사용하면, 레플리카를 추가하는 것으로 읽기 쿼리 용량을 키울 수 있다. 스테이트풀셋을 사용하면, 단 한 줄의 명령으로 달성할 수 있다. ```shell kubectl scale statefulset mysql --replicas=5 ``` 명령을 실행시켜서 새로운 파드들이 올라오는 것을 관찰하자. ```shell kubectl get pods -l app=mysql --watch ``` 파드들이 올라오면, `SELECT @@server_id` 루프 출력에 서버 ID `103` 과 `104`가 나타나기 시작할 것이다. 그리고 해당 파드들이 존재하기 전에 추가된 데이터들이 해당 새 서버들에게도 존재하는 것을 확인할 수 있다. ```shell kubectl run mysql-client --image=mysql:5.7 -i -t --rm --restart=Never -- mysql -h mysql-3.mysql -e \"SELECT * FROM test.messages\" ``` ``` Waiting for pod default/mysql-client to be running, status is Pending, pod ready: false +---------+ | message | +---------+ | hello | +---------+ pod \"mysql-client\" deleted ``` 축소하는 것도 간단하게 할 수 있다. ```shell kubectl scale statefulset mysql --replicas=3 ``` {{< note >}} 확장은 퍼시스턴트볼륨클레임을 자동으로 생성하지만, 축소에서는 해당 PVC들이 자동으로 삭제되지 않는다. 이로써 확장을 빠르게 하기 위해 초기화된 PVC들을 보관해 두거나, 삭제하기 전에 데이터를 추출하는 선택을 할 수 있다. {{< /note >}} 다음 명령을 실행하여 확인할 수 있다. ```shell kubectl get pvc -l app=mysql ``` 스테이트풀셋을 3으로 축소했음에도 PVC 5개가 아직 남아있음을 보여준다. ``` NAME STATUS VOLUME CAPACITY ACCESSMODES AGE data-mysql-0 Bound pvc-8acbf5dc-b103-11e6-93fa-42010a800002 10Gi RWO 20m data-mysql-1 Bound pvc-8ad39820-b103-11e6-93fa-42010a800002 10Gi RWO 20m data-mysql-2 Bound pvc-8ad69a6d-b103-11e6-93fa-42010a800002 10Gi RWO 20m data-mysql-3 Bound pvc-50043c45-b1c5-11e6-93fa-42010a800002 10Gi RWO 2m data-mysql-4 Bound pvc-500a9957-b1c5-11e6-93fa-42010a800002 10Gi RWO 2m ``` 만약 여분의 PVC들을 재사용하지 않을 것이라면, 이들을 삭제할 수 있다. ```shell kubectl delete pvc data-mysql-3 kubectl delete pvc data-mysql-4 ``` ## {{% heading \"cleanup\" %}} 1. `SELECT @@server_id` 루프를 끝내기 위해, 터미널에 **Ctrl+C**를 입력하거나, 해당 명령을 다른 터미널에서 실행시키자. ```shell kubectl delete pod mysql-client-loop --now ``` 1. 스테이트풀셋을 삭제한다. 이것은 파드들 또한 삭제할 것이다. ```shell kubectl delete statefulset mysql ``` 1. 파드들의 삭제를 확인한다. 삭제가 완료되기까지 시간이 걸릴 수 있다. ```shell kubectl get pods -l app=mysql ``` 위와 같은 메세지가 나타나면 파드들이 삭제되었다는 것을 알 수 있다. ``` No resources found. ``` 1. 컨피그맵, 서비스, 그리고 퍼시스턴트볼륨클레임들을 삭제한다. ```shell kubectl delete configmap,service,pvc -l app=mysql ``` 1. 만약 수동으로 퍼시스턴스볼륨들을 프로비저닝했다면, 수동으로 삭제하면서, 그 밑에 존재하는 리소스들을 또한 삭제해야 한다. 만약 동적 프로비저너를 사용했다면, 당신이 퍼시스턴트볼륨클레임으로 삭제하면 자동으로 퍼시스턴트볼륨을 삭제한다. 일부 (EBS나 PD와 같은) 동적 프로비저너들은 퍼시스턴트볼륨을 삭제 하면 그 뒤에 존재하는 리소스들도 삭제한다. ## {{% heading \"whatsnext\" %}} * [스테이트풀셋(StatefulSet) 확장하기](/ko/docs/tasks/run-application/scale-stateful-set/)에 대해 더 배워보기. * [스테이트풀셋 디버깅하기](/ko/docs/tasks/debug/debug-application/debug-statefulset/)에 대해 더 배워보기. * [스테이트풀셋(StatefulSet) 삭제하기](/ko/docs/tasks/run-application/delete-stateful-set/)에 대해 더 배워보기. * [스테이트풀셋(StatefulSet) 파드 강제 삭제하기](/ko/docs/tasks/run-application/force-delete-stateful-set-pod/)에 대해 더 배워보기. * [Helm Charts 저장소](https://artifacthub.io/)를 통해 다른 스테이트풀 애플리케이션 예제들을 확인해보기. "} {"_id":"q-en-website-ca6376add9780fce1ab0d7579ce0dafd46adde124706190cb23040bd8acb6775","text":"| `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 | To illustrate these labels in action, consider the following StatefulSet object: To illustrate these labels in action, consider the following {{< glossary_tooltip text=\"StatefulSet\" term_id=\"statefulset\" >}} object: ```yaml # This is an excerpt apiVersion: apps/v1 kind: StatefulSet metadata:"} {"_id":"q-en-website-cbea14ebf3625b36f27a10b2529a4ea766763a9c61b86e6dd72b7d607bb5fbdb","text":"gcloud components install kubectl ``` Do check that the version is sufficiently up-to-date using `kubectl version`. Check that the version is sufficiently up-to-date using `kubectl version`. ## Install with brew ## Install with Homebrew on macOS If you are on MacOS and using brew, you can install with: If you are on macOS and using [Homebrew](https://brew.sh/) package manager, you can install with: ```shell brew install kubectl"} {"_id":"q-en-website-cc316be2ee541111e7e1dbe460b2ad9971ed27efe278e0cc4a44c31b1b53cbbf","text":"body.cid-community #gallery { display: flex; max-width: 100vw; max-width: 100%; gap: 0.75rem; justify-content: center; margin-left: auto;"} {"_id":"q-en-website-cd434535c2fc9682d6ddfc070961235255e746849dc30d09dbe6a0855bd3591e","text":"| Golang marker | OpenAPI extension | Accepted values | Description | Introduced in | |---|---|---|---|---| | `//+listType` | `x-kubernetes-list-type` | `atomic`/`set`/`map` | Applicable to lists. `atomic` and `set` apply to lists with scalar elements only. `map` applies to lists of nested types only. If configured as `atomic`, the entire list is replaced during merge; a single manager manages the list as a whole at any one time. If `granular`, different managers can manage entries separately. | 1.16 | | `//+listType` | `x-kubernetes-list-type` | `atomic`/`set`/`map` | Applicable to lists. `atomic` and `set` apply to lists with scalar elements only. `map` applies to lists of nested types only. If configured as `atomic`, the entire list is replaced during merge; a single manager manages the list as a whole at any one time. If `set` or `map`, different managers can manage entries separately. | 1.16 | | `//+listMapKey` | `x-kubernetes-list-map-keys` | Slice of map keys that uniquely identify entries for example `[\"port\", \"protocol\"]` | Only applicable when `+listType=map`. A slice of strings whose values in combination must uniquely identify list entries. While there can be multiple keys, `listMapKey` is singular because keys need to be specified individually in the Go type. | 1.16 | | `//+mapType` | `x-kubernetes-map-type` | `atomic`/`granular` | Applicable to maps. `atomic` means that the map can only be entirely replaced by a single manager. `granular` means that the map supports separate managers updating individual fields. | 1.17 | | `//+structType` | `x-kubernetes-map-type` | `atomic`/`granular` | Applicable to structs; otherwise same usage and OpenAPI annotation as `//+mapType`.| 1.17 |"} {"_id":"q-en-website-cf49cd95ce2b3c265e3efb5b47754634ce8d6e5d9402c0998c1e4b36bf697d6a","text":"title: \"Overview\" weight: 20 description: Get a high-level outline of Kubernetes and the components it is built from. sitemap: priority: 0.9 ---"} {"_id":"q-en-website-d1907d333153765b0ab1a5cc0ff232ed1660faa14382de850279531b5d9243f5","text":"id: statefulset name: StatefulSet full-link: /docs/concepts/workloads/controllers/statefulset/ aka: - PetSet related: - deployment - pod"} {"_id":"q-en-website-d1a4ed3e179ba7b3980e382ea464fede9d9e7bb8c328583a1396479e92f33e2d","text":"If you want to use minikube again to learn more about Kubernetes, you don't need to delete it. ## Conclusion This page covered the basic aspects to get a minikube cluster up and running. You are now ready to deploy applications. ## {{% heading \"whatsnext\" %}}"} {"_id":"q-en-website-d24f9d5521b348e9d7cf7d8fa77e98556c8c2250b5273636456ac0f0d4fe5113","text":"`Pending` | The Pod has been accepted by the Kubernetes cluster, but one or more of the containers has not been set up and made ready to run. This includes time a Pod spends waiting to be scheduled as well as the time spent downloading container images over the network. `Running` | The Pod has been bound to a node, and all of the containers have been created. At least one container is still running, or is in the process of starting or restarting. `Succeeded` | All containers in the Pod have terminated in success, and will not be restarted. `Failed` | All containers in the Pod have terminated, and at least one container has terminated in failure. That is, the container either exited with non-zero status or was terminated by the system. `Failed` | All containers in the Pod have terminated, and at least one container has terminated in failure. That is, the container either exited with non-zero status or was terminated by the system, and is not set for automatic restarting. `Unknown` | For some reason the state of the Pod could not be obtained. This phase typically occurs due to an error in communicating with the node where the Pod should be running. {{< note >}}"} {"_id":"q-en-website-d2c178b99abb3784cdcdde1c6da07af0dd056f73a2b2b073df14db3906104b1f","text":"/docs/reference/generated/kube-scheduler/ /docs/reference/command-line-tools-reference/kube-scheduler/ 301 /docs/reference/generated/kubectl/kubectl-options/ /docs/reference/kubectl/kubectl/ 301 /docs/reference/generated/kubectl/kubectl/ /docs/reference/generated/kubectl/kubectl-commands/ 301 /docs/reference/generated/kubectl/kubectl/kubectl_*.md /docs/reference/generated/kubectl/kubectl-commands#:splat 301 /docs/reference/generated/kubectl/kubectl/kubectl_* /docs/reference/generated/kubectl/kubectl-commands#:splat 301 /docs/reference/glossary/maintainer/ /docs/reference/glossary/approver/ 301 /docs/reference/kubectl/kubectl-cmds/ /docs/reference/generated/kubectl/kubectl-commands/ 301! /docs/reference/kubectl/kubectl/kubectl_*.md /docs/reference/generated/kubectl/kubectl-commands#:splat 301 /docs/reference/kubectl/kubectl/kubectl_* /docs/reference/generated/kubectl/kubectl-commands#:splat 301 /docs/reference/scheduling/profiles/ /docs/reference/scheduling/config/#profiles 301 /docs/reference/generated/kubernetes-api/v1.15/ https://v1-15.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.15/ 301"} {"_id":"q-en-website-d505812049817cab7ce67927bb3c62cbc6e46f47c8c9df8ce8c54afff3305757","text":"--> ### 仅在某些节点上运行 Pod 如果指定了 `.spec.template.spec.nodeSelector`,DaemonSet Controller 将在能够与 [Node Selector](/zh/docs/concepts/scheduling-eviction/assign-pod-node/) 匹配的节点上创建 Pod。类似这种情况,可以指定 `.spec.template.spec.affinity`,然后 DaemonSet Controller 将在能够与 [node Affinity](/zh/docs/concepts/scheduling-eviction/assign-pod-node/) 匹配的节点上创建 Pod。 如果指定了 `.spec.template.spec.nodeSelector`,DaemonSet 控制器将在能够与 [Node 选择算符](/zh/docs/concepts/scheduling-eviction/assign-pod-node/) 匹配的节点上创建 Pod。 类似这种情况,可以指定 `.spec.template.spec.affinity`,之后 DaemonSet 控制器 将在能够与[节点亲和性](/zh/docs/concepts/scheduling-eviction/assign-pod-node/) 匹配的节点上创建 Pod。 如果根本就没有指定,则 DaemonSet Controller 将在所有节点上创建 Pod。 不推荐使用 `run-pod/v1` 以外的其他生成器。
不推荐使用 `run-pod/v1` 以外的其他生成器. {{< /note >}} **作者:** Xing Yang (VMware) 最初在 1.19 中引入的 CSI 卷健康监控功能在 1.21 版本中进行了大规模更新。 ## 为什么要向 Kubernetes 添加卷健康监控? 如果没有卷健康监控,在 PVC 被 Pod 配置和使用后,Kubernetes 将不知道存储系统的底层卷的状态。 在 Kubernetes 中配置卷后,底层存储系统可能会发生很多事情。 例如,卷可能在 Kubernetes 之外被意外删除、卷所在的磁盘可能发生故障、容量不足、磁盘可能被降级而影响其性能等等。 即使卷被挂载到 Pod 上并被应用程序使用,以后也可能会出现诸如读/写 I/O 错误、文件系统损坏、在 Kubernetes 之外被意外卸载卷等问题。 当发生这样的事情时,调试和检测根本原因是非常困难的。 卷健康监控对 Kubernetes 用户非常有益。 它可以与 CSI 驱动程序通信以检索到底层存储系统检测到的错误。 用户可以收到报告上来的 PVC 事件继而采取行动。 例如,如果卷容量不足,他们可以请求卷扩展以获得更多空间。 ## 什么是卷健康监控? CSI 卷健康监控允许 CSI 驱动程序检测来自底层存储系统的异常卷状况,并将其作为 PVC 或 Pod 上的事件报送。 监控卷和使用卷健康信息报送事件的 Kubernetes 组件包括: * Kubelet 除了收集现有的卷统计信息外,还将观察该节点上 PVC 的卷健康状况。 如果 PVC 的健康状况异常,则会在使用 PVC 的 Pod 对象上报送事件。 如果多个 Pod 使用相同的 PVC,则将在使用该 PVC 的所有 Pod 上报送事件。 * 一个[外部卷健康监视控制器](https://github.com/kubernetes-csi/external-health-monitor)监视 PVC 的卷健康并报告 PVC 上的事件。 请注意,在 Kubernetes 1.19 版本中首次引入此功能时,节点侧卷健康监控逻辑是一个外部代理。 在 Kubernetes 1.21 中,节点侧卷健康监控逻辑从外部代理移至 Kubelet,以避免 CSI 函数重复调用。 随着 1.21 中的这一变化,为 Kubelet 中的卷健康监控逻辑引入了一个新的 alpha [特性门](/zh-cn/docs/reference/command-line-tools-reference/feature-gates/) `CSIVolumeHealth`。 目前,卷健康监控功能仅供参考,因为它只报送 PVC 或 Pod 上的异常卷健康事件。 用户将需要检查这些事件并手动修复问题。 此功能可作为 Kubernetes 未来以编程方式检测和解决卷健康问题的基石。 ## 如何在 Kubernetes 集群上使用卷健康? 要使用卷健康功能,首先确保你使用的 CSI 驱动程序支持此功能。 请参阅此 [CSI 驱动程序文档](https://kubernetes-csi.github.io/docs/drivers.html)以了解哪些 CSI 驱动程序支持此功能。 要从节点侧启用卷健康监控,需要启用 alpha 特性门 `CSIVolumeHealth`。 如果 CSI 驱动程序支持控制器端的卷健康监控功能,则有关异常卷条件的事件将记录在 PVC 上。 如果 CSI 驱动程序支持控制器端的卷健康监控功能, 当部署外部健康监控控制器时 `enable-node-watcher` 标志设置为 true,用户还可以获得有关节点故障的事件。 当检测到节点故障事件时,会在 PVC 上报送一个事件,指示使用该 PVC 的 Pod 在故障节点上。 如果 CSI 驱动程序支持节点端的卷健康监控功能,则有关异常卷条件的事件将使用 PVC 记录在 Pod 上。 ## 作为存储供应商,如何向 CSI 驱动程序添加对卷健康的支持? 卷健康监控包括两个部分: * 外部卷健康监控控制器从控制器端监控卷健康。 * Kubelet 从节点端监控卷的健康状况。 有关详细信息,请参阅 [CSI 规约](https://github.com/container-storage-interface/spec/blob/master/spec.md) 和 [Kubernetes-CSI 驱动开发者指南](https://kubernetes-csi.github.io/docs/volume-health-monitor.html)。 [CSI 主机路径驱动程序](https://github.com/kubernetes-csi/csi-driver-host-path)中有一个卷健康的示例实现。 ### 控制器端卷健康监控 要了解如何部署外部卷健康监控控制器, 请参阅 CSI 文档中的 [CSI external-health-monitor-controller](https://kubernetes-csi.github.io/docs/external-health-monitor-controller.html)。 如果检测到异常卷条件, 外部健康监视器控制器调用 `ListVolumes` 或者 `ControllerGetVolume` CSI RPC 并报送 VolumeConditionAbnormal 事件以及 PVC 上的消息。 只有具有 `LIST_VOLUMES` 和 `VOLUME_CONDITION` 控制器能力、 或者具有 `GET_VOLUME` 和 `VOLUME_CONDITION` 能力的 CSI 驱动程序才支持外部控制器中的卷健康监控。 要从控制器端实现卷健康功能,CSI 驱动程序**必须**添加对新控制器功能的支持。 如果 CSI 驱动程序支持 `LIST_VOLUMES` 和 `VOLUME_CONDITION` 控制器功能,它**必须**实现控制器 RPC `ListVolumes` 并在响应中报送卷状况。 如果 CSI 驱动程序支持 `GET_VOLUME` 和 `VOLUME_CONDITION` 控制器功能,它**必须**实现控制器 PRC `ControllerGetVolume` 并在响应中报送卷状况。 如果 CSI 驱动程序支持 `LIST_VOLUMES`、`GET_VOLUME` 和 `VOLUME_CONDITION` 控制器功能,则外部健康监视控制器将仅调用 `ListVolumes` CSI RPC。 ### 节点侧卷健康监控 如果检测到异常的卷条件, Kubelet 会调用 `NodeGetVolumeStats` CSI RPC 并报送 VolumeConditionAbnormal 事件以及 Pod 上的信息。 只有具有 `VOLUME_CONDITION` 节点功能的 CSI 驱动程序才支持 Kubelet 中的卷健康监控。 要从节点端实现卷健康功能,CSI 驱动程序**必须**添加对新节点功能的支持。 如果 CSI 驱动程序支持 `VOLUME_CONDITION` 节点能力,它**必须**在节点 RPC `NodeGetVoumeStats` 中报送卷状况。 ## 下一步是什么? 根据反馈和采纳情况,Kubernetes 团队计划在 1.22 或 1.23 中将 CSI 卷健康实施推向 beta。 我们还在探索如何在 Kubernetes 中使用卷健康信息进行编程检测和自动协调。 ## 如何了解更多? 要了解卷健康监控的设计细节,请阅读[卷健康监控](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/1432-volume-health-monitor)增强提案。 卷健康检测控制器源代码位于: [https://github.com/kubernetes-csi/external-health-monitor](https://github.com/kubernetes-csi/external-health-monitor)。 [容器存储接口文档](https://kubernetes-csi.github.io/docs/)中还有关于卷健康检查的更多详细信息。 ## 如何参与? [Kubernetes Slack 频道 #csi](https://kubernetes.slack.com/messages/csi) 和任何[标准 SIG Storage 通信频道](https://github.com/kubernetes/community/blob/master/sig-storage/README.md#contact)都是联系 SIG Storage 和 CSI 团队的绝佳媒介。 我们非常感谢在 1.21 中帮助发布此功能的贡献者。 我们要感谢 Yuquan Ren ([NickrenREN](https://github.com/nickrenren)) 在外部健康监控仓库中实现了初始卷健康监控控制器和代理, 感谢 Ran Xu ([fengzixu](https://github.com/fengzixu)) 在 1.21 中将卷健康监控逻辑从外部代理转移到 Kubelet, 我们特别感谢以下人员的深刻评论: David Ashpole ([dashpole](https://github.com/dashpole))、 Michelle Au ([msau42](https://github.com/msau42))、 David Eads ([deads2k](https://github.com/deads2k))、 Elana Hashman ([ehashman](https://github.com/ehashman))、 Seth Jennings ([sjenning](https://github.com/sjenning)) 和 Jiawei Wang ([Jiawei0227](https://github.com/Jiawei0227)) 那些有兴趣参与 CSI 或 Kubernetes 存储系统任何部分的设计和开发的人, 请加入 [Kubernetes Storage 特殊兴趣小组](https://github.com/kubernetes/community/tree/master/sig-storage)(SIG)。 我们正在迅速发展,并且欢迎新的贡献者。 "} {"_id":"q-en-website-d81c51e97ae9d2d102c40e7ac0302d4e6b699c272b3cb388a5e8fef6b917d829","text":" --- title: 调度器配置 content_type: concept weight: 20 --- {{< feature-state for_k8s_version=\"v1.19\" state=\"beta\" >}} 你可以通过编写配置文件,并将其路径传给 `kube-scheduler` 的命令行参数,定制 `kube-scheduler` 的行为。 你可以通过运行 `kube-scheduler --config ` 来设置调度配置, 配置文件使用组件配置的 API ([`v1alpha1`](https://pkg.go.dev/k8s.io/kube-scheduler@v0.18.0/config/v1alpha1?tab=doc#KubeSchedulerConfiguration) 或 [`v1alpha2`](https://pkg.go.dev/k8s.io/kube-scheduler@v0.18.0/config/v1alpha2?tab=doc#KubeSchedulerConfiguration))。 `v1alpha2` 可以配置 kube-scheduler 运行[多个配置文件](#multiple-profiles)。 最简单的配置如下: ```yaml apiVersion: kubescheduler.config.k8s.io/v1beta1 kind: KubeSchedulerConfiguration clientConnection: kubeconfig: /etc/srv/kubernetes/kube-scheduler/kubeconfig ``` ## 配置文件 {#profiles} 通过调度配置文件,你可以配置 {{< glossary_tooltip text=\"kube-scheduler\" term_id=\"kube-scheduler\" >}} 在不同阶段的调度行为。 每个阶段都在一个[扩展点](#extension-points)中公开。 [调度插件](#scheduling-plugins)通过实现一个或多个扩展点,来提供调度行为。 你可以配置同一 `kube-scheduler` 实例使用[多个配置文件](#multiple-profiles)。 ### 扩展点 {#extensions-points} 调度行为发生在一系列阶段中,这些阶段是通过以下扩展点公开的: 1. `QueueSort`:这些插件对调度队列中的悬决的 Pod 排序。 一次只能启用一个队列排序插件。 2. `PreFilter`:这些插件用于在过滤之前预处理或检查 Pod 或集群的信息。 它们可以将 Pod 标记为不可调度。 3. `Filter`:这些插件相当于调度策略中的断言(Predicates),用于过滤不能运行 Pod 的节点。 过滤器的调用顺序是可配置的。 如果没有一个节点通过所有过滤器的筛选,Pod 将会被标记为不可调度。 4. `PreScore`:这是一个信息扩展点,可用于预打分工作。 5. `Score`:这些插件给通过筛选阶段的节点打分。调度器会选择得分最高的节点。 6. `Reserve`:这是一个信息扩展点,当资源已经预留给 Pod 时,会通知插件。 这些插件还实现了 `Unreserve` 接口,在 `Reserve` 期间或之后出现故障时调用。 7. `Permit`:这些插件可以阻止或延迟 Pod 绑定。 8. `PreBind`:这些插件在 Pod 绑定节点之前执行。 9. `Bind`:这个插件将 Pod 与节点绑定。绑定插件是按顺序调用的,只要有一个插件完成了绑定,其余插件都会跳过。绑定插件至少需要一个。 10. `PostBind`:这是一个信息扩展点,在 Pod 绑定了节点之后调用。 对每个扩展点,你可以禁用[默认插件](#scheduling-plugins)或者是启用自己的插件,例如: ```yaml apiVersion: kubescheduler.config.k8s.io/v1beta1 kind: KubeSchedulerConfiguration profiles: - plugins: score: disabled: - name: NodeResourcesLeastAllocated enabled: - name: MyCustomPluginA weight: 2 - name: MyCustomPluginB weight: 1 ``` 你可以在 `disabled` 数组中使用 `*` 禁用该扩展点的所有默认插件。 如果需要,这个字段也可以用来对插件重新顺序。 ### 调度插件 {#scheduling-plugin} 1. `UnReserve`:这是一个信息扩展点,如果一个 Pod 在预留后被拒绝,并且被 `Permit` 插件搁置,它就会被调用。 ## 调度插件 {#scheduling-plugins} 下面默认启用的插件实现了一个或多个扩展点: - `SelectorSpread`:对于属于 {{< glossary_tooltip text=\"Services\" term_id=\"service\" >}}、 {{< glossary_tooltip text=\"ReplicaSets\" term_id=\"replica-set\" >}} 和 {{< glossary_tooltip text=\"StatefulSets\" term_id=\"statefulset\" >}} 的 Pod,偏好跨多个节点部署。 实现的扩展点:`PreScore`,`Score`。 - `ImageLocality`:选择已经存在 Pod 运行所需容器镜像的节点。 实现的扩展点:`Score`。 - `TaintToleration`:实现了[污点和容忍](/zh/docs/concepts/scheduling-eviction/taint-and-toleration/)。 实现的扩展点:`Filter`,`Prescore`,`Score`。 - `NodeName`:检查 Pod 指定的节点名称与当前节点是否匹配。 实现的扩展点:`Filter`。 - `NodePorts`:检查 Pod 请求的端口在节点上是否可用。 实现的扩展点:`PreFilter`,`Filter`。 - `NodePreferAvoidPods`:基于节点的 {{< glossary_tooltip text=\"注解\" term_id=\"annotation\" >}} `scheduler.alpha.kubernetes.io/preferAvoidPods` 打分。 实现的扩展点:`Score`。 - `NodeAffinity`:实现了[节点选择器](/zh/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector) 和[节点亲和性](/zh/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity)。 实现的扩展点:`Filter`,`Score`. - `PodTopologySpread`:实现了 [Pod 拓扑分布](/zh/docs/concepts/workloads/pods/pod-topology-spread-constraints/)。 实现的扩展点:`PreFilter`,`Filter`,`PreScore`,`Score`。 - `NodeUnschedulable`:过滤 `.spec.unschedulable` 值为 true 的节点。 实现的扩展点:`Filter`。 - `NodeResourcesFit`:检查节点是否拥有 Pod 请求的所有资源。 实现的扩展点:`PreFilter`,`Filter`。 - `NodeResourcesBalancedAllocation`:调度 Pod 时,选择资源使用更为均衡的节点。 实现的扩展点:`Score`。 - `NodeResourcesLeastAllocated`:选择资源分配较少的节点。 实现的扩展点:`Score`。 - `VolumeBinding`:检查节点是否有请求的卷,或是否可以绑定请求的卷。 实现的扩展点: `PreFilter`,`Filter`,`Reserve`,`PreBind`。 - `VolumeRestrictions`:检查挂载到节点上的卷是否满足卷提供程序的限制。 实现的扩展点:`Filter`。 - `VolumeZone`:检查请求的卷是否在任何区域都满足。 实现的扩展点:`Filter`。 - `NodeVolumeLimits`:检查该节点是否满足 CSI 卷限制。 实现的扩展点:`Filter`。 - `EBSLimits`:检查节点是否满足 AWS EBS 卷限制。 实现的扩展点:`Filter`。 - `GCEPDLimits`:检查该节点是否满足 GCP-PD 卷限制。 实现的扩展点:`Filter`。 - `AzureDiskLimits`:检查该节点是否满足 Azure 卷限制。 实现的扩展点:`Filter`。 - `InterPodAffinity`:实现 [Pod 间亲和性与反亲和性](/zh/docs/concepts/scheduling-eviction/assign-pod-node/#inter-pod-affinity-and-anti-affinity)。 实现的扩展点:`PreFilter`,`Filter`,`PreScore`,`Score`。 - `PrioritySort`:提供默认的基于优先级的排序。 实现的扩展点:`QueueSort`。 - `DefaultBinder`:提供默认的绑定机制。 实现的扩展点:`Bind`。 - `DefaultPreemption`:提供默认的抢占机制。 实现的扩展点:`PostFilter`。 你也可以通过组件配置 API 启用以下插件(默认不启用): - `NodeResourcesMostAllocated`:选择已分配资源多的节点。 实现的扩展点:`Score`。 - `RequestedToCapacityRatio`:根据已分配资源的某函数设置选择节点。 实现的扩展点:`Score`。 - `NodeResourceLimits`:选择满足 Pod 资源限制的节点。 实现的扩展点:`PreScore`,`Score`。 - `CinderVolume`:检查该节点是否满足 OpenStack Cinder 卷限制。 实现的扩展点:`Filter`。 - `NodeLabel`:根据配置的 {{< glossary_tooltip text=\"标签\" term_id=\"label\" >}} 过滤节点和/或给节点打分。 实现的扩展点:`Filter`,`Score`。 - `ServiceAffinity`:检查属于某个 {{< glossary_tooltip term_id=\"service\" >}} 的 Pod 与配置的标签所定义的节点集是否适配。 这个插件还支持将属于某个 Service 的 Pod 分散到各个节点。 实现的扩展点:`PreFilter`,`Filter`,`Score`。 ### 多配置文件 {#multiple-profiles} 你可以配置 `kube-scheduler` 运行多个配置文件。 每个配置文件都有一个关联的调度器名称,并且可以在其扩展点中配置一组不同的插件。 使用下面的配置样例,调度器将运行两个配置文件:一个使用默认插件,另一个禁用所有打分插件。 ```yaml apiVersion: kubescheduler.config.k8s.io/v1beta1 kind: KubeSchedulerConfiguration profiles: - schedulerName: default-scheduler - schedulerName: no-scoring-scheduler plugins: preScore: disabled: - name: '*' score: disabled: - name: '*' ``` 希望根据特定配置文件调度的 Pod,可以在 `.spec.schedulerName` 字段指定相应的调度器名称。 默认情况下,将创建一个名为 `default-scheduler` 的配置文件。 这个配置文件包括上面描述的所有默认插件。 声明多个配置文件时,每个配置文件中调度器名称必须唯一。 如果 Pod 未指定调度器名称,kube-apiserver 将会把它设置为 `default-scheduler`。 因此,应该存在一个名为 `default-scheduler` 的配置文件来调度这些 Pod。 {{< note >}} Pod 的调度事件把 `.spec.schedulerName` 字段值作为 ReportingController。 领导者选择事件使用列表中第一个配置文件的调度器名称。 {{< /note >}} {{< note >}} 所有配置文件必须在 QueueSort 扩展点使用相同的插件,并具有相同的配置参数(如果适用)。 这是因为调度器只有一个的队列保存悬决的 Pod。 {{< /note >}} ## {{% heading \"whatsnext\" %}} * 阅读 [kube-scheduler 参考](/zh/docs/reference/command-line-tools-reference/kube-scheduler/) * 了解[调度](/zh/docs/concepts/scheduling-eviction/kube-scheduler/) No newline at end of file"} {"_id":"q-en-website-d92eed0afe691b58b59d93fec9a9244e2853ed0d2e21855e37b31b0cdc8ec75d","text":"{{< codenew file=\"service/networking/network-policy-default-deny-egress.yaml\" >}} This ensures that even pods that aren't selected by any other NetworkPolicy will not be allowed egress traffic. This policy does not change the default ingress isolation behavior. change the ingress isolation behavior of any pod. ### Default allow all egress traffic ### Allow all egress traffic If you want to allow all traffic from all pods in a namespace (even if policies are added that cause some pods to be treated as \"isolated\"), you can create a policy that explicitly allows all egress traffic in that namespace. If you want to allow all connections from all pods in a namespace, you can create a policy that explicitly allows all outgoing connections from pods in that namespace. {{< codenew file=\"service/networking/network-policy-allow-all-egress.yaml\" >}} With this policy in place, no additional policy or policies can cause any outgoing connection from those pods to be denied. This policy has no effect on isolation for ingress to any pod. ### Default deny all ingress and all egress traffic You can create a \"default\" policy for a namespace which prevents all ingress AND egress traffic by creating the following NetworkPolicy in that namespace."} {"_id":"q-en-website-d9cdb5c7c2bc52f8eda762f8b72333bb8a03e61e8d6496173315e8e5312d002d","text":"```shell $ export SERVICE_IP=$(kubectl get service nginx-service -o go-template={% raw %}{{.spec.clusterIP}}{% endraw %}) $ export SERVICE_PORT=$(kubectl get service nginx-service -o go-template={% raw %}{{(index .spec.ports 0).port}}{% endraw %}) $ export SERVICE_PORT=$(kubectl get service nginx-service -o go-template='{% raw %}{{(index .spec.ports 0).port}}{% endraw %}') $ curl http://${SERVICE_IP}:${SERVICE_PORT} ```"} {"_id":"q-en-website-da6759f31f0507ffef9b6507a0f1e2dbf48b5a4f3460a11da3b92f9820f8672f","text":"Sebagai contoh, untuk menghasilan sebuah Secret dari _file-file_ `./username.txt` dan `./password.txt` ```shell # Membuat sebuah file kustomization.yaml dengan SecretGenerator # Membuat sebuah berkas kustomization.yaml dengan SecretGenerator cat <./kustomization.yaml secretGenerator: - name: db-user-pass"} {"_id":"q-en-website-dae613f261720754d87b568e7d31943a55f06339e8ce50da01cef93b5a4b4e3c","text":"--- title: CRIのインストール title: コンテナランタイム content_type: concept weight: 10 weight: 20 --- {{< feature-state for_k8s_version=\"v1.6\" state=\"stable\" >}} Podのコンテナを実行するために、Kubernetesはコンテナランタイムを使用します。 様々なランタイムのインストール手順は次のとおりです。 {{% dockershim-removal %}} クラスター内の各ノードがPodを実行できるようにするため、{{< glossary_tooltip text=\"コンテナランタイム\" term_id=\"container-runtime\" >}}をインストールする必要があります。 このページでは、ノードをセットアップするための概要と関連する作業について説明します。 Kubernetes {{< skew currentVersion >}}においては、{{< glossary_tooltip term_id=\"cri\" text=\"Container Runtime Interface\">}} (CRI)に準拠したランタイムを使用する必要があります。 {{< caution >}} コンテナ実行時にruncがシステムファイルディスクリプターを扱える脆弱性が見つかりました。 悪意のあるコンテナがこの脆弱性を利用してruncのバイナリを上書きし、 コンテナホストシステム上で任意のコマンドを実行する可能性があります。 詳しくは[サポートするCRIのバージョン](#cri-versions)をご覧ください。 この問題の更なる情報は[CVE-2019-5736](https://access.redhat.com/security/cve/cve-2019-5736)を参照してください。 {{< /caution >}} このページではいくつかの一般的なコンテナランタイムをKubernetesで使用する方法の概要を説明します。 ### 適用性 - [containerd](#containerd) - [CRI-O](#cri-o) - [Docker Engine](#docker) - [Mirantis Container Runtime](#mcr) {{< note >}} このドキュメントはLinuxにCRIをインストールするユーザーのために書かれています。 他のオペレーティングシステムの場合、プラットフォーム固有のドキュメントを見つけてください。 {{< /note >}} このガイドでは全てのコマンドを `root` で実行します。 例として、コマンドに `sudo` を付けたり、 `root` になってそのユーザーでコマンドを実行します。 ### Cgroupドライバー systemdがLinuxのディストリビューションのinitシステムとして選択されている場合、 initプロセスが作成され、rootコントロールグループ(`cgroup`)を使い、cgroupマネージャーとして行動します。 systemdはcgroupと密接に統合されており、プロセスごとにcgroupを割り当てます。 `cgroupfs` を使うように、あなたのコンテナランライムとkubeletを設定することができます。 systemdと一緒に `cgroupfs` を使用するということは、2つの異なるcgroupマネージャーがあることを意味します。 v1.24以前のKubernetesリリースでは、 _dockershim_ という名前のコンポーネントを使用したDocker Engineとの直接の統合が含まれていました。 この特別な直接統合は、もはやKubernetesの一部ではありません(この削除はv1.20リリースの一部として[発表](/blog/2020/12/08/kubernetes-1-20-release-announcement/#dockershim-deprecation)されています)。 dockershimの廃止がどのような影響を与えるかについては、[dockershim削除の影響範囲を確認する](/ja/docs/tasks/administer-cluster/migrating-from-dockershim/check-if-dockershim-removal-affects-you/) をご覧ください。 dockershimからの移行について知りたい場合、[dockershimからの移行](/ja/docs/tasks/administer-cluster/migrating-from-dockershim/)を参照してください。 コントロールグループはプロセスに割り当てられるリソースを制御するために使用されます。 単一のcgroupマネージャーは、割り当てられているリソースのビューを単純化し、 デフォルトでは使用可能なリソースと使用中のリソースについてより一貫性のあるビューになります。 2つのマネージャーがある場合、それらのリソースについて2つのビューが得られます。 kubeletとDockerに `cgroupfs` を使用し、ノード上で実行されている残りのプロセスに `systemd` を使用するように設定されたノードが、 リソース圧迫下で不安定になる場合があります。 コンテナランタイムとkubeletがcgroupドライバーとしてsystemdを使用するように設定を変更することでシステムは安定します。 以下のDocker設定の `native.cgroupdriver=systemd` オプションに注意してください。 v{{< skew currentVersion >}}以外のバージョンのKubernetesを実行している場合、そのバージョンのドキュメントを確認してください。 {{< /note >}} {{< caution >}} すでにクラスターに組み込まれているノードのcgroupドライバーを変更することは非常におすすめしません。 kubeletが一方のcgroupドライバーを使用してPodを作成した場合、コンテナランタイムを別のもう一方のcgroupドライバーに変更すると、そのような既存のPodのPodサンドボックスを再作成しようとするとエラーが発生する可能性があります。 kubeletを再起動しても問題は解決しないでしょう。 ワークロードからノードを縮退させ、クラスターから削除して再び組み込むことを推奨します。 {{< /caution >}} ## Docker ## インストールと設定の必須要件 それぞれのマシンに対してDockerをインストールします。 バージョン19.03.11が推奨されていますが、1.13.1、17.03、17.06、17.09、18.06、18.09についても動作が確認されています。 Kubernetesのリリースノートにある、Dockerの動作確認済み最新バージョンについてもご確認ください。 以下の手順では、全コンテナランタイムに共通の設定をLinux上のKubernetesノードに適用します。 システムへDockerをインストールするには、次のコマンドを実行します。 特定の設定が不要であることが分かっている場合、手順をスキップして頂いて構いません。 {{< tabs name=\"tab-cri-docker-installation\" >}} {{% tab name=\"Ubuntu 16.04+\" %}} 詳細については、[Network Plugin Requirements](/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/#network-plugin-requirements)または、特定のコンテナランタイムのドキュメントを参照してください。 ```shell # (Install Docker CE) ## リポジトリをセットアップ ### HTTPS越しのリポジトリの使用をaptに許可するために、パッケージをインストール apt-get update && apt-get install -y apt-transport-https ca-certificates curl software-properties-common gnupg2 ``` ### IPv4フォワーディングを有効化し、iptablesからブリッジされたトラフィックを見えるようにする ```shell # Docker公式のGPG鍵を追加: curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - ``` 以下のコマンドを実行します。 ```shell # Dockerのaptレポジトリを追加: add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" ``` ```bash cat < ```shell # Docker CEのインストール apt-get update && apt-get install -y containerd.io=1.2.13-2 docker-ce=5:19.03.11~3-0~ubuntu-$(lsb_release -cs) docker-ce-cli=5:19.03.11~3-0~ubuntu-$(lsb_release -cs) ``` sudo modprobe overlay sudo modprobe br_netfilter ```shell # デーモンをセットアップ cat > /etc/docker/daemon.json < # この構成に必要なカーネルパラメーター、再起動しても値は永続します cat < EOF ``` ```shell mkdir -p /etc/systemd/system/docker.service.d # 再起動せずにカーネルパラメーターを適用 sudo sysctl --system ``` ```shell # dockerを再起動 systemctl daemon-reload systemctl restart docker ``` {{% /tab %}} {{% tab name=\"CentOS/RHEL 7.4+\" %}} 以下のコマンドを実行して`br_netfilter`と`overlay`モジュールが読み込まれていることを確認してください。 ```shell # (Docker CEのインストール) ## リポジトリをセットアップ ### 必要なパッケージのインストール yum install -y yum-utils device-mapper-persistent-data lvm2 ```bash lsmod | grep br_netfilter lsmod | grep overlay ``` ```shell ## Dockerリポジトリの追加 yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo ``` 以下のコマンドを実行して、`net.bridge.bridge-nf-call-iptables`、`net.bridge.bridge-nf-call-ip6tables`、`net.ipv4.ip_forward`カーネルパラメーターが1に設定されていることを確認します。 ```shell ## Docker CEのインストール yum update -y && yum install -y containerd.io-1.2.13 docker-ce-19.03.11 docker-ce-cli-19.03.11 ```bash sysctl net.bridge.bridge-nf-call-iptables net.bridge.bridge-nf-call-ip6tables net.ipv4.ip_forward ``` ```shell ## /etc/docker ディレクトリを作成 mkdir /etc/docker ``` ## cgroupドライバー {#cgroup-drivers} ```shell # デーモンをセットアップ cat > /etc/docker/daemon.json < Linuxでは、プロセスに割り当てられるリソースを制約するために{{< glossary_tooltip text=\"cgroup\" term_id=\"cgroup\" >}}が使用されます。 ```shell mkdir -p /etc/systemd/system/docker.service.d ``` {{< glossary_tooltip text=\"kubelet\" term_id=\"kubelet\" >}}と基盤となるコンテナランタイムは、[コンテナのリソース管理](/ja/docs/concepts/configuration/manage-resources-containers/)を実施し、CPU/メモリーの要求や制限などのリソースを設定するため、cgroupとインターフェースする必要があります。 cgroupとインターフェースするために、kubeletおよびコンテナランタイムは*cgroupドライバー*を使用する必要があります。 この際、kubeletとコンテナランタイムが同一のcgroupドライバーを使用し、同一の設定を適用することが不可欠となります。 ```shell # dockerを再起動 systemctl daemon-reload systemctl restart docker ``` {{% /tab %}} {{< /tabs >}} 利用可能なcgroupドライバーは以下の2つです。 ブート時にDockerサービスを開始させたい場合は、以下のコマンドを入力してください: * [`cgroupfs`](#cgroupfs-cgroup-driver) * [`systemd`](#systemd-cgroup-driver) ```shell sudo systemctl enable docker ``` ### cgroupfsドライバー {#cgroupfs-cgroup-driver} 詳細については、[Dockerの公式インストールガイド](https://docs.docker.com/engine/installation/)を参照してください。 `cgroupfs`ドライバーは、kubeletのデフォルトのcgroupドライバーです。 `cgroupfs`ドライバーを使用すると、kubeletとコンテナランタイムはcgroupファイルシステムと直接インターフェイスし、cgroupを設定します。 ## CRI-O [systemd](https://www.freedesktop.org/wiki/Software/systemd/)がinitシステムである場合、`cgroupfs`ドライバーは推奨**されません**。 なぜなら、systemdはシステム上のcgroupマネージャーが単一であると想定しているからです。 また、[cgroup v2](/ja/docs/concepts/architecture/cgroups)を使用している場合は、`cgroupfs`の代わりに`systemd` cgroupドライバーを使用してください。 このセクションでは、CRIランタイムとして`CRI-O`を利用するために必要な手順について説明します。 ### systemd cgroupドライバー {#systemd-cgroup-driver} システムへCRI-Oをインストールするためには以下のコマンドを利用します: Linuxディストリビューションのinitシステムに[systemd](https://www.freedesktop.org/wiki/Software/systemd/)が選択されている場合、 initプロセスはルートcgroupを生成・消費し、cgroupマネージャーとして動作します。 {{< note >}} CRI-OのメジャーとマイナーバージョンはKubernetesのメジャーとマイナーバージョンと一致しなければなりません。 詳細は[CRI-O互換性表](https://github.com/cri-o/cri-o)を参照してください。 {{< /note >}} systemdはcgroupと密接に連携しており、systemdユニットごとにcgroupを割り当てます。 その結果、initシステムに`systemd`を使用した状態で`cgroupfs`ドライバーを使用すると、 システムには2つの異なるcgroupマネージャーが存在することになります。 ### 事前準備 2つのcgroupマネージャーが存在することで、システムで利用可能なリソースおよび使用中のリソースに、2つの異なる見え方が与えられることになります。 特定の場合において、kubeletとコンテナランタイムに`cgroupfs`を、残りのプロセスに`systemd`を使用するように設定されたノードが高負荷時に不安定になることがあります。 ```shell modprobe overlay modprobe br_netfilter このような不安定性を緩和するためのアプローチは、systemdがinitシステムに採用されている場合にkubeletとコンテナランタイムのcgroupドライバーとして`systemd`を使用することです。 # 必要なカーネルパラメータの設定をします。これらの設定値は再起動後も永続化されます。 cat > /etc/sysctl.d/99-kubernetes-cri.conf < cgroupドライバーに`systemd`を設定するには、以下のように[`KubeletConfiguration`](/docs/tasks/administer-cluster/kubelet-config-file/)の`cgroupDriver`オプションを編集して`systemd`を設定します。 sysctl --system ```yaml apiVersion: kubelet.config.k8s.io/v1beta1 kind: KubeletConfiguration ... cgroupDriver: systemd ``` {{< tabs name=\"tab-cri-cri-o-installation\" >}} {{% tab name=\"Debian\" %}} kubelet用のcgroupドライバーとして`systemd`を設定する場合、コンテナランタイムのcgroupドライバーにも`systemd`を設定する必要があります。 具体的な手順については、以下のリンクなどの、お使いのコンテナランタイムのドキュメントを参照してください。 CRI-Oを以下のOSにインストールするには、環境変数$OSを以下の表の適切なフィールドに設定します。 * [containerd](#containerd-systemd) * [CRI-O](#cri-o) | Operating system | $OS | | ---------------- | ----------------- | | Debian Unstable | `Debian_Unstable` | | Debian Testing | `Debian_Testing` | {{< caution >}} クラスターに参加したノードのcgroupドライバーを変更するのはデリケートな操作です。 kubeletが特定のcgroupドライバーのセマンティクスを使用してPodを作成していた場合、 コンテナランタイムを別のcgroupドライバーに変更すると、そのような既存のPodに対してPodサンドボックスを再作成しようとしたときにエラーが発生することがあります。 kubeletを再起動してもこのようなエラーは解決しない可能性があります。
そして、`$VERSION`にKubernetesのバージョンに合わせたCRI-Oのバージョンを設定します。例えば、CRI-O 1.18をインストールしたい場合は、`VERSION=1.18` を設定します。インストールを特定のリリースに固定することができます。バージョン 1.18.3をインストールするには、`VERSION=1.18:1.18.3` を設定します。
もしあなたが適切な自動化の手段を持っているのであれば、更新された設定を使用してノードを別のノードに置き換えるか、自動化を使用して再インストールを行ってください。 {{< /caution >}} 以下を実行します。 ```shell echo \"deb https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/$OS/ /\" > /etc/apt/sources.list.d/devel:kubic:libcontainers:stable.list echo \"deb http://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable:/cri-o:/$VERSION/$OS/ /\" > /etc/apt/sources.list.d/devel:kubic:libcontainers:stable:cri-o:$VERSION.list ### kubeadmで管理されたクラスターでの`systemd`ドライバーへの移行 curl -L https://download.opensuse.org/repositories/devel:kubic:libcontainers:stable:cri-o:$VERSION/$OS/Release.key | apt-key add - curl -L https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/$OS/Release.key | apt-key add - 既存のkubeadm管理クラスターで`systemd` cgroupドライバーに移行したい場合は、[cgroupドライバーの設定](/ja/docs/tasks/administer-cluster/kubeadm/configure-cgroup-driver/)に従ってください。 apt-get update apt-get install cri-o cri-o-runc ``` ## サポートするCRIのバージョン {#cri-versions} {{% /tab %}} コンテナランタイムは、Container Runtime Interfaceのv1alpha2以上をサポートする必要があります。 {{% tab name=\"Ubuntu\" %}} Kubernetes {{< skew currentVersion >}}は、デフォルトでCRI APIのv1を使用します。 コンテナランタイムがv1 APIをサポートしていない場合、kubeletは代わりに(非推奨の)v1alpha2 APIにフォールバックします。 CRI-Oを以下のOSにインストールするには、環境変数$OSを以下の表の適切なフィールドに設定します。 ## コンテナランタイム {#container-runtimes} | Operating system | $OS | | ---------------- | ----------------- | | Ubuntu 20.04 | `xUbuntu_20.04` | | Ubuntu 19.10 | `xUbuntu_19.10` | | Ubuntu 19.04 | `xUbuntu_19.04` | | Ubuntu 18.04 | `xUbuntu_18.04` | {{% thirdparty-content %}}
次に、`$VERSION`をKubernetesのバージョンと一致するCRI-Oのバージョンに設定します。例えば、CRI-O 1.18をインストールしたい場合は、`VERSION=1.18` を設定します。インストールを特定のリリースに固定することができます。バージョン 1.18.3 をインストールするには、`VERSION=1.18:1.18.3` を設定します。
### containerd 以下を実行します。 ```shell echo \"deb https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/$OS/ /\" > /etc/apt/sources.list.d/devel:kubic:libcontainers:stable.list echo \"deb http://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable:/cri-o:/$VERSION/$OS/ /\" > /etc/apt/sources.list.d/devel:kubic:libcontainers:stable:cri-o:$VERSION.list このセクションでは、CRIランタイムとしてcontainerdを使用するために必要な手順の概要を説明します。 curl -L https://download.opensuse.org/repositories/devel:kubic:libcontainers:stable:cri-o:$VERSION/$OS/Release.key | apt-key add - curl -L https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/$OS/Release.key | apt-key add - 以下のコマンドを使用して、システムにcontainerdをインストールします: apt-get update apt-get install cri-o cri-o-runc ``` {{% /tab %}} まずは[containerdの使用を開始する](https://github.com/containerd/containerd/blob/main/docs/getting-started.md)の指示に従ってください。有効な`config.toml`設定ファイルを作成したら、このステップに戻ります。 {{% tab name=\"CentOS\" %}} {{< tabs name=\"Finding your config.toml file\" >}} {{% tab name=\"Linux\" %}} このファイルはパス`/etc/containerd/config.toml`にあります。 {{% /tab %}} {{% tab name=\"Windows\" %}} このファイルは`C:Program Filescontainerdconfig.toml`にあります。 {{% /tab %}} {{< /tabs >}} CRI-Oを以下のOSにインストールするには、環境変数$OSを以下の表の適切なフィールドに設定します。 Linuxでは、containerd用のデフォルトのCRIソケットは`/run/containerd/containerd.sock`です。 Windowsでは、デフォルトのCRIエンドポイントは`npipe://./pipe/containerd-containerd`です。 | Operating system | $OS | | ---------------- | ----------------- | | Centos 8 | `CentOS_8` | | Centos 8 Stream | `CentOS_8_Stream` | | Centos 7 | `CentOS_7` | #### `systemd` cgroupドライバーを構成する
次に、`$VERSION`をKubernetesのバージョンと一致するCRI-Oのバージョンに設定します。例えば、CRI-O 1.18 をインストールしたい場合は、`VERSION=1.18` を設定します。インストールを特定のリリースに固定することができます。バージョン 1.18.3 をインストールするには、`VERSION=1.18:1.18.3` を設定します。
`/etc/containerd/config.toml`内で`runc`が`systemd` cgroupドライバーを使うようにするには、次のように設定します。 以下を実行します。 ```shell curl -L -o /etc/yum.repos.d/devel:kubic:libcontainers:stable.repo https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/$OS/devel:kubic:libcontainers:stable.repo curl -L -o /etc/yum.repos.d/devel:kubic:libcontainers:stable:cri-o:$VERSION.repo https://download.opensuse.org/repositories/devel:kubic:libcontainers:stable:cri-o:$VERSION/$OS/devel:kubic:libcontainers:stable:cri-o:$VERSION.repo yum install cri-o ``` [plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc] ... [plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc.options] SystemdCgroup = true ``` {{% /tab %}} {{% tab name=\"openSUSE Tumbleweed\" %}} [cgroup v2](/ja/docs/concepts/architecture/cgroups)を使用する場合は`systemd` cgroupドライバーの利用を推奨します。 ```shell sudo zypper install cri-o ``` {{% /tab %}} {{% tab name=\"Fedora\" %}} {{< note >}} パッケージ(RPMや`.deb`など)からcontainerdをインストールした場合、 CRI統合プラグインがデフォルトで無効になっていることがあります。 Kubernetesでcontainerdを使用するには、CRIサポートを有効にする必要があります。 `/etc/containerd/config.toml`内の`disabled_plugins`リストに`cri`が含まれていないことを確認してください。 このファイルを変更した場合、`containerd`も再起動してください。 クラスターの初回構築後、またはCNIをインストールした後にコンテナのクラッシュループが発生した場合、 パッケージと共に提供されるcontainerdの設定に互換性のないパラメーターが含まれている可能性があります。 [get-started.md](https://github.com/containerd/containerd/blob/main/docs/getting-started.md#advanced-topics)にあるように、 `containerd config default > /etc/containerd/config.toml`でcontainerdの設定をリセットした上で、 上記の設定パラメーターを使用することを検討してください。 {{< /note >}} $VERSIONには、Kubernetesのバージョンと一致するCRI-Oのバージョンを設定します。例えば、CRI-O 1.18をインストールしたい場合は、$VERSION=1.18を設定します。 以下のコマンドで、利用可能なバージョンを見つけることができます。 ```shell dnf module list cri-o ``` CRI-OはFedoraの特定のリリースにピン留めすることをサポートしていません。 この変更を適用した場合、必ずcontainerdを再起動してください。 以下を実行します。 ```shell dnf module enable cri-o:$VERSION dnf install cri-o sudo systemctl restart containerd ``` {{% /tab %}} {{< /tabs >}} kubeadmを使用している場合、手動で[kubelet cgroupドライバーの設定](/ja/docs/tasks/administer-cluster/kubeadm/configure-cgroup-driver/#configuring-the-kubelet-cgroup-driver)を行ってください。 #### サンドボックス(pause)イメージの上書き {#override-pause-image-containerd} ### CRI-Oの起動 [containerdの設定](https://github.com/containerd/containerd/blob/main/docs/cri/config.md)で以下の設定をすることで、サンドボックスのイメージを上書きすることができます。 ```shell systemctl daemon-reload systemctl start crio ```toml [plugins.\"io.containerd.grpc.v1.cri\"] sandbox_image = \"registry.k8s.io/pause:3.2\" ``` 詳細については、[CRI-Oインストールガイド](https://github.com/kubernetes-sigs/cri-o#getting-started)を参照してください。 この場合も、設定ファイルの更新後に`systemctl restart containerd`を実行して`containerd`も再起動する必要があるでしょう。 ## Containerd ### CRI-O このセクションでは、CRIランタイムとして`containerd`を利用するために必要な手順について説明します。 本セクションでは、コンテナランタイムとしてCRI-Oをインストールするために必要な手順を説明します。 システムへContainerdをインストールするためには次のコマンドを実行します。 CRI-Oをインストールするには、[CRI-Oのインストール手順](https://github.com/cri-o/cri-o/blob/main/install.md#readme)に従ってください。 ### 必要な設定の追加 #### cgroupドライバー ```shell cat > /etc/modules-load.d/containerd.conf < CRI-Oはデフォルトでsystemd cgroupドライバーを使用し、おそらく問題なく動作します。 `cgroupfs` cgroupドライバーに切り替えるには、`/etc/crio/crio.conf` を編集するか、 `/etc/crio/crio.conf.d/02-cgroup-manager.conf`にドロップイン設定ファイルを置いて、以下のような設定を記述してください。 # 必要なカーネルパラメータの設定をします。これらの設定値は再起動後も永続化されます。 cat > /etc/sysctl.d/99-kubernetes-cri.conf < ```toml [crio.runtime] conmon_cgroup = \"pod\" cgroup_manager = \"cgroupfs\" ``` ### containerdのインストール 上記で`conmon_cgroup`も変更されていることに注意してください。 CRI-Oで`cgroupfs`を使用する場合、ここには`pod`という値を設定する必要があります。 一般に、kubeletのcgroupドライバーの設定(通常はkubeadmによって行われます)とCRI-Oの設定は一致させる必要があります。 {{< tabs name=\"tab-cri-containerd-installation\" >}} {{% tab name=\"Ubuntu 16.04\" %}} CRI-Oの場合、CRIソケットはデフォルトで`/var/run/crio/crio.sock`となります。 ```shell # (containerdのインストール) ## リポジトリの設定 ### HTTPS越しのリポジトリの使用をaptに許可するために、パッケージをインストール apt-get update && apt-get install -y apt-transport-https ca-certificates curl software-properties-common ``` #### サンドボックス(pause)イメージの上書き {#override-pause-image-cri-o} ```shell ## Docker公式のGPG鍵を追加 curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - ``` [CRI-Oの設定](https://github.com/cri-o/cri-o/blob/main/docs/crio.conf.5.md)において、以下の値を設定することができます。 ```shell ## Dockerのaptリポジトリの追加 add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" ```toml [crio.image] pause_image=\"registry.k8s.io/pause:3.6\" ``` ```shell ## containerdのインストール apt-get update && apt-get install -y containerd.io ``` このオプションはライブ設定リロードによる変更の適用に対応しています。 `systemctl reload crio`または`crio`プロセスに`SIGHUP`を送信することで変更を適用できます。 ```shell # containerdの設定 mkdir -p /etc/containerd containerd config default | sudo tee /etc/containerd/config.toml ``` ### Docker Engine {#docker} ```shell # containerdの再起動 systemctl restart containerd ``` {{% /tab %}} {{% tab name=\"CentOS/RHEL 7.4+\" %}} {{< note >}} この手順では、Docker EngineとKubernetesを統合するために[`cri-dockerd`](https://github.com/Mirantis/cri-dockerd)アダプターを使用することを想定しています。 {{< /note >}} ```shell # (containerdのインストール) ## リポジトリの設定 ### 必要なパッケージのインストール yum install -y yum-utils device-mapper-persistent-data lvm2 ``` 1. 各ノードに、使用しているLinuxディストリビューション用のDockerを[Docker Engineのインストール](https://docs.docker.com/engine/install/#server)に従ってインストールします。 ```shell ## Dockerのリポジトリの追加 yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo ``` 2. [`cri-dockerd`](https://github.com/Mirantis/cri-dockerd)をリポジトリ内の指示に従ってインストールします。 ```shell ## containerdのインストール yum update -y && yum install -y containerd.io ``` `cri-dockerd`の場合、CRIソケットはデフォルトで`/run/cri-dockerd.sock`になります。 ```shell ## containerdの設定 mkdir -p /etc/containerd containerd config default | sudo tee /etc/containerd/config.toml ``` ### Mirantis Container Runtime {#mcr} ```shell # containerdの再起動 systemctl restart containerd ``` {{% /tab %}} {{< /tabs >}} [Mirantis Container Runtime](https://docs.mirantis.com/mcr/20.10/overview.html)(MCR)は、 以前はDocker Enterprise Editionとして知られていた、商業的に利用可能なコンテナランタイムです。 MCRに含まれるオープンソースの[`cri-dockerd`](https://github.com/Mirantis/cri-dockerd)コンポーネントを使用することで、 Mirantis Container RuntimeをKubernetesで使用することができます。 ### systemd Mirantis Container Runtimeのインストール方法について知るには、[MCRデプロイガイド](https://docs.mirantis.com/mcr/20.10/install.html)を参照してください。 `systemd`のcgroupドライバーを使うには、`/etc/containerd/config.toml`内で`plugins.cri.systemd_cgroup = true`を設定してください。 kubeadmを使う場合は[kubeletのためのcgroupドライバー](/ja/docs/setup/production-environment/tools/kubeadm/install-kubeadm/#マスターノードのkubeletによって使用されるcgroupドライバーの設定)を手動で設定してください。 CRIソケットのパスを見つけるには、systemdの`cri-docker.socket`という名前のユニットを確認してください。 ## その他のCRIランタイム: frakti #### サンドボックス(pause)イメージを上書きする {#override-pause-image-cri-dockerd-mcr} 詳細については[Fraktiのクイックスタートガイド](https://github.com/kubernetes/frakti#quickstart)を参照してください。 `cri-dockerd`アダプターは、Podインフラコンテナ(\"pause image\")として使用するコンテナイメージを指定するためのコマンドライン引数を受け付けます。 使用するコマンドライン引数は `--pod-infra-container-image`です。 ## {{% heading \"whatsnext\" %}} コンテナランタイムに加えて、クラスターには動作する[ネットワークプラグイン](/ja/docs/concepts/cluster-administration/networking/#how-to-implement-the-kubernetes-network-model)が必要です。 "} {"_id":"q-en-website-dcbafd435be7ae51fc50ad80ff9989226bc7feb53df5258e674be504ff6cd1de","text":"The `dashboard` command enables the dashboard add-on and opens the proxy in the default web browser. You can create Kubernetes resources on the dashboard such as Deployment and Service. If you are running in an environment as root, see [Open Dashboard with URL](#open-dashboard-with-url). To find out how to avoid directly invoking the browser from the terminal and get a URL for the web dashboard, see the \"URL copy and paste\" tab. By default, the dashboard is only accessible from within the internal Kubernetes virtual network. The `dashboard` command creates a temporary proxy to make the dashboard accessible from outside the Kubernetes virtual network."} {"_id":"q-en-website-dda6aa6c344699a2863c92821168250cdfbfdf8df2b63cac047bde2fb2223162","text":" --- api_metadata: apiVersion: \"networking.k8s.io/v1\" import: \"k8s.io/api/networking/v1\" kind: \"IngressClass\" content_type: \"api_reference\" description: \"IngressClass 代表 Ingress 的类, 被 Ingress 的规约引用。\" title: \"IngressClass\" weight: 5 --- `apiVersion: networking.k8s.io/v1` `import \"k8s.io/api/networking/v1\"` ## IngressClass {#IngressClass} IngressClass 代表 Ingress 的类, 被 Ingress 的规约引用。 `ingressclass.kubernetes.io/is-default-class` 注解可以用来标明一个 IngressClass 应该被视为默认的 Ingress 类。 当某个 IngressClass 资源将此注解设置为 true 时, 没有指定类的新 Ingress 资源将被分配到此默认类。
- **apiVersion**: networking.k8s.io/v1 - **kind**: IngressClass - **metadata** (}}\">ObjectMeta) 标准的列表元数据。 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata - **spec** (}}\">IngressClassSpec) spec 是 IngressClass 的期望状态。更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status ## IngressClassSpec {#IngressClassSpec} IngressClassSpec 提供有关 Ingress 类的信息。
- **controller** (string) controller 是指应该处理此类的控制器名称。 这允许由同一控制器控制不同“口味”。例如,对于同一个实现的控制器你可能有不同的参数。 此字段应该指定为长度不超过 250 个字符的域前缀路径,例如 “acme.io/ingress-controller”。 该字段是不可变的。 - **parameters** (IngressClassParametersReference) parameters 是指向控制器中包含额外配置的自定义资源的链接。 如果控制器不需要额外的属性,这是可选的。 **IngressClassParametersReference 标识一个 API 对象。这可以用来指定一个集群或者命名空间范围的资源** - **parameters.kind** (string),必需 kind 是被引用资源的类型。 - **parameters.name** (string),必需 name 是被引用资源的名称。 - **parameters.apiGroup** (string) apiGroup 是被引用资源的组。 如果未指定 apiGroup,则被指定的 kind 必须在核心 API 组中。 对于任何其他第三方类型, APIGroup 是必需的。 - **parameters.namespace** (string) namespace 是被引用资源的命名空间。当范围被设置为 “namespace” 时,此字段是必需的,当范围被设置为 “Cluster”,此字段必须取消设置。 - **parameters.scope** (string) scope 表示是否引用集群或者命名空间范围的资源。 这可以设置为“集群”(默认)或者“命名空间”。 ## IngressClassList {#IngressClassList} IngressClassList 是 IngressClasses 的集合。
- **apiVersion**: networking.k8s.io/v1 - **kind**: IngressClassList - **metadata** (}}\">ListMeta) 标准的列表元数据。 - **items** ([]}}\">IngressClass),必需 items 是 IngressClasses 的列表 ## 操作 {#Operations}
### `get` 读取指定的 IngressClass #### HTTP 请求 GET /apis/networking.k8s.io/v1/ingressclasses/{name} #### 参数 - **name** (**路径参数**):string,必需 IngressClass 的名称 - **pretty** (**查询参数**):string }}\">pretty #### 响应 200 (}}\">IngressClass): OK 401: Unauthorized ### `list` 列出或监视 IngressClass 类型的对象 #### HTTP 请求 GET /apis/networking.k8s.io/v1/ingressclasses #### 参数 - **allowWatchBookmarks** (**查询参数**):boolean }}\">allowWatchBookmarks - **continue** (**查询参数**):string }}\">continue - **fieldSelector** (**查询参数**):string }}\">fieldSelector - **labelSelector** (**查询参数**):string }}\">labelSelector - **limit** (**查询参数**):integer }}\">limit - **pretty** (**查询参数**):string }}\">pretty - **resourceVersion** (**查询参数**):string }}\">resourceVersion - **resourceVersionMatch** (**查询参数**):string }}\">resourceVersionMatch - **timeoutSeconds** (**查询参数**):integer }}\">timeoutSeconds - **watch** (**查询参数**):boolean }}\">watch #### 响应 200 (}}\">IngressClassList): OK 401: Unauthorized ### `create` 创建一个 IngressClass #### HTTP 请求 POST /apis/networking.k8s.io/v1/ingressclasses #### 参数 - **body**: }}\">IngressClass,必需 - **dryRun** (**查询参数**):string }}\">dryRun - **fieldManager** (**查询参数**):string }}\">fieldManager - **fieldValidation** (**查询参数**):string }}\">fieldValidation - **pretty** (**查询参数**):string }}\">pretty #### 响应 200 (}}\">IngressClass): OK 201 (}}\">IngressClass): Created 202 (}}\">IngressClass): Accepted 401: Unauthorized ### `update` 替换指定的 IngressClass #### HTTP 请求 PUT /apis/networking.k8s.io/v1/ingressclasses/{name} #### 参数 - **name** (**路径参数**):string,必需 IngressClass 的名称 - **body**: }}\">IngressClass,必需 - **dryRun** (**查询参数**):string }}\">dryRun - **fieldManager** (**查询参数**):string }}\">fieldManager - **fieldValidation** (**查询参数**):string }}\">fieldValidation - **pretty** (**查询参数**):string }}\">pretty #### 响应 200 (}}\">IngressClass): OK 201 (}}\">IngressClass): Created 401: Unauthorized ### `patch` 部分更新指定的 IngressClass #### HTTP 请求 PATCH /apis/networking.k8s.io/v1/ingressclasses/{name} #### 参数 - **name** (**路径参数**):string,必需 IngressClass 的名称 - **body**: }}\">Patch,必需 - **dryRun** (**查询参数**):string }}\">dryRun - **fieldManager** (**查询参数**):string }}\">fieldManager - **fieldValidation** (**查询参数**):string }}\">fieldValidation - **force** (**查询参数**):boolean }}\">force - **pretty** (**查询参数**):string }}\">pretty #### 响应 200 (}}\">IngressClass): OK 201 (}}\">IngressClass): Created 401: Unauthorized ### `delete` 删除一个 IngressClass #### HTTP 请求 DELETE /apis/networking.k8s.io/v1/ingressclasses/{name} #### 参数 - **name** (**路径参数**):string,必需 IngressClass 的名称 - **body**: }}\">DeleteOptions - **dryRun** (**查询参数**):string }}\">dryRun - **gracePeriodSeconds** (**查询字符串**):integer }}\">gracePeriodSeconds - **pretty** (**查询参数**):string }}\">pretty - **propagationPolicy** (**查询参数**):string }}\">propagationPolicy #### 响应 200 (}}\">Status): OK 202 (}}\">Status): Accepted 401: Unauthorized ### `deletecollection` 删除 IngressClass 的集合 DELETE /apis/networking.k8s.io/v1/ingressclasses #### 参数 - **body**: }}\">DeleteOptions - **continue** (**查询参数**):string }}\">continue - **dryRun** (**查询参数**):string }}\">dryRun - **fieldSelector** (**查询参数**):string }}\">fieldSelector - **gracePeriodSeconds** (**查询字符串**):integer }}\">gracePeriodSeconds - **labelSelector** (**查询参数**):string }}\">labelSelector - **limit** (**查询参数**):integer }}\">limit - **pretty** (**查询参数**):string }}\">pretty - **propagationPolicy** (**查询参数**):string }}\">propagationPolicy - **resourceVersion** (**查询参数**):string }}\">resourceVersion - **resourceVersionMatch** (**查询参数**):string }}\">resourceVersionMatch - **timeoutSeconds** (**查询参数**):integer }}\">timeoutSeconds #### 响应 200 (}}\">Status): OK 401: Unauthorized
"} {"_id":"q-en-website-df698d4e20fbee6f8246a13da6ae41bf327aeb4f2f995f29dcc9a14f44850556","text":"Here are a few methods to install kubectl. ## Install kubectl Binary Via curl ## Install kubectl binary via curl Download the latest release with the command:"} {"_id":"q-en-website-df765e0cb2a3b4528acc86cac5a97a0ad41e8c73f5cd5c249dfa0a39f236ca1a","text":" --- title: ネットワークポリシーを宣言する min-kubernetes-server-version: v1.8 content_type: task --- このドキュメントでは、Pod同士の通信を制御するネットワークポリシーを定義するための、Kubernetesの[NetworkPolicy API](/docs/concepts/services-networking/network-policies/)を使い始める手助けをします。 ## {{% heading \"prerequisites\" %}} {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}} ネットワークポリシーをサポートしているネットワークプロバイダーが設定済みであることを確認してください。さまざまなネットワークプロバイダーがNetworkPolicyをサポートしています。次に挙げるのは一例です。 * [Calico](/docs/tasks/administer-cluster/network-policy-provider/calico-network-policy/) * [Cilium](/docs/tasks/administer-cluster/network-policy-provider/cilium-network-policy/) * [Kube-router](/docs/tasks/administer-cluster/network-policy-provider/kube-router-network-policy/) * [Romana](/docs/tasks/administer-cluster/network-policy-provider/romana-network-policy/) * [Weave Net](/docs/tasks/administer-cluster/network-policy-provider/weave-network-policy/) {{< note >}} 上記のリストは製品名のアルファベット順にソートされていて、推奨順や好ましい順にソートされているわけではありません。このページの例は、Kubernetesクラスターでこれらのどのプロバイダーを使用していても有効です。 {{< /note >}} ## `nginx` Deploymentを作成してService経由で公開する Kubernetesのネットワークポリシーの仕組みを理解するために、まずは`nginx` Deploymentを作成することから始めましょう。 ```console kubectl create deployment nginx --image=nginx ``` ```none deployment.apps/nginx created ``` `nginx`という名前のService経由でDeploymentを公開します。 ```console kubectl expose deployment nginx --port=80 ``` ```none service/nginx exposed ``` 上記のコマンドを実行すると、nginx Podを持つDeploymentが作成され、そのDeploymentが`nginx`という名前のService経由で公開されます。`nginx`のPodおよびDeploymentは`default`名前空間の中にあります。 ```console kubectl get svc,pod ``` ```none NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/kubernetes 10.100.0.1 443/TCP 46m service/nginx 10.100.0.16 80/TCP 33s NAME READY STATUS RESTARTS AGE pod/nginx-701339712-e0qfq 1/1 Running 0 35s ``` ## もう1つのPodからアクセスしてServiceを検証する これで、新しい`nginx`サービスに他のPodからアクセスできるようになったはずです。`default`名前空間内の他のPodから`nginx` Serviceにアクセスするために、busyboxコンテナを起動します。 ```console kubectl run busybox --rm -ti --image=busybox -- /bin/sh ``` シェルの中で、次のコマンドを実行します。 ```shell wget --spider --timeout=1 nginx ``` ```none Connecting to nginx (10.100.0.16:80) remote file exists ``` ## `nginx` Serviceへのアクセスを制限する `nginx` Serviceへのアクセスを制限するために、`access: true`というラベルが付いたPodだけがクエリできるようにします。次の内容でNetworkPolicyオブジェクトを作成してください。 {{< codenew file=\"service/networking/nginx-policy.yaml\" >}} NetworkPolicyオブジェクトの名前は、有効な[DNSサブドメイン名](/ja/docs/concepts/overview/working-with-objects/names#dns-subdomain-names)でなければなりません。 {{< note >}} このNetworkPolicyには、ポリシーを適用するPodのグループを選択するための`podSelector`が含まれています。このポリシーは、ラベル`app=nginx`の付いたPodを選択していることがわかります。このラベルは、`nginx` Deployment内のPodに自動的に追加されたものです。空の`podSelector`は、その名前空間内のすべてのPodを選択します。 {{< /note >}} ## Serviceにポリシーを割り当てる kubectlを使って、上記の`nginx-policy.yaml`ファイルからNetworkPolicyを作成します。 ```console kubectl apply -f https://k8s.io/examples/service/networking/nginx-policy.yaml ``` ```none networkpolicy.networking.k8s.io/access-nginx created ``` ## accessラベルが定義されていない状態でServiceへのアクセスをテストする `nginx` Serviceに正しいラベルが付いていないPodからアクセスを試してみると、リクエストがタイムアウトします。 ```console kubectl run busybox --rm -ti --image=busybox -- /bin/sh ``` シェルの中で、次のコマンドを実行します。 ```shell wget --spider --timeout=1 nginx ``` ```none Connecting to nginx (10.100.0.16:80) wget: download timed out ``` ## accessラベルを定義して再テストする 正しいラベルが付いたPodを作成すると、リクエストが許可されるようになるのがわかります。 ```console kubectl run busybox --rm -ti --labels=\"access=true\" --image=busybox -- /bin/sh ``` シェルの中で、次のコマンドを実行します。 ```shell wget --spider --timeout=1 nginx ``` ```none Connecting to nginx (10.100.0.16:80) remote file exists ``` "} {"_id":"q-en-website-dfb843ea2f256f6c49e13cd5e1aaf3fef17dae5f3baa0814687a9fb99adcd3cf","text":"# Replace the value of \"containerRuntimeEndpoint\" for a different container runtime if needed. ``` --> ```sh cat << EOF > /etc/systemd/system/kubelet.service.d/kubelet.conf # 将下面的 \"systemd\" 替换为你的容器运行时所使用的 cgroup 驱动。"} {"_id":"q-en-website-dfd2998269dd71e07d16ed78ad12a2538cc4a7f361c0ff2bce4cddec256e91da","text":"1. 运行以下命令: ```sh ./etcd --listen-client-urls=http://$PRIVATE_IP:2379 --advertise-client-urls=http://$PRIVATE_IP:2379 ``` ```sh etcd --listen-client-urls=http://$PRIVATE_IP:2379 --advertise-client-urls=http://$PRIVATE_IP:2379 ``` 2. 使用参数 `--etcd-servers=$PRIVATE_IP:2379` 启动 Kubernetes API 服务器。 使用您 etcd 客户端 IP 替换 `PRIVATE_IP`。 确保将 `PRIVATE_IP` 设置为etcd客户端 IP。 ### 多节点 etcd 集群 为了耐用性和高可用性,在生产中将以多节点集群的方式运行 etcd,并且定期备份。建议在生产中使用五个成员的集群。有关该内容的更多信息,请参阅[常见问题文档](https://github.com/coreos/etcd/blob/master/Documentation/faq.md#what-is-failure-tolerance)。 为了耐用性和高可用性,在生产中将以多节点集群的方式运行 etcd,并且定期备份。 建议在生产中使用五个成员的集群。 有关该内容的更多信息,请参阅 [常见问题文档](https://etcd.io/docs/current/faq/#what-is-failure-tolerance)。 可以通过静态成员信息或动态发现的方式配置 etcd 集群。有关集群的详细信息,请参阅 [etcd 集群文档](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/clustering.md)。 可以通过静态成员信息或动态发现的方式配置 etcd 集群。 有关集群的详细信息,请参阅 [etcd 集群文档](https://etcd.io/docs/current/op-guide/clustering/)。 例如,考虑运行以下客户端 URL 的五个成员的 etcd 集群:`http://$IP1:2379`,`http://$IP2:2379`,`http://$IP3:2379`,`http://$IP4:2379` 和 `http://$IP5:2379`。要启动 Kubernetes API 服务器: 例如,考虑运行以下客户端 URL 的五个成员的 etcd 集群:`http://$IP1:2379`, `http://$IP2:2379`,`http://$IP3:2379`,`http://$IP4:2379` 和 `http://$IP5:2379`。 要启动 Kubernetes API 服务器: 1. 运行以下命令: ```sh ./etcd --listen-client-urls=http://$IP1:2379, http://$IP2:2379, http://$IP3:2379, http://$IP4:2379, http://$IP5:2379 --advertise-client-urls=http://$IP1:2379, http://$IP2:2379, http://$IP3:2379, http://$IP4:2379, http://$IP5:2379 ``` ```shell etcd --listen-client-urls=http://$IP1:2379,http://$IP2:2379,http://$IP3:2379,http://$IP4:2379,http://$IP5:2379 --advertise-client-urls=http://$IP1:2379,http://$IP2:2379,http://$IP3:2379,http://$IP4:2379,http://$IP5:2379 ``` 2. 使用参数 `--etcd-servers=$IP1:2379, $IP2:2379, $IP3:2379, $IP4:2379, $IP5:2379` 启动 Kubernetes API 服务器。 2. 使用参数 `--etcd-servers=$IP1:2379,$IP2:2379,$IP3:2379,$IP4:2379,$IP5:2379` 启动 Kubernetes API 服务器。 使用您 etcd 客户端 IP 地址替换 `IP`。 确保将 `IP` 变量设置为客户端 IP 地址。 If you want to control traffic flow at the IP address or port level (OSI layer 3 or 4), then you might consider using Kubernetes NetworkPolicies for particular applications in your cluster. NetworkPolicies are an application-centric construct which allow you to specify how a {{< glossary_tooltip text=\"pod\" term_id=\"pod\">}} is allowed to communicate with various network \"entities\" (we use the word \"entity\" here to avoid overloading the more common terms such as \"endpoints\" and \"services\", which have specific Kubernetes connotations) over the network. If you want to control traffic flow at the IP address or port level (OSI layer 3 or 4), then you might consider using Kubernetes NetworkPolicies for particular applications in your cluster. NetworkPolicies are an application-centric construct which allow you to specify how a {{< glossary_tooltip text=\"pod\" term_id=\"pod\">}} is allowed to communicate with various network \"entities\" (we use the word \"entity\" here to avoid overloading the more common terms such as \"endpoints\" and \"services\", which have specific Kubernetes connotations) over the network. NetworkPolicies apply to a connection with a pod on one or both ends, and are not relevant to other connections. The entities that a Pod can communicate with are identified through a combination of the following 3 identifiers:"} {"_id":"q-en-website-e23453bb542cf9d1d80c45aed4f0e77179529712aa7ea01b7ae9620cd3b56b25","text":" {{< glossary_definition term_id=\"etcd\" length=\"all\" >}} ## {{% heading \"prerequisites\" %}} {{< include \"task-tutorial-prereqs.md\" >}} {{< version-check >}}"} {"_id":"q-en-website-e31595534352f4a07bf9dda51812e8ee2fee999359f2d4fcce3ae01f8eed35d4","text":" --- title: 設定ファイルを使用してSecretを管理する content_type: task weight: 20 description: リソース設定ファイルを使用してSecretを作成する --- ## {{% heading \"prerequisites\" %}} {{< include \"task-tutorial-prereqs.md\" >}} ## 設定ファイルを作成する あらかじめYAMLまたはJSON形式でSecretのマニフェストを作成したうえで、オブジェクトを作成することができます。 [Secret](/docs/reference/generated/kubernetes-api/{{< param \"version\" >}}/#secret-v1-core)リソースには、`data`と`stringData`の2つのマップが含まれています。 `data`フィールドは任意のデータを格納するのに使用され、base64でエンコードされます。 `stringData`フィールドは利便性のために用意されており、Secretデータをエンコードされていない文字列として提供することができます。 `data`と`stringData`のキーは、英数字、`-`、`_`、`.`で構成されている必要があります。 たとえば、`data`フィールドを使用して2つの文字列をSecretに格納するには、次のように文字列をbase64に変換します: ```shell echo -n 'admin' | base64 ``` 出力は次のようになります: ``` YWRtaW4= ``` ```shell echo -n '1f2d1e2e67df' | base64 ``` 出力は次のようになります: ``` MWYyZDFlMmU2N2Rm ``` 以下のようなSecret設定ファイルを記述します: ```yaml apiVersion: v1 kind: Secret metadata: name: mysecret type: Opaque data: username: YWRtaW4= password: MWYyZDFlMmU2N2Rm ``` なお、Secretオブジェクトの名前は、有効な[DNSサブドメイン名](/ja/docs/concepts/overview/working-with-objects/names#dns-subdomain-names)である必要があります。 {{< note >}} SecretデータのシリアライズされたJSONおよびYAMLの値は、base64文字列としてエンコードされます。 文字列中の改行は不正で、含まれていてはなりません。 Darwin/macOSで`base64`ユーティリティーを使用する場合、長い行を分割するために`-b`オプションを使用するのは避けるべきです。 逆に、Linux ユーザーは、`base64` コマンドにオプション`-w 0`を追加するか、`-w`オプションが利用できない場合には、パイプライン`base64 | tr -d 'n'`を追加する*必要があります*。 {{< /note >}} 特定のシナリオでは、代わりに`stringData`フィールドを使用できます。 このフィールドでは、base64エンコードされていない文字列を直接Secretに入れることができ、Secretの作成時や更新時には、その文字列がエンコードされます。 たとえば、設定ファイルを保存するためにSecretを使用しているアプリケーションをデプロイする際に、デプロイプロセス中に設定ファイルの一部を入力したい場合などが考えられます。 たとえば、次のような設定ファイルを使用しているアプリケーションの場合: ```yaml apiUrl: \"https://my.api.com/api/v1\" username: \"\" password: \"\" ``` 次のような定義でSecretに格納できます: ```yaml apiVersion: v1 kind: Secret metadata: name: mysecret type: Opaque stringData: config.yaml: | apiUrl: \"https://my.api.com/api/v1\" username: password: ``` ## Secretを作成する [`kubectl apply`](/docs/reference/generated/kubectl/kubectl-commands#apply)でSecretを作成します: ```shell kubectl apply -f ./secret.yaml ``` 出力は次のようになります: ``` secret/mysecret created ``` ## Secretを確認する `stringData`フィールドは、書き込み専用の便利なフィールドです。Secretを取得する際には決して出力されません。たとえば、次のようなコマンドを実行した場合: ```shell kubectl get secret mysecret -o yaml ``` 出力は次のようになります: ```yaml apiVersion: v1 kind: Secret metadata: creationTimestamp: 2018-11-15T20:40:59Z name: mysecret namespace: default resourceVersion: \"7225\" uid: c280ad2e-e916-11e8-98f2-025000000001 type: Opaque data: config.yaml: YXBpVXJsOiAiaHR0cHM6Ly9teS5hcGkuY29tL2FwaS92MSIKdXNlcm5hbWU6IHt7dXNlcm5hbWV9fQpwYXNzd29yZDoge3twYXNzd29yZH19 ``` `kubectl get`と`kubectl describe`コマンドはデフォルトではSecretの内容を表示しません。 これは、Secretが不用意に他人にさらされたり、ターミナルログに保存されたりしないようにするためです。 エンコードされたデータの実際の内容を確認するには、[Secretのデコード](/ja/docs/tasks/configmap-secret/managing-secret-using-kubectl/#decoding-secret)を参照してください。 `username`などのフィールドが`data`と`stringData`の両方に指定されている場合は、`stringData`の値が使われます。 たとえば、以下のようなSecretの定義の場合: ```yaml apiVersion: v1 kind: Secret metadata: name: mysecret type: Opaque data: username: YWRtaW4= stringData: username: administrator ``` 結果は以下の通りです: ```yaml apiVersion: v1 kind: Secret metadata: creationTimestamp: 2018-11-15T20:46:46Z name: mysecret namespace: default resourceVersion: \"7579\" uid: 91460ecb-e917-11e8-98f2-025000000001 type: Opaque data: username: YWRtaW5pc3RyYXRvcg== ``` `YWRtaW5pc3RyYXRvcg==`をデコードすると`administrator`となります。 ## クリーンアップ 作成したSecretを削除するには次のコマンドを実行します: ```shell kubectl delete secret mysecret ``` ## {{% heading \"whatsnext\" %}} - [Secretのコンセプト](/ja/docs/concepts/configuration/secret/)を読む - [kubectlを使用してSecretを管理する](/ja/docs/tasks/configmap-secret/managing-secret-using-kubectl/)方法を知る - [kustomizeを使用してSecretを管理する](/docs/tasks/configmap-secret/managing-secret-using-kustomize/)方法を知る "} {"_id":"q-en-website-e4aab511146dc59e364c8d8ced945ee075cbe962d2164fb9c0eb0a466f9a5e08","text":"* For detailed information about Pod and container status in the API, see the API reference documentation covering [`status`](/docs/reference/kubernetes-api/workload-resources/pod-v1/#PodStatus) for Pod. No newline at end of file [`status`](/docs/reference/kubernetes-api/workload-resources/pod-v1/#PodStatus) for Pod. "} {"_id":"q-en-website-e52dbd25dfc455fd4edabde1038b78ca577ce006bf6684527a5040328140ce0b","text":"This feature gate will never graduate to beta or stable. - `TopologyManagerPolicyBetaOptions`: Allow fine-tuning of topology manager policies, experimental, Beta-quality options. This feature gate guards *a group* of topology manager options whose quality level is alpha. This feature gate guards *a group* of topology manager options whose quality level is beta. This feature gate will never graduate to stable. - `TopologyManagerPolicyOptions`: Allow fine-tuning of topology manager policies, - `UserNamespacesStatelessPodsSupport`: Enable user namespace support for stateless Pods."} {"_id":"q-en-website-e5caef133f8579c5ab84778ea0c6632a4605a9c292339e21cb90b7154930c13d","text":"* The named groups are at REST path `/apis/$GROUP_NAME/$VERSION` and use `apiVersion: $GROUP_NAME/$VERSION` (for example, `apiVersion: batch/v1`). You can find the full list of supported API groups in [Kubernetes API reference](/docs/reference/generated/kubernetes-api/{{< param \"version\" >}}/). [Kubernetes API reference](/docs/reference/generated/kubernetes-api/{{< param \"version\" >}}/#-strong-api-groups-strong-). ## Enabling or disabling API groups {#enabling-or-disabling} Certain resources and API groups are enabled by default. You can enable or disable them by setting `--runtime-config` on the API server. The `--runtime-config` flag accepts comma separated `=` pairs describing the runtime configuration of the API server. For example: `--runtime-config` flag accepts comma separated `[=]` pairs describing the runtime configuration of the API server. If the `=` part is omitted, it is treated as if `=true` is specified. For example: - to disable `batch/v1`, set `--runtime-config=batch/v1=false` - to enable `batch/v2alpha1`, set `--runtime-config=batch/v2alpha1`"} {"_id":"q-en-website-e63bae8f25789be964cb30a732487ce4dd389abc7903fc94fa33b298795b2685","text":"/docs/tasks/administer-cluster/quota-memory-cpu-namespace/ /docs/tasks/administer-cluster/manage-resources/quota-memory-cpu-namespace/ 301 /docs/tasks/administer-cluster/quota-pod-namespace/ /docs/tasks/administer-cluster/manage-resources/quota-pod-namespace/ 301 /docs/tasks/administer-cluster/reserve-compute-resources/out-of-resource.md /docs/tasks/administer-cluster/out-of-resource/ 301 /docs/tasks/administer-cluster/out-of-resource/ /docs/concepts/scheduling-eviction/pod-eviction/ 301 /docs/tasks/administer-cluster/out-of-resource/ /docs/concepts/scheduling-eviction/node-pressure-eviction/ 301 /docs/tasks/administer-cluster/romana-network-policy/ /docs/tasks/administer-cluster/network-policy-provider/romana-network-policy/ 301 /docs/tasks/administer-cluster/running-cloud-controller.md /docs/tasks/administer-cluster/running-cloud-controller/ 301 /docs/tasks/administer-cluster/share-configuration/ /docs/tasks/access-application-cluster/configure-access-multiple-clusters/ 301"} {"_id":"q-en-website-e6da19023dcc7696c932aaf92163a39ce5a13829b36e2d2790b4c8be99c15495","text":" apiVersion: v1 kind: Pod metadata: name: dapi-test-pod spec: containers: - name: test-container image: k8s.gcr.io/busybox command: [ \"/bin/sh\", \"-c\", \"env\" ] envFrom: - configMapRef: name: special-config restartPolicy: Never "} {"_id":"q-en-website-e7413c1a765e8baa218e5b703d5aa12831eaea3103cb3d0e388eb96a88605698","text":"

If you haven't worked through the earlier sections, start from Using minikube to create a cluster.

Scaling is accomplished by changing the number of replicas in a Deployment

NOTE If you are trying this after the previous section , then you may have deleted the service you created, or have created a Service of type: NodePort. In this section, it is assumed that a service with type: LoadBalancer is created for the kubernetes-bootcamp Deployment.

If you have not deleted the Service created in the previous section, first delete that Service and then run the following command to create a new Service with its type set to LoadBalancer:

kubectl expose deployment/kubernetes-bootcamp --type=\"LoadBalancer\" --port 8080


"} {"_id":"q-en-website-e773a7f3f1bcb4f79f6f6ae84271cd45bd2f5da3501bdf734ce2ca959f861b1a","text":"### Check the local DNS configuration first Take a look inside the resolv.conf file. (See [Inheriting DNS from the node](/docs/tasks/administer-cluster/dns-custom-nameservers/#inheriting-dns-from-the-node) and (See [Customizing DNS Service](/docs/tasks/administer-cluster/dns-custom-nameservers) and [Known issues](#known-issues) below for more information) ```shell"} {"_id":"q-en-website-e7ebf74469821646f99446180cc2050e8d286b01cc913d025c6f534be2d21074","text":" ## 安全的 etcd 集群 对 etcd 的访问相当于集群中的 root 权限,因此理想情况下只有 API 服务器才能访问它。考虑到数据的敏感性,建议只向需要访问 etcd 集群的节点授予权限。 对 etcd 的访问相当于集群中的 root 权限,因此理想情况下只有 API 服务器才能访问它。 考虑到数据的敏感性,建议只向需要访问 etcd 集群的节点授予权限。 想要确保 etcd 的安全,可以设置防火墙规则或使用 etcd 提供的安全特性,这些安全特性依赖于 x509 公钥基础设施(PKI)。首先,通过生成密钥和证书对来建立安全的通信通道。 例如,使用密钥对 `peer.key` 和 `peer.cert` 来保护 etcd 成员之间的通信,而 `client.cert` 和 `client.cert` 用于保护 etcd 与其客户端之间的通信。请参阅 etcd 项目提供的[示例脚本](https://github.com/coreos/etcd/tree/master/hack/tls-setup),以生成用于客户端身份验证的密钥对和 CA 文件。 想要确保 etcd 的安全,可以设置防火墙规则或使用 etcd 提供的安全特性,这些安全特性依赖于 x509 公钥基础设施(PKI)。 首先,通过生成密钥和证书对来建立安全的通信通道。 例如,使用密钥对 `peer.key` 和 `peer.cert` 来保护 etcd 成员之间的通信, 而 `client.key` 和 `client.cert` 用于保护 etcd 与其客户端之间的通信。 请参阅 etcd 项目提供的[示例脚本](https://github.com/coreos/etcd/tree/master/hack/tls-setup), 以生成用于客户端身份验证的密钥对和 CA 文件。 ### 安全通信 若要使用安全对等通信对 etcd 进行配置,请指定参数 `--peer-key-file=peer.key` 和 `--peer-cert-file=peer.cert`,并使用 https 作为 URL 模式。 若要使用安全对等通信对 etcd 进行配置,请指定参数 `--peer-key-file=peer.key` 和 `--peer-cert-file=peer.cert`,并使用 HTTPS 作为 URL 模式。 类似地,要使用安全客户端通信对 etcd 进行配置,请指定参数 `--key-file=k8sclient.key` 和 `--cert-file=k8sclient.cert`,并使用 https 作为 URL 模式。 类似地,要使用安全客户端通信对 etcd 进行配置,请指定参数 `--key-file=k8sclient.key` 和 `--cert-file=k8sclient.cert`,并使用 HTTPS 作为 URL 模式。 使用安全通信的客户端命令的示例: ``` ETCDCTL_API=3 etcdctl --endpoints 10.2.0.9:2379 --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key --cacert=/etc/kubernetes/pki/etcd/ca.crt member list ``` ### 限制 etcd 集群的访问 配置安全通信后,将 etcd 集群的访问限制在 Kubernetes API 服务器上。使用 TLS 身份验证来完成此任务。 例如,考虑由 CA `etcd.ca` 信任的密钥对 `k8sclient.key` 和 `k8sclient.cert`。当 etcd 配置为 `--client-cert-auth` 和 TLS 时,它使用系统 CA 或由 `--trusted-ca-file` 参数传入的 CA 验证来自客户端的证书。 例如,考虑由 CA `etcd.ca` 信任的密钥对 `k8sclient.key` 和 `k8sclient.cert`。 当 etcd 配置为 `--client-cert-auth` 和 TLS 时,它使用系统 CA 或由 `--trusted-ca-file` 参数传入的 CA 验证来自客户端的证书。 指定参数 `--client-cert-auth=true` 和 `--trusted-ca-file=etcd.ca` 将限制对具有证书 `k8sclient.cert` 的客户端的访问。 一旦正确配置了 etcd,只有具有有效证书的客户端才能访问它。要让 Kubernetes API 服务器访问,可以使用参数 `--etcd-certfile=k8sclient.cert`,`--etcd-keyfile=k8sclient.key` 和 `--etcd-cafile=ca.cert` 配置它。 一旦正确配置了 etcd,只有具有有效证书的客户端才能访问它。要让 Kubernetes API 服务器访问, 可以使用参数 `--etcd-certfile=k8sclient.cert`,`--etcd-keyfile=k8sclient.key` 和 `--etcd-cafile=ca.cert` 配置。 {{< note >}} Kubernetes 目前不支持 etcd 身份验证。想要了解更多信息,请参阅相关的问题[支持 etcd v2 的基本认证](https://github.com/kubernetes/kubernetes/issues/23398)。 Kubernetes 目前不支持 etcd 身份验证。 想要了解更多信息,请参阅相关的问题 [支持 etcd v2 的基本认证](https://github.com/kubernetes/kubernetes/issues/23398)。 {{< /note >}} ## 替换失败的 etcd 成员 etcd 集群通过容忍少数成员故障实现高可用性。但是,要改善集群的整体健康状况,请立即替换失败的成员。当多个成员失败时,逐个替换它们。替换失败成员需要两个步骤:删除失败成员和添加新成员。 etcd 集群通过容忍少数成员故障实现高可用性。 但是,要改善集群的整体健康状况,请立即替换失败的成员。当多个成员失败时,逐个替换它们。 替换失败成员需要两个步骤:删除失败成员和添加新成员。 虽然 etcd 在内部保留唯一的成员 ID,但建议为每个成员使用唯一的名称,以避免人为错误。例如,考虑一个三成员的 etcd 集群。让 URL 为:member1=http://10.0.0.1, member2=http://10.0.0.2 和 member3=http://10.0.0.3。当 member1 失败时,将其替换为 member4=http://10.0.0.4。 虽然 etcd 在内部保留唯一的成员 ID,但建议为每个成员使用唯一的名称,以避免人为错误。 例如,考虑一个三成员的 etcd 集群。让 URL 为:`member1=http://10.0.0.1`, `member2=http://10.0.0.2` 和 `member3=http://10.0.0.3`。当 `member1` 失败时,将其替换为 `member4=http://10.0.0.4`。 1. 获取失败的 member1 的成员 ID: 1. 获取失败的 `member1` 的成员 ID: `etcdctl --endpoints=http://10.0.0.2,http://10.0.0.3 member list` ```shell etcdctl --endpoints=http://10.0.0.2,http://10.0.0.3 member list ``` 显示以下信息: 显示以下信息: 8211f1d0f64f3269, started, member1, http://10.0.0.1:2380, http://10.0.0.1:2379 91bc3c398fb3c146, started, member2, http://10.0.0.2:2380, http://10.0.0.2:2379 fd422379fda50e48, started, member3, http://10.0.0.3:2380, http://10.0.0.3:2379 ```console 8211f1d0f64f3269, started, member1, http://10.0.0.1:2380, http://10.0.0.1:2379 91bc3c398fb3c146, started, member2, http://10.0.0.2:2380, http://10.0.0.2:2379 fd422379fda50e48, started, member3, http://10.0.0.3:2380, http://10.0.0.3:2379 ``` 2. 移除失败的成员 `etcdctl member remove 8211f1d0f64f3269` ```shell etcdctl member remove 8211f1d0f64f3269 ``` 显示以下信息: 显示以下信息: Removed member 8211f1d0f64f3269 from cluster ```console Removed member 8211f1d0f64f3269 from cluster ``` 3. 增加新成员: `./etcdctl member add member4 --peer-urls=http://10.0.0.4:2380` ```shell etcdctl member add member4 --peer-urls=http://10.0.0.4:2380 ``` 显示以下信息: 显示以下信息: Member 2be1eb8f84b7f63e added to cluster ef37ad9dc622a7c4 ```console Member 2be1eb8f84b7f63e added to cluster ef37ad9dc622a7c4 ``` 4. 在 IP 为 `10.0.0.4` 的机器上启动新增加的成员: export ETCD_NAME=\"member4\" export ETCD_INITIAL_CLUSTER=\"member2=http://10.0.0.2:2380,member3=http://10.0.0.3:2380,member4=http://10.0.0.4:2380\" export ETCD_INITIAL_CLUSTER_STATE=existing etcd [flags] ```shell export ETCD_NAME=\"member4\" export ETCD_INITIAL_CLUSTER=\"member2=http://10.0.0.2:2380,member3=http://10.0.0.3:2380,member4=http://10.0.0.4:2380\" export ETCD_INITIAL_CLUSTER_STATE=existing etcd [flags] ``` 5. 做以下事情之一: 1. 更新其 `--etcd-servers` 参数,使 Kubernetes 知道配置进行了更改,然后重新启动 Kubernetes API 服务器。 1. 更新 Kubernetes API 服务器的 `--etcd-servers` 参数,使 Kubernetes 知道配置进行了更改,然后重新启动 Kubernetes API 服务器。 2. 如果在 deployment 中使用了负载均衡,更新负载均衡配置。 有关集群重新配置的详细信息,请参阅 [etcd 重构文档](https://github.com/coreos/etcd/blob/master/Documentation/op-guide/runtime-configuration.md#remove-a-member)。 有关集群重新配置的详细信息,请参阅 [etcd 重构文档](https://etcd.io/docs/current/op-guide/runtime-configuration/#remove-a-member)。 ## 备份 etcd 集群 所有 Kubernetes 对象都存储在 etcd 上。定期备份 etcd 集群数据对于在灾难场景(例如丢失所有主节点)下恢复 Kubernetes 集群非常重要。快照文件包含所有 Kubernetes 状态和关键信息。为了保证敏感的 Kubernetes 数据的安全,可以对快照文件进行加密。 所有 Kubernetes 对象都存储在 etcd 上。定期备份 etcd 集群数据对于在灾难场景(例如丢失所有控制平面节点)下恢复 Kubernetes 集群非常重要。 快照文件包含所有 Kubernetes 状态和关键信息。为了保证敏感的 Kubernetes 数据的安全,可以对快照文件进行加密。 备份 etcd 集群可以通过两种方式完成:etcd 内置快照和卷快照。 **作者**: [Jordan Liggitt](https://github.com/liggitt) (Google) 作为 Kubernetes 维护者,我们一直在寻找在保持兼容性的同时提高可用性的方法。 在开发功能、分类 Bug、和回答支持问题的过程中,我们积累了有助于 Kubernetes 用户了解的信息。 过去,共享这些信息仅限于发布说明、公告电子邮件、文档和博客文章等带外方法。 除非有人知道需要寻找这些信息并成功找到它们,否则他们不会从中受益。 在 Kubernetes v1.19 中,我们添加了一个功能,允许 Kubernetes API 服务器[向 API 客户端发送警告](https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/1693-warnings)。 警告信息使用[标准 `Warning` 响应头](https://tools.ietf.org/html/rfc7234#section-5.5)发送, 因此它不会以任何方式更改状态代码或响应体。 这一设计使得服务能够发送任何 API 客户端都可以轻松读取的警告,同时保持与以前的客户端版本兼容。 警告在 `kubectl` v1.19+ 的 `stderr` 输出中和 `k8s.io/client-go` v0.19.0+ 客户端库的日志中出现。 `k8s.io/client-go` 行为可以[在进程或客户端层面重载](#customize-client-handling)。 ## 弃用警告 {#deprecation-warnings} 我们第一次使用此新功能是针对已弃用的 API 调用发送警告。 Kubernetes 是一个[大型、快速发展的项目](https://www.cncf.io/cncf-kubernetes-project-journey/#development-velocity)。 跟上每个版本的[变更](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.19.md#changelog-since-v1180)可能是令人生畏的, 即使对于全职从事该项目的人来说也是如此。一种重要的变更是 API 弃用。 随着 Kubernetes 中的 API 升级到 GA 版本,预发布的 API 版本会被弃用并最终被删除。 即使有[延长的弃用期](/zh-cn/docs/reference/using-api/deprecation-policy/), 并且[在发布说明中](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.19.md#deprecation)也包含了弃用信息, 他们仍然很难被追踪。在弃用期内,预发布 API 仍然有效, 允许多个版本过渡到稳定的 API 版本。 然而,我们发现用户往往甚至没有意识到他们依赖于已弃用的 API 版本, 直到升级到不再提供相应服务的新版本。 从 v1.19 开始,系统每当收到针对已弃用的 REST API 的请求时,都会返回警告以及 API 响应。 此警告包括有关 API 将不再可用的版本以及替换 API 版本的详细信息。 因为警告源自服务器端,并在客户端层级被拦截,所以它适用于所有 kubectl 命令, 包括像 `kubectl apply` 这样的高级命令,以及像 `kubectl get --raw` 这样的低级命令: \"kubectl 这有助于受弃用影响的人们知道他们所请求的API已被弃用, 他们有多长时间来解决这个问题,以及他们应该使用什么 API。 这在用户应用不是由他们创建的清单文件时特别有用, 所以他们有时间联系作者要一个更新的版本。 我们还意识到**使用**已弃用的 API 的人通常不是负责升级集群的人, 因此,我们添加了两个面向管理员的工具来帮助跟踪已弃用的 API 的使用情况并确定何时升级安全。 ### 度量指标 {#metrics} 从 Kubernetes v1.19 开始,当向已弃用的 REST API 端点发出请求时, 在 kube-apiserver 进程中,`apiserver_requested_deprecated_apis` 度量指标会被设置为 `1`。 该指标具有 API `group`、`version`、`resource` 和 `subresource` 的标签, 和一个 `removed_release` 标签,表明不再提供 API 的 Kubernetes 版本。 下面是一个使用 `kubectl` 的查询示例,[prom2json](https://github.com/prometheus/prom2json) 和 [jq](https://stedolan.github.io/jq/) 用来确定当前 API 服务器实例上收到了哪些对已弃用的 API 请求: ```sh kubectl get --raw /metrics | prom2json | jq ' .[] | select(.name==\"apiserver_requested_deprecated_apis\").metrics[].labels ' ``` 输出: ```json { \"group\": \"extensions\", \"removed_release\": \"1.22\", \"resource\": \"ingresses\", \"subresource\": \"\", \"version\": \"v1beta1\" } { \"group\": \"rbac.authorization.k8s.io\", \"removed_release\": \"1.22\", \"resource\": \"clusterroles\", \"subresource\": \"\", \"version\": \"v1beta1\" } ``` 输出展示在此服务器上请求了已弃用的 `extensions/v1beta1` Ingress 和 `rbac.authorization.k8s.io/v1beta1` ClusterRole API,这两个 API 都将在 v1.22 中被删除。 我们可以将该信息与 `apiserver_request_total` 指标结合起来,以获取有关这些 API 请求的更多详细信息: ```sh kubectl get --raw /metrics | prom2json | jq ' # set $deprecated to a list of deprecated APIs [ .[] | select(.name==\"apiserver_requested_deprecated_apis\").metrics[].labels | {group,version,resource} ] as $deprecated | # select apiserver_request_total metrics which are deprecated .[] | select(.name==\"apiserver_request_total\").metrics[] | select(.labels | {group,version,resource} as $key | $deprecated | index($key)) ' ``` 输出: ```json { \"labels\": { \"code\": \"0\", \"component\": \"apiserver\", \"contentType\": \"application/vnd.kubernetes.protobuf;stream=watch\", \"dry_run\": \"\", \"group\": \"extensions\", \"resource\": \"ingresses\", \"scope\": \"cluster\", \"subresource\": \"\", \"verb\": \"WATCH\", \"version\": \"v1beta1\" }, \"value\": \"21\" } { \"labels\": { \"code\": \"200\", \"component\": \"apiserver\", \"contentType\": \"application/vnd.kubernetes.protobuf\", \"dry_run\": \"\", \"group\": \"extensions\", \"resource\": \"ingresses\", \"scope\": \"cluster\", \"subresource\": \"\", \"verb\": \"LIST\", \"version\": \"v1beta1\" }, \"value\": \"1\" } { \"labels\": { \"code\": \"200\", \"component\": \"apiserver\", \"contentType\": \"application/json\", \"dry_run\": \"\", \"group\": \"rbac.authorization.k8s.io\", \"resource\": \"clusterroles\", \"scope\": \"cluster\", \"subresource\": \"\", \"verb\": \"LIST\", \"version\": \"v1beta1\" }, \"value\": \"1\" } ``` 上面的输出展示,对这些 API 发出的都只是读请求,并且大多数请求都用来监测已弃用的 Ingress API。 你还可以通过以下 Prometheus 查询获取这一信息, 该查询返回关于已弃用的、将在 v1.22 中删除的 API 请求的信息: ```promql apiserver_requested_deprecated_apis{removed_release=\"1.22\"} * on(group,version,resource,subresource) group_right() apiserver_request_total ``` ### 审计注解 {#audit-annotations} 度量指标是检查是否正在使用已弃用的 API 以及使用率如何的快速方法, 但它们没有包含足够的信息来识别特定的客户端或 API 对象。 从 Kubernetes v1.19 开始, 对已弃用的 API 的请求进行审计时,[审计事件](/zh-cn/docs/tasks/debug/debug-cluster/audit/)中会包括 审计注解 `\"k8s.io/deprecated\":\"true\"`。 管理员可以使用这些审计事件来识别需要更新的特定客户端或对象。 ## 自定义资源定义 {#custom-resource-definitions} 除了 API 服务器对已弃用的 API 使用发出警告的能力外,从 v1.19 开始,CustomResourceDefinition 可以指示[它定义的资源的特定版本已被弃用](/zh-cn/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning/#version-deprecation)。 当对自定义资源的已弃用的版本发出 API 请求时,将返回一条警告消息,与内置 API 的行为相匹配。 CustomResourceDefinition 的作者还可以根据需要自定义每个版本的警告。 这允许他们在需要时提供指向迁移指南的信息或其他信息。 ```yaml apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition name: crontabs.example.com spec: versions: - name: v1alpha1 # 这表示 v1alpha1 版本的自定义资源已经废弃了。 # 对此版本的 API 请求会在服务器响应中收到警告。 deprecated: true # 这会把返回给发出 v1alpha1 API 请求的客户端的默认警告覆盖。 deprecationWarning: \"example.com/v1alpha1 CronTab is deprecated; use example.com/v1 CronTab (see http://example.com/v1alpha1-v1)\" ... - name: v1beta1 # 这表示 v1beta1 版本的自定义资源已经废弃了。 # 对此版本的 API 请求会在服务器响应中收到警告。 # 此版本返回默认警告消息。 deprecated: true ... - name: v1 ... ``` ## 准入 Webhook {#admission-webhooks} [准入 Webhook](/zh-cn/docs/reference/access-authn-authz/extensible-admission-controllers)是将自定义策略或验证与 Kubernetes 集成的主要方式。 从 v1.19 开始,Admission Webhook 可以[返回警告消息](/zh-cn/docs/reference/access-authn-authz/extensible-admission-controllers/#response), 传递给发送请求的 API 客户端。警告可以与允许或拒绝的响应一起返回。 例如,允许请求但警告已知某个配置无法正常运行时,准入 Webhook 可以发送以下响应: ```json { \"apiVersion\": \"admission.k8s.io/v1\", \"kind\": \"AdmissionReview\", \"response\": { \"uid\": \"\", \"allowed\": true, \"warnings\": [ \".spec.memory: requests >1GB do not work on Fridays\" ] } } ``` 如果你在实现一个返回警告消息的 Webhook,这里有一些提示: * 不要在消息中包含 “Warning:” 前缀(由客户端在输出时添加) * 使用警告消息来正确描述能被发出 API 请求的客户端纠正或了解的问题 * 保持简洁;如果可能,将警告限制为 120 个字符以内 准入 Webhook 可以通过多种方式使用这个新功能,我期待看到大家想出来的方法。 这里有一些想法可以帮助你入门: * 添加 “complain” 模式的 Webhook 实现,它们返回警告而不是拒绝, 允许在开始执行之前尝试策略以验证它是否按预期工作 * “lint” 或 “vet” 风格的 Webhook,检查对象并在未遵循最佳实践时显示警告 ## 自定义客户端处理方式 {#customize-client-handling} 使用 `k8s.io/client-go` 库发出 API 请求的应用程序可以定制如何处理从服务器返回的警告。 默认情况下,收到的警告会以日志形式输出到 stderr, 但[在进程层面](https://godoc.org/k8s.io/client-go/rest#SetDefaultWarningHandler)或[客户端层面] (https://godoc.org/k8s.io/client-go/rest#Config)均可定制这一行为。 这个例子展示了如何让你的应用程序表现得像 `kubectl`, 在进程层面重载整个消息处理逻辑以删除重复的警告, 并在支持的情况下使用彩色输出突出显示消息: ```go import ( \"os\" \"k8s.io/client-go/rest\" \"k8s.io/kubectl/pkg/util/term\" ... ) func main() { rest.SetDefaultWarningHandler( rest.NewWarningWriter(os.Stderr, rest.WarningWriterOptions{ // only print a given warning the first time we receive it Deduplicate: true, // highlight the output with color when the output supports it Color: term.AllowsColorOutput(os.Stderr), }, ), ) ... ``` 下一个示例展示如何构建一个忽略警告的客户端。 这对于那些操作所有资源类型(使用发现 API 在运行时动态发现) 的元数据并且不会从已弃用的特定资源的警告中受益的客户端很有用。 对于需要使用特定 API 的客户端,不建议抑制弃用警告。 ```go import ( \"k8s.io/client-go/rest\" \"k8s.io/client-go/kubernetes\" ) func getClientWithoutWarnings(config *rest.Config) (kubernetes.Interface, error) { // copy to avoid mutating the passed-in config config = rest.CopyConfig(config) // set the warning handler for this client to ignore warnings config.WarningHandler = rest.NoWarnings{} // construct and return the client return kubernetes.NewForConfig(config) } ``` ## Kubectl 强制模式 {#kubectl-strict-mode} 如果你想确保及时注意到弃用问题并立即着手解决它们, `kubectl` 在 v1.19 中添加了 `--warnings-as-errors` 选项。使用此选项调用时, `kubectl` 将从服务器收到的所有警告视为错误,并以非零码退出: \"kubectl 这可以在 CI 作业中用于将清单文件应用到当前服务器, 其中要求通过零退出码才能使 CI 作业成功。 ## 未来的可能性 {#future-possibilities} 现在我们有了一种在上下文中向用户传达有用信息的方法, 我们已经在考虑使用其他方法来改善人们使用 Kubernetes 的体验。 我们接下来要研究的几个领域是关于[已知有问题的值](http://issue.k8s.io/64841#issuecomment-395141013)的警告。 出于兼容性原因,我们不能直接拒绝,而应就使用已弃用的字段或字段值 (例如使用 beta os/arch 节点标签的选择器, [在 v1.14 中已弃用](/zh-cn/docs/reference/labels-annotations-taints/#beta-kubernetes-io-arch-deprecated)) 给出警告。 我很高兴看到这方面的进展,继续让 Kubernetes 更容易使用。 "} {"_id":"q-en-website-ebd2643a0f505519a1d70caf37d4830354fb3aa66ca0c494f269968e06e9ac15","text":"#### Serving {{< feature-state for_k8s_version=\"v1.20\" state=\"alpha\" >}} {{< feature-state for_k8s_version=\"v1.22\" state=\"beta\" >}} `serving` is identical to the `ready` condition, except it does not account for terminating states. Consumers of the EndpointSlice API should check this condition if they care about pod readiness while"} {"_id":"q-en-website-ed02862399efa0fac298a70416397da2d5531280299fce4a67565768e95d1b69","text":"Minimum value is 1. * `failureThreshold`: After a probe fails `failureThreshold` times in a row, Kubernetes considers that the overall check has failed: the container is _not_ ready/healthy/live. Defaults to 3. Minimum value is 1. For the case of a startup or liveness probe, if at least `failureThreshold` probes have failed, Kubernetes treats the container as unhealthy and triggers a restart for that specific container. The kubelet honors the setting of `terminationGracePeriodSeconds`"} {"_id":"q-en-website-ed12e196bde4d7bc24a086e13a7a6c70972116550897d104da161df0bf8d33e6","text":"content_type: task --- {{< feature-state for_k8s_version=\"v1.20\" state=\"alpha\" >}} {{< feature-state for_k8s_version=\"v1.24\" state=\"beta\" >}} "} {"_id":"q-en-website-ed51fbaf5a4e982720d8df7e2fd94fecc1ebf7bb1c08d442b574aea1de498fc5","text":"[feedback_yes] other = \"Tak\" [final_patch_release] other = \"Ostatnie wydanie poprawek\" [inline_list_separator] other = \",\" [input_placeholder_email_address] other = \"adres e-mail\" [javascript_required] other = \"JavaScript musi być [włączony](https://www.enable-javascript.com/pl/) na tej stronie\" [latest_release] other = \"Najnowsze wydanie:\""} {"_id":"q-en-website-ed7e0ab0a5cf2388c13c948be40dd94ff3a1f5fbcb7dd2b8250624d4caadd2b1","text":"[end_of_life] other = \"Zakończenie wsparcia:\" [envvars_heading] other = \"Zmienne środowiska\" [error_404_were_you_looking_for] other = \"Czy chodziło o:\" [examples_heading] other = \"Przykłady\" [feature_state] other = \"STATUS FUNKCJONALNOŚCI:\" [feedback_heading] other = \"Twoja opinia\""} {"_id":"q-en-website-efccd59a0cc98ee889ff1c3da294484a4ba92bbfaaf7903ee2bb019a081e5f64","text":"/docs/concepts/workloads/controllers/deployment/docs/concepts/workloads/pods/pod/ /docs/concepts/workloads/pods/pod/ 301 /docs/concepts/workloads/controllers/deployment.md /docs/concepts/workloads/controllers/deployment/ 301 /docs/concepts/workloads/controllers/job/ /docs/concepts/workloads/controllers/jobs-run-to-completion/ 301 /docs/concepts/workloads/controllers/petset/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/concepts/workloads/controllers/petsets/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/concepts/workloads/controllers/statefulsets/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/concepts/workloads/controllers/statefulset.md /docs/concepts/workloads/controllers/statefulset/ 301 /docs/concepts/workloads/pods/init-containers/Kubernetes/ /docs/concepts/workloads/pods/init-containers/ 301"} {"_id":"q-en-website-f1aa8984969b4ac5b26c29e02c839a8dc56d85337ee45cef978b6e1980acbbb8","text":" No newline at end of file"} {"_id":"q-en-website-f2817fccf21dcce9857f76ebd818cd7158e37141e31373cfac42df38eb0072ce","text":"`Bookmark` events can be requested by `allowWatchBookmarks=true` option in watch requests, but clients shouldn't assume bookmarks are returned at any specific interval, nor may they assume the server will send any `bookmark` event. ## Retrieving large results sets in chunks {{< feature-state for_k8s_version=\"v1.9\" state=\"beta\" >}} On large clusters, retrieving the collection of some resource types may result in very large responses that can impact the server and client. For instance, a cluster may have tens of thousands of pods, each of which is 1-2kb of encoded JSON. Retrieving all pods across all namespaces may result in a very large response (10-20MB) and consume a large amount of server resources. Starting in Kubernetes 1.9 the server supports the ability to break a single large collection request into many smaller chunks while preserving the consistency of the total request. Each chunk can be returned sequentially which reduces both the total size of the request and allows user-oriented clients to display results incrementally to improve responsiveness."} {"_id":"q-en-website-f2bf7ec0cf6c4f858087558efb1cf55b13dcaefd2c637d1ecfa80e0bedbfe0a7","text":"/docs/user-guide/kubectl-conventions/ /docs/reference/kubectl/conventions/ /docs/user-guide/kubectl-cheatsheet/ /docs/reference/kubectl/cheatsheet/ /cheatsheet /docs/reference/kubectl/cheatsheet/ 302 /docs/user-guide/kubectl/kubectl_*/ /docs/reference/generated/kubectl/kubectl-commands#:splat 301 /docs/user-guide/kubectl/kubectl_* /docs/reference/generated/kubectl/kubectl-commands#:splat 301 /docs/user-guide/labels/ /docs/concepts/overview/working-with-objects/labels/ 301 /docs/user-guide/liveness/ /docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/ 301 /docs/user-guide/load-balancer/ /docs/tasks/access-application-cluster/create-external-load-balancer/ 301"} {"_id":"q-en-website-f309a1472b196675a162f3297fa44fdbd74abbf7671af54f5f64618022c27025","text":"Used on: Node Label that kubeadm applies on the control plane nodes that it manages. A marker label to indicate that the node is used to run {{< glossary_tooltip text=\"control plane\" term_id=\"control-plane\" >}} components. The kubeadm tool applies this label to the control plane nodes that it manages. Other cluster management tools typically also set this taint. You can label control plane nodes with this label to make it easier to schedule Pods only onto these nodes, or to avoid running Pods on the control plane. If this label is set, [EndpointSlice controller](/docs/concepts/services-networking/topology-aware-routing/#implementation-control-plane) ignores that node while calculating Topology Aware Hints. ### node-role.kubernetes.io/control-plane {#node-role-kubernetes-io-control-plane-taint} Used on: Node Taint that kubeadm applies on control plane nodes to restrict placing pods and allow only specific pods to schedule on them. Example: `node-role.kubernetes.io/control-plane:NoSchedule` Taint that kubeadm applies on control plane nodes to allow only critical workloads to schedule on them. If this Taint is applied, control plane nodes allow only critical workloads to schedule on them. You can manually remove this taint with the following command on a specific node. ```shell kubectl taint nodes node-role.kubernetes.io/control-plane:NoSchedule- ``` ### node-role.kubernetes.io/master (deprecated) {#node-role-kubernetes-io-master-taint}"} {"_id":"q-en-website-f3e58fbf16a0233405eb0ffd315437b50712955403e983e79b4ef82f3f5c7bbc","text":" --- linktitle: リリースノート title: ノート type: docs description: > Kubernetesのリリースノート sitemap: priority: 0.5 --- リリースノートは、使用しているKubernetesのバージョンに合った[Changelog](https://github.com/kubernetes/kubernetes/tree/master/CHANGELOG)を読むことで確認できます。 {{< skew currentVersionAddMinor 0 >}}のchangelogを見るには[GitHub](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-{{< skew currentVersionAddMinor 0 >}}.md)を参照してください。 またリリースノートは、[relnotes.k8s.io](https://relnotes.k8s.io)上で検索してフィルタリングすることもできます。 {{< skew currentVersionAddMinor 0 >}}のフィルタリングされたリリースノートを見るには[relnotes.k8s.io](https://relnotes.k8s.io/?releaseVersions={{< skew currentVersionAddMinor 0 >}}.0)を参照してください。 "} {"_id":"q-en-website-f4079d49a523f8ea06de653b40b088f721ec9b8a85a491d88f9df1aac79fc2f5","text":"containers: - name: mysql image: mysql env: - name: MYSQL_ROOT_PASSWORD value: \"rootpasswd\" volumeMounts: - mountPath: /var/lib/mysql name: site-data subPath: mysql - name: php image: php image: php:7.0-apache volumeMounts: - mountPath: /var/www/html name: site-data"} {"_id":"q-en-website-f49c249424f13cb00a9d7eead0f9a4bdb15602e99f2da54da10e155c2a1d97d5","text":"To demonstrate this, let's spin up a simple Deployment and Pods in the `development` namespace. ```shell kubectl create deployment snowflake --image=k8s.gcr.io/serve_hostname -n=development kubectl create deployment snowflake --image=k8s.gcr.io/serve_hostname -n=development kubectl scale deployment snowflake --replicas=2 -n=development ``` We have just created a deployment whose replica size is 2 that is running the pod called `snowflake` with a basic container that just serves the hostname. Note that `kubectl run` creates deployments only on Kubernetes cluster >= v1.2. If you are running older versions, it creates replication controllers instead. If you want to obtain the old behavior, use `--generator=run/v1` to create replication controllers. See [`kubectl run`](/docs/reference/generated/kubectl/kubectl-commands/#run) for more details. ```shell kubectl get deployment -n=development"} {"_id":"q-en-website-f4c32867938630f44ae4a2f7519eb7f287622df7f87ae9185bd450ae776fe5e9","text":"/docs/api-reference/v1/operations/ /docs/api-reference/v1.9/ 301 /docs/concepts/abstractions/controllers/garbage-collection/ /docs/concepts/workloads/controllers/garbage-collection/ 301 /docs/concepts/abstractions/controllers/petsets/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/concepts/abstractions/controllers/statefulsets/ /docs/concepts/workloads/controllers/statefulset/ 301 /docs/concepts/abstractions/init-containers/ /docs/concepts/workloads/pods/init-containers/ 301 /docs/concepts/abstractions/overview/ /docs/concepts/overview/working-with-objects/kubernetes-objects/ 301"} {"_id":"q-en-website-f4dddd70776b6c37c4166706cd318f0c4aab57baa0e4fc123b73edd5cf38d766","text":"h4, h4.alert-heading { color: #000; display: block; float: left; float: initial; font-size: 1rem; padding: 0; padding-right: 0.5rem;"} {"_id":"q-en-website-f5074c39ee5b5011b55116591f8198cfcbe301bc67adcfb84b0542a00e58f5ef","text":"} body.cid-community .community-section#values { width: 100vw; width: 100%; max-width: initial; background-image: url('/images/community/event-bg.jpg'); color: #fff;"} {"_id":"q-en-website-f64162407a328fe9aab59ed8625127958513bb40faecdc9725dd5fe54cd4d617","text":"* `Localhost` to use a profile loaded on the host (see below) * `Unconfined` to run without AppArmor See the [API Reference](#api-reference) for the full details on the AppArmor profile API. See [Specifying AppArmor Confinement](#specifying-apparmor-confinement) for full details on the AppArmor profile API. To verify that the profile was applied, you can check that the container's root process is running with the correct profile by examining its proc attr:"} {"_id":"q-en-website-f762848a2e2865f4f7df2cdd0454baeb1c25a73560fd878a4bd0b029afc8cb0d","text":"

localAPIEndpoint represents the endpoint of the API server instance that's deployed on this control plane node. In HA setups, this differs from ClusterConfiguration.controlPlaneEndpoint in the sense that ontrolPlaneEndpoint is the global endpoint for the cluster, which then in the sense that controlPlaneEndpoint is the global endpoint for the cluster, which then loadbalances the requests to each individual API server. This configuration object lets you customize what IP/DNS name and port the local API server advertises it's accessible on. By default, kubeadm tries to auto-detect the IP of the default"} {"_id":"q-en-website-f8c96784e2444e48574d742ceb4687a08f0501f95301f45482dc1155012a6dc6","text":"Sebagai contoh, untuk membuat sebuah Secret dari literal `username=admin` dan `password=secret`, kamu dapat menspesifikasikan _generator_ Secret pada _file_ `kustomization.yaml` sebagai ```shell # Membuat sebuah file kustomization.yaml dengan menggunakan SecretGenerator # Membuat sebuah berkas kustomization.yaml dengan menggunakan SecretGenerator $ cat <./kustomization.yaml secretGenerator: - name: db-user-pass"} {"_id":"q-en-website-faaa2fd36725401774d3db09f601d4de91ea61efaa0f38cd839cbee08232f7e2","text":" --- title: 调试运行中的 Pod content_type: task --- 本页解释了如何调试节点上正在运行(或者正在崩溃)的 Pod。 ## {{% heading \"prerequisites\" %}} * 你的 {{< glossary_tooltip text=\"Pod\" term_id=\"pod\" >}} 应该已经调度并正在运行。 如果 Pod 尚未运行,则从 [应用故障排查](/zh/docs/tasks/debug-application-cluster/debug-application/) 开始。 * 对于一些高级调试步骤, 你需要知道 Pod 在哪个节点上运行,并拥有在该节点上执行 shell 命令的权限。 在使用 `kubectl` 运行标准调试步骤时,则不需要这种权限。 ## 检查 Pod 日志 {#examine-pod-logs} 首先,查看受影响的容器的日志: ```shell kubectl logs ${POD_NAME} ${CONTAINER_NAME} ``` 如果你的容器以前崩溃过,你可以访问前一个容器的崩溃日志: ```shell kubectl logs --previous ${POD_NAME} ${CONTAINER_NAME} ``` ## 使用容器 exec 调试 {#container-exec} 如果 {{< glossary_tooltip text=\"容器镜像\" term_id=\"image\" >}} 包含调试工具,就像基于 Linux 和 Windows 基础镜像构建的镜像一样, 你可以使用 `kubectl exec` 在特定的容器中执行命令: ```shell kubectl exec ${POD_NAME} -c ${CONTAINER_NAME} -- ${CMD} ${ARG1} ${ARG2} ... ${ARGN} ``` {{< note >}} `-c ${CONTAINER_NAME}` 是可选项。 对于单容器 Pod,可以省略此参数。 {{< /note >}} 例如,要查看正在运行的 Cassandra Pod 的日志,可以执行: ```shell kubectl exec cassandra -- cat /var/log/cassandra/system.log ``` 你可以使用 `kubectl exec` 的 `-i` 和 `-t` 参数启动一个连接到终端的 shell,例如: ```shell kubectl exec -it cassandra -- sh ``` 更多细节,参见 [获取运行容器的 Shell]( /zh/docs/tasks/debug-application-cluster/get-shell-running-container/)。 ## 使用临时调试容器进行调试 {#ephemeral-container} {{< feature-state state=\"alpha\" for_k8s_version=\"v1.18\" >}} 因为容器已经崩溃,或因为容器镜像没有内含调试工具,比如 [distroless images](https://github.com/GoogleContainerTools/distroless), 导致 `kubectl exec` 不足以解决问题时, {{< glossary_tooltip text=\"Ephemeral containers\" term_id=\"ephemeral-container\" >}} 对交互式故障诊断非常有用。 从 `v1.18` 开始,`kubectl` 提供 alpha 命令,它可以为调试创建临时容器。 ## 示例:使用临时容器调试 {#ephemeral-container-example} {{< note >}} 本节中的示例要求在集群启用 `EphemeralContainers` [特性门控]( /zh/docs/reference/command-line-tools-reference/feature-gates/ )。 并且要求 `kubectl` v1.18 或更高版本。 {{< /note >}} 可以使用 `kubectl alpha debug` 命令将临时容器添加到正在运行的 Pod 中。 首先,为本例创建一个 Pod: ```shell kubectl run ephemeral-demo --image=k8s.gcr.io/pause:3.1 --restart=Never ``` {{< note >}} 本节在示例中使用 `pause` 容器镜像, 是因为它不包含用户态的调试工具。 但此方法适用于所有容器镜像。 {{< /note >}} 如果你试图使用 `kubectl exec` 去建立一个 shell, 你会看到一个报错, 这是因为在容器镜像中并没有包含 shell。 ```shell kubectl exec -it ephemeral-demo -- sh ``` ``` OCI runtime exec failed: exec failed: container_linux.go:346: starting container process caused \"exec: \"sh\": executable file not found in $PATH\": unknown ``` 你可以使用 `kubectl alpha debug` 添加一个调试容器。 如果指定了 `-i`/`--interactive` 参数, `kubectl` 将自动连接到临时容器的控制台。 ```shell kubectl alpha debug -it ephemeral-demo --image=busybox --target=ephemeral-demo ``` ``` Defaulting debug container name to debugger-8xzrl. If you don't see a command prompt, try pressing enter. / # ``` 此命令添加一个新的 busybox 容器并连接。 `--target` 参数指定了另一个容器的进程命名空间。 这里必须这样做,因为 `kubectl run` 没有在它创建的 Pod 中启用 [进程命名空间共享](/zh/docs/tasks/configure-pod-container/share-process-namespace/) 。 {{< note >}} {{< glossary_tooltip text=\"Container Runtime\" term_id=\"container-runtime\" >}} 必须支持 `--target` 参数。 如果不支持,临时容器可能无法启动, 或者可能使用隔离的进程名称空间启动。 {{< /note >}} 可以使用 `kubectl describe` 查看新创建的临时容器的状态: ```shell kubectl describe pod ephemeral-demo ``` ``` ... Ephemeral Containers: debugger-8xzrl: Container ID: docker://b888f9adfd15bd5739fefaa39e1df4dd3c617b9902082b1cfdc29c4028ffb2eb Image: busybox Image ID: docker-pullable://busybox@sha256:1828edd60c5efd34b2bf5dd3282ec0cc04d47b2ff9caa0b6d4f07a21d1c08084 Port: Host Port: State: Running Started: Wed, 12 Feb 2020 14:25:42 +0100 Ready: False Restart Count: 0 Environment: Mounts: ... ``` 完成后,使用 `kubectl delete` 删除 Pod: ```shell kubectl delete pod ephemeral-demo ``` ## 通过节点上的 shell 进行调试 {#node-shell-session} 如果这些方法都不起作用, 你可以找到运行 Pod 的主机并通过 SSH 连接到该主机, 但是 Kubernetes API 中的工具通常不需要这样做。 因此,如果你发现自己需要 ssh 到一台机器上,请在 GitHub 上提交一个功能请求,描述你的用例以及为什么这些工具不够用。 "} {"_id":"q-en-website-fbcb0d8970043ec8a2cfde76f601a1a1ba170e38f1b36e24091be98f9203e98f","text":"display: block; height: 100%; position: fixed; width: 100%; z-index: 1; top: 0; left: 0; background-color: rgba(51, 113, 227, 3%); border-right: 1px solid #dee2e6; overflow-x: hidden; overflow-x: scroll; padding-top: .5rem; }"} {"_id":"q-en-website-fd0cbc83ba0cc4b20f3d71feafacee94b3e4d5bd7168484bbacf10d8d8a67d70","text":"## The Kubernetes network model Every [`Pod`](/docs/concepts/workloads/pods/) in a cluster gets its own unique cluster-wide IP address. Every [`Pod`](/docs/concepts/workloads/pods/) in a cluster gets its own unique cluster-wide IP address (one address per IP address family). This means you do not need to explicitly create links between `Pods` and you almost never need to deal with mapping container ports to host ports. This creates a clean, backwards-compatible model where `Pods` can be treated"} {"_id":"q-en-website-fd5d0ba3cb168aaf9c02fcfddda93dbd90328197d0186969b5781d0059d49701","text":"snowflake 2/2 2 2 2m ``` ```shell kubectl get pods -l run=snowflake -n=development kubectl get pods -l app=snowflake -n=development ``` ``` NAME READY STATUS RESTARTS AGE"} {"_id":"q-en-website-feac750fe5feeabe2eaa51f3bf5181f754900cfc68319e210d0748d264da4001","text":"to find your localization's two-letter language code. For example, the two-letter code for Korean is `ko`. If the language you are starting a localization for is spoken in various places with significant differences between the variants, it might make sense to combine the lowercased ISO-3166 country code with the language two-letter code. For example, Brazilian Portuguese is localized as `pt-br`. When you start a new localization, you must localize all the [minimum required content](#minimum-required-content) before the Kubernetes project can publish your changes to the live"} {"_id":"q-en-website-ff3b3e626920568a8d96ce53ac93221b7997dee734dae8b67198e019c7821f85","text":"minikube dashboard --url ``` Now, switch back to the terminal where you ran `minikube start`. Now, you can use this URL and switch back to the terminal where you ran `minikube start`. {{% /tab %}} {{< /tabs >}}"} {"_id":"q-en-website-ff6a43eb87245d96ee7938906e454cd20264d58aec05f4b504759eccfcb2b439","text":"### kube-scheduler [kube-scheduler](/docs/admin/kube-scheduler/) watches newly created pods that have no node assigned, and selects a node for them to run on. [kube-scheduler](/docs/admin/kube-scheduler/) watches newly created pods that are not assigned to any node, and selects a node for them to run on. ### addons"}