diff --git a/OWNERS_ALIASES b/OWNERS_ALIASES index 291db36bf2..43f27a88b2 100644 --- a/OWNERS_ALIASES +++ b/OWNERS_ALIASES @@ -41,7 +41,6 @@ aliases: sig-docs-en-owners: # Admins for English content - bradtopol - daminisatya - - gochist - jaredbhatti - jimangel - kbarnard10 @@ -58,7 +57,6 @@ aliases: sig-docs-en-reviews: # PR reviews for English content - bradtopol - daminisatya - - gochist - jaredbhatti - jimangel - kbarnard10 @@ -192,10 +190,12 @@ aliases: - femrtnz - jcjesus - devlware + - jhonmike sig-docs-pt-reviews: # PR reviews for Portugese content - femrtnz - jcjesus - devlware + - jhonmike sig-docs-vi-owners: # Admins for Vietnamese content - huynguyennovem - ngtuna diff --git a/README-id.md b/README-id.md index b178b220bc..1d6b830f2e 100644 --- a/README-id.md +++ b/README-id.md @@ -9,7 +9,7 @@ Selamat datang! Repositori ini merupakan wadah bagi semua komponen yang dibutuhk Pertama, kamu dapat menekan tombol **Fork** yang berada pada bagian atas layar, untuk menyalin repositori pada akun Github-mu. Salinan ini disebut sebagai **fork**. Kamu dapat menambahkan konten pada **fork** yang kamu miliki, setelah kamu merasa cukup untuk menambahkan konten yang kamu miliki dan ingin memberikan konten tersebut pada kami, kamu dapat melihat **fork** yang telah kamu buat dan membuat **pull request** untuk memberi tahu kami bahwa kamu ingin menambahkan konten yang telah kamu buat. -Setelah kamu membuat sebuah **pull request**, seorang **reviewer** akan memberikan masukan terhadap konten yang kamu sediakan serta beberapa hal yang dapat kamu lakukan apabila perbaikan diperlukan terhadap konten yang telah kamu sediakan. Sebagai seorang yang membuat **pull request**, **sudah menjadi kewajiban kamu untuk melakukan modifikasi terhadap konten yang kamu berikan sesuai dengan masukan yang diberikan oleh seorang reviewer Kubernetes**. Perlu kamu ketahui bahwa kamu dapat saja memiliki lebih dari satu orang **reviewer Kubernetes** atau dalam kasus kamu bisa saja mendapatkan **reviewer Kubernetes** yang berbeda dengan **reviewer Kubernetes** awal yang ditugaskan untuk memberikan masukan terhadap konten yang kamu sediakan. Selain itu, seorang **reviewer Kubernetes** bisa saja meminta masukan teknis dari [reviewer teknis Kubernetes](https://github.com/kubernetes/website/wiki/Tech-reviewers) jika diperlukan. +Setelah kamu membuat sebuah **pull request**, seorang **reviewer** akan memberikan masukan terhadap konten yang kamu sediakan serta beberapa hal yang dapat kamu lakukan apabila perbaikan diperlukan terhadap konten yang telah kamu sediakan. Sebagai seorang yang membuat **pull request**, **sudah menjadi kewajiban kamu untuk melakukan modifikasi terhadap konten yang kamu berikan sesuai dengan masukan yang diberikan oleh seorang reviewer Kubernetes**. Perlu kamu ketahui bahwa kamu dapat saja memiliki lebih dari satu orang **reviewer Kubernetes** atau dalam kasus kamu bisa saja mendapatkan **reviewer Kubernetes** yang berbeda dengan **reviewer Kubernetes** awal yang ditugaskan untuk memberikan masukan terhadap konten yang kamu sediakan. Selain itu, seorang **reviewer Kubernetes** bisa saja meminta masukan teknis dari [reviewer teknis Kubernetes](https://github.com/kubernetes/website/wiki/Tech-reviewers) jika diperlukan. Untuk informasi lebih lanjut mengenai tata cara melakukan kontribusi, kamu dapat melihat tautan di bawah ini: @@ -21,11 +21,11 @@ Untuk informasi lebih lanjut mengenai tata cara melakukan kontribusi, kamu dapat ## Menjalankan Dokumentasi Kubernetes pada Mesin Lokal Kamu -Petunjuk yang disarankan untuk menjalankan Dokumentasi Kubernetes pada mesin lokal kamus adalah dengan menggunakan [Docker](https://docker.com) **image** yang memiliki **package** [Hugo](https://gohugo.io), **Hugo** sendiri merupakan generator website statis. +Petunjuk yang disarankan untuk menjalankan Dokumentasi Kubernetes pada mesin lokal kamus adalah dengan menggunakan [Docker](https://docker.com) **image** yang memiliki **package** [Hugo](https://gohugo.io), **Hugo** sendiri merupakan generator website statis. > Jika kamu menggunakan Windows, kamu mungkin membutuhkan beberapa langkah tambahan untuk melakukan instalasi perangkat lunak yang dibutuhkan. Instalasi ini dapat dilakukan dengan menggunakan [Chocolatey](https://chocolatey.org). `choco install make` -> Jika kamu ingin menjalankan **website** tanpa menggunakan **Docker**, kamu dapat melihat tautan berikut [Petunjuk untuk menjalankan website pada mesin lokal dengan menggunakan Hugo](#petunjuk-untuk-menjalankan-website-pada-mesin-lokal-denga-menggunakan-hugo) di bagian bawah. +> Jika kamu ingin menjalankan **website** tanpa menggunakan **Docker**, kamu dapat melihat tautan berikut [Petunjuk untuk menjalankan website pada mesin lokal dengan menggunakan Hugo](#petunjuk-untuk-menjalankan-website-pada-mesin-lokal-dengan-menggunakan-hugo) di bagian bawah. Jika kamu sudah memiliki **Docker** [yang sudah dapat digunakan](https://www.docker.com/get-started), kamu dapat melakukan **build** `kubernetes-hugo` **Docker image** secara lokal: @@ -44,7 +44,7 @@ Buka **browser** kamu ke http://localhost:1313 untuk melihat laman dokumentasi. ## Petunjuk untuk menjalankan website pada mesin lokal dengan menggunakan Hugo -Kamu dapat melihat [dokumentasi resmi Hugo](https://gohugo.io/getting-started/installing/) untuk mengetahui langkah yang diperlukan untuk melakukan instalasi **Hugo**. Pastikan kamu melakukan instalasi versi **Hugo** sesuai dengan versi yang tersedia pada **environment variable** `HUGO_VERSION` pada **file**[`netlify.toml`](netlify.toml#L9). +Kamu dapat melihat [dokumentasi resmi Hugo](https://gohugo.io/getting-started/installing/) untuk mengetahui langkah yang diperlukan untuk melakukan instalasi **Hugo**. Pastikan kamu melakukan instalasi versi **Hugo** sesuai dengan versi yang tersedia pada **environment variable** `HUGO_VERSION` pada **file**[`netlify.toml`](netlify.toml#L9). Untuk menjalankan laman pada mesin lokal setelah instalasi **Hugo**, kamu dapat menjalankan perintah berikut: diff --git a/README-it.md b/README-it.md index e94f770ca9..5530a673e5 100644 --- a/README-it.md +++ b/README-it.md @@ -21,11 +21,11 @@ Per maggiori informazioni su come contribuire alla documentazione Kubernetes, ve ## Eseguire il sito Web localmente usando Docker -Il modo consigliato per eseguire localmente il sito Web Kubernetes prevede l'utilizzo di un'immagine [Docker] (https://docker.com) inclusa nel sito e configurata con tutti i software necessari, a partire dal generatore di siti web statici [Hugo] (https://gohugo.io). +Il modo consigliato per eseguire localmente il sito Web Kubernetes prevede l'utilizzo di un'immagine [Docker](https://docker.com) inclusa nel sito e configurata con tutti i software necessari, a partire dal generatore di siti web statici [Hugo](https://gohugo.io). -> Se stai utilizzando Windows, avrai bisogno di alcuni strumenti aggiuntivi che puoi installare con [Chocolatey] (https://chocolatey.org). `choco install make` +> Se stai utilizzando Windows, avrai bisogno di alcuni strumenti aggiuntivi che puoi installare con [Chocolatey](https://chocolatey.org). `choco install make` -> Se preferisci eseguire il sito Web localmente senza Docker, vedi [Eseguire il sito Web localmente utilizzando Hugo](# running-the-site-local-using-hugo) di seguito. +> Se preferisci eseguire il sito Web localmente senza Docker, vedi [Eseguire il sito Web localmente utilizzando Hugo](#eseguire-il-sito-web-localmente-utilizzando-hugo) di seguito. Se hai Docker [attivo e funzionante](https://www.docker.com/get-started), crea l'immagine Docker `kubernetes-hugo` localmente: diff --git a/README-vi.md b/README-vi.md index 454d687d02..b06b6df368 100644 --- a/README-vi.md +++ b/README-vi.md @@ -26,7 +26,7 @@ Cách được đề xuất để chạy trang web Kubernetes cục bộ là dù > Nếu bạn làm việc trên môi trường Windows, bạn sẽ cần thêm môt vài công cụ mà bạn có thể cài đặt với [Chocolatey](https://chocolatey.org). `choco install make` -> Nếu bạn không muốn dùng Docker để chạy trang web cục bộ, hãy xem [Chạy website cục bộ dùng Hugo](#Chạy website cục bộ dùng Hugo) dưới đây. +> Nếu bạn không muốn dùng Docker để chạy trang web cục bộ, hãy xem [Chạy website cục bộ dùng Hugo](#chạy-website-cục-bộ-dùng-hugo) dưới đây. Nếu bạn có Docker đang [up và running](https://www.docker.com/get-started), build `kubernetes-hugo` Docker image cục bộ: diff --git a/assets/sass/_desktop.sass b/assets/sass/_desktop.sass index cc75a377d7..6eda82df7b 100644 --- a/assets/sass/_desktop.sass +++ b/assets/sass/_desktop.sass @@ -107,7 +107,7 @@ $video-section-height: 550px padding-right: 10px #home - section, header, footer + section, header .main-section max-width: 1000px @@ -178,16 +178,18 @@ $video-section-height: 550px nav overflow: hidden margin-bottom: 20px + display: flex + justify-content: space-between a - width: 16.65% + width: auto float: left font-size: 24px font-weight: 300 white-space: nowrap .social - padding: 0 30px + padding: 0 max-width: 1200px div diff --git a/assets/sass/_tablet.sass b/assets/sass/_tablet.sass index 96b24322a2..a8d1ce36ed 100644 --- a/assets/sass/_tablet.sass +++ b/assets/sass/_tablet.sass @@ -133,18 +133,21 @@ $feature-box-div-width: 45% max-width: 25% max-height: 100% transform: translateY(-50%) + width: 100% &:nth-child(odd) padding-right: 210px .image-wrapper right: 0 + text-align: right &:nth-child(even) padding-left: 210px .image-wrapper left: 0 + text-align: left &:nth-child(1) padding-right: 0 @@ -219,9 +222,8 @@ $feature-box-div-width: 45% footer nav text-align: center - a - width: 30% + width: auto padding: 0 20px .social diff --git a/content/de/docs/concepts/_index.md b/content/de/docs/concepts/_index.md index b8fc0272db..82b5b0e5b0 100644 --- a/content/de/docs/concepts/_index.md +++ b/content/de/docs/concepts/_index.md @@ -52,7 +52,7 @@ Wenn Sie beispielsweise mit der Kubernetes-API ein Deployment-Objekt erstellen, ### Kubernetes Master -Der Kubernetes-Master ist für Erhalt des gewünschten Status Ihres Clusters verantwortlich. Wenn Sie mit Kubernetes interagieren, beispielsweise mit dem Kommanduzeilen-Tool `kubectl`, kommunizieren Sie mit dem Kubernetes-Master Ihres Clusters. +Der Kubernetes-Master ist für Erhalt des gewünschten Status Ihres Clusters verantwortlich. Wenn Sie mit Kubernetes interagieren, beispielsweise mit dem Kommandozeilen-Tool `kubectl`, kommunizieren Sie mit dem Kubernetes-Master Ihres Clusters. > Der Begriff "Master" bezeichnet dabei eine Reihe von Prozessen, die den Clusterstatus verwalten. Normalerweise werden diese Prozesse alle auf einem einzigen Node im Cluster ausgeführt. Dieser Node wird auch als Master bezeichnet. Der Master kann repliziert werden, um die Verfügbarkeit und Redundanz zu erhöhen. diff --git a/content/de/docs/setup/minikube.md b/content/de/docs/setup/minikube.md index f4d19ea80c..06734bd28f 100644 --- a/content/de/docs/setup/minikube.md +++ b/content/de/docs/setup/minikube.md @@ -205,7 +205,7 @@ Weitere Informationen zu unterstützten Treibern und zur Installation von Plugin ### Lokale Images durch erneute Verwendung des Docker-Daemon ausführen -Wenn Sie eine einzige Kubernetes VM verwenden, ist es sehr praktisch, den integrierten Docker-Daemon von Minikube wiederzuverwenden; Dies bedeutet, dass Sie auf Ihrem lokalen Computer keine Docker-Registy erstellen und das Image in die Registry importortieren müssen - Sie können einfach innerhalb desselben Docker-Daemons wie Minikube arbeiten, was lokale Experimente beschleunigt. Stellen Sie einfach sicher, dass Sie Ihr Docker-Image mit einem anderen Element als 'latest' versehen, und verwenden Sie dieses Tag, wenn Sie das Image laden. Andernfalls, wenn Sie keine Version Ihres Images angeben, wird es als `:latest` angenommen, mit der Pull-Image-Richtlinie von `Always` entsprechend, was schließlich zu `ErrImagePull` führen kann, da Sie möglicherweise noch keine Versionen Ihres Docker-Images in der Standard-Docker-Registry (normalerweise DockerHub) haben. +Wenn Sie eine einzige Kubernetes VM verwenden, ist es sehr praktisch, den integrierten Docker-Daemon von Minikube wiederzuverwenden; Dies bedeutet, dass Sie auf Ihrem lokalen Computer keine Docker-Registy erstellen und das Image in die Registry importieren müssen - Sie können einfach innerhalb desselben Docker-Daemons wie Minikube arbeiten, was lokale Experimente beschleunigt. Stellen Sie einfach sicher, dass Sie Ihr Docker-Image mit einem anderen Element als 'latest' versehen, und verwenden Sie dieses Tag, wenn Sie das Image laden. Andernfalls, wenn Sie keine Version Ihres Images angeben, wird es als `:latest` angenommen, mit der Pull-Image-Richtlinie von `Always` entsprechend, was schließlich zu `ErrImagePull` führen kann, da Sie möglicherweise noch keine Versionen Ihres Docker-Images in der Standard-Docker-Registry (normalerweise DockerHub) haben. Um mit dem Docker-Daemon auf Ihrem Mac/Linux-Computer arbeiten zu können, verwenden Sie den `docker-env`-Befehl in Ihrer Shell: diff --git a/content/en/_index.html b/content/en/_index.html index 0be8e71375..8beda75ada 100644 --- a/content/en/_index.html +++ b/content/en/_index.html @@ -45,12 +45,12 @@ Kubernetes is open source giving you the freedom to take advantage of on-premise


- Attend KubeCon in Amsterdam on Mar. 30-Apr. 2, 2020 + Attend KubeCon in Amsterdam in July/August TBD



- Attend KubeCon in Shanghai on July 28-30, 2020 + Attend KubeCon in Boston on November 17-20, 2020
diff --git a/content/en/blog/_posts/2019-07-18-some-apis-are-being-deprecated.md b/content/en/blog/_posts/2019-07-18-some-apis-are-being-deprecated.md index 9639e87a53..587080617c 100644 --- a/content/en/blog/_posts/2019-07-18-some-apis-are-being-deprecated.md +++ b/content/en/blog/_posts/2019-07-18-some-apis-are-being-deprecated.md @@ -23,30 +23,30 @@ The **v1.16** release will stop serving the following deprecated API versions in Existing persisted data can be retrieved/updated via the new version. * Notable changes: * `spec.templateGeneration` is removed - * `spec.selector` is now required and immutable after creation - * `spec.updateStrategy.type` now defaults to `RollingUpdate` + * `spec.selector` is now required and immutable after creation; use the existing template labels as the selector for seamless upgrades + * `spec.updateStrategy.type` now defaults to `RollingUpdate` (the default in `extensions/v1beta1` was `OnDelete`) * Deployment in the **extensions/v1beta1**, **apps/v1beta1**, and **apps/v1beta2** API versions is no longer served * Migrate to use the **apps/v1** API version, available since v1.9. Existing persisted data can be retrieved/updated via the new version. * Notable changes: * `spec.rollbackTo` is removed - * `spec.selector` is now required and immutable after creation - * `spec.progressDeadlineSeconds` now defaults to `600` seconds - * `spec.revisionHistoryLimit` now defaults to `10` - * `maxSurge` and `maxUnavailable` now default to `25%` + * `spec.selector` is now required and immutable after creation; use the existing template labels as the selector for seamless upgrades + * `spec.progressDeadlineSeconds` now defaults to `600` seconds (the default in `extensions/v1beta1` was no deadline) + * `spec.revisionHistoryLimit` now defaults to `10` (the default in `apps/v1beta1` was `2`, the default in `extensions/v1beta1` was to retain all) + * `maxSurge` and `maxUnavailable` now default to `25%` (the default in `extensions/v1beta1` was `1`) * StatefulSet in the **apps/v1beta1** and **apps/v1beta2** API versions is no longer served * Migrate to use the **apps/v1** API version, available since v1.9. Existing persisted data can be retrieved/updated via the new version. * Notable changes: - * `spec.selector` is now required and immutable after creation - * `spec.updateStrategy.type` now defaults to `RollingUpdate` + * `spec.selector` is now required and immutable after creation; use the existing template labels as the selector for seamless upgrades + * `spec.updateStrategy.type` now defaults to `RollingUpdate` (the default in `apps/v1beta1` was `OnDelete`) * ReplicaSet in the **extensions/v1beta1**, **apps/v1beta1**, and **apps/v1beta2** API versions is no longer served * Migrate to use the **apps/v1** API version, available since v1.9. Existing persisted data can be retrieved/updated via the new version. * Notable changes: - * `spec.selector` is now required and immutable after creation + * `spec.selector` is now required and immutable after creation; use the existing template labels as the selector for seamless upgrades -The **v1.20** release will stop serving the following deprecated API versions in favor of newer and more stable API versions: +The **v1.22** release will stop serving the following deprecated API versions in favor of newer and more stable API versions: * Ingress in the **extensions/v1beta1** API version will no longer be served * Migrate to use the **networking.k8s.io/v1beta1** API version, available since v1.14. @@ -84,8 +84,8 @@ apiserver startup arguments: Deprecations are announced in the Kubernetes release notes. You can see these announcements in -[1.14](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG-1.14.md#deprecations) -and [1.15](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG-1.15.md#deprecations-and-removals). +[1.14](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.14.md#deprecations) +and [1.15](https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG/CHANGELOG-1.15.md#deprecations-and-removals). You can read more [in our deprecation policy document](https://kubernetes.io/docs/reference/using-api/deprecation-policy/#deprecating-parts-of-the-api) about the deprecation policies for Kubernetes APIs, and other Kubernetes components. diff --git a/content/en/blog/_posts/2020-01-21-csi-ephemeral-inline-volumes.md b/content/en/blog/_posts/2020-01-21-csi-ephemeral-inline-volumes.md index 46570a3e5a..b1574e341d 100644 --- a/content/en/blog/_posts/2020-01-21-csi-ephemeral-inline-volumes.md +++ b/content/en/blog/_posts/2020-01-21-csi-ephemeral-inline-volumes.md @@ -186,7 +186,7 @@ metadata: spec: containers: - name: nginx - image: nginx:1.13-alpine + image: nginx:1.16-alpine ports: - containerPort: 80 volumeMounts: diff --git a/content/en/blog/_posts/2020-03-04-Contributor-Summit-Delayed.md b/content/en/blog/_posts/2020-03-04-Contributor-Summit-Delayed.md new file mode 100644 index 0000000000..1996b6201e --- /dev/null +++ b/content/en/blog/_posts/2020-03-04-Contributor-Summit-Delayed.md @@ -0,0 +1,15 @@ +--- +layout: blog +title: Contributor Summit Amsterdam Postponed +date: 2020-03-04 +slug: Contributor-Summit-Delayed +--- + +**Authors:** Dawn Foster (VMware), Jorge Castro (VMware) + +The CNCF has announced that [KubeCon + CloudNativeCon EU has been delayed](https://events.linuxfoundation.org/kubecon-cloudnativecon-europe/attend/novel-coronavirus-update/) until July/August of 2020. As a result the Contributor Summit planning team is weighing options for how to proceed. Here’s the current plan: + +- There will be an in-person Contributor Summit as planned when KubeCon + CloudNativeCon is rescheduled. +- We are looking at options for having additional virtual contributor activities in the meantime. + +We will communicate via this blog and the usual communications channels on the final plan. Please bear with us as we adapt when we get more information. Thank you for being patient as the team pivots to bring you a great Contributor Summit! \ No newline at end of file diff --git a/content/en/blog/_posts/2020-03-16-kubernetes-the-hard-way.md b/content/en/blog/_posts/2020-03-16-kubernetes-the-hard-way.md new file mode 100644 index 0000000000..422ee78527 --- /dev/null +++ b/content/en/blog/_posts/2020-03-16-kubernetes-the-hard-way.md @@ -0,0 +1,42 @@ +--- +layout: blog +title: Join SIG Scalability and Learn Kubernetes the Hard Way +date: 2020-03-19 +slug: join-sig-scalability +--- + +**Authors:** Alex Handy + +Contributing to SIG Scalability is a great way to learn Kubernetes in all its depth and breadth, and the team would love to have you [join as a contributor](https://github.com/kubernetes/community/tree/master/sig-scalability#scalability-special-interest-group). I took a look at the value of learning the hard way and interviewed the current SIG chairs to give you an idea of what contribution feels like. + +## The value of Learning The Hard Way + +There is a belief in the software development community that pushes for the most challenging and rigorous possible method of learning a new language or system. These tend to go by the moniker of "Learn \_\_ the Hard Way." Examples abound: Learn Code the Hard Way, Learn Python the Hard Way, and many others originating with Zed Shaw's courses in the topic. + +While there are folks out there who offer you a "Learn Kubernetes the Hard Way" type experience (most notably [Kelsey Hightower's](https://github.com/kelseyhightower/kubernetes-the-hard-way)), any "Hard Way" project should attempt to cover every aspect of the core topic's principles. + +Therefore, the real way to "Learn Kubernetes the Hard Way," is to join the CNCF and get involved in the project itself. And there is only one SIG that could genuinely offer a full-stack learning experience for Kubernetes: SIG Scalability. + +The team behind SIG Scalability is responsible for detecting and dealing with issues that arise when Kubernetes clusters are working with upwards of a thousand nodes. Said [Wojiciech Tyczynski](https://github.com/wojtek-t), a staff software engineer at Google and a member of SIG Scalability, the standard size for a test cluster for this SIG is over 5,000 nodes. + +And yet, this SIG is not composed of Ph.D.'s in highly scalable systems designs. Many of the folks working with Tyczynski, for example, joined the SIG knowing very little about these types of issues, and often, very little about Kubernetes. + +Working on SIG Scalability is like jumping into the deep end of the pool to learn to swim, and the SIG is inherently concerned with the entire Kubernetes project. SIG Scalability focuses on how Kubernetes functions as a whole and at scale. The SIG Scalability team members have an impetus to learn about every system and to understand how all systems interact with one another. + +## A complex and rewarding contributor experience + +While that may sound complicated (and it is!), that doesn't mean it's outside the reach of an average developer, tester, or administrator. Google software developer Matt Matejczyk has only been on the team since the beginning of 2019, and he's been a valued member of the team since then, ferreting out bugs. + +"I am new here," said Matejczyk. "I joined the team in January [2019]. Before that, I worked on AdWords at Google in New York. Why did I join? I knew some people there, so that was one of the decisions for me to move. I thought at that time that Kubernetes is a unique, cutting edge technology. I thought it'd be cool to work on that." + +Matejczyk was correct about the coolness. "It's cool," he said. "So actually, ramping up on scalability is not easy. There are many things you need to understand. You need to understand Kubernetes very well. It can use every part of Kubernetes. I am still ramping up after these 8 months. I think it took me maybe 3 months to get up to decent speed." + +When Matejczyk spoke to what he had worked on during those 8 months, he answered, "An interesting example is a regression I have been working on recently. We noticed the overall slowness of Kubernetes control plane in specific scenarios, and we couldn't attribute it to any particular component. In the end, we realized that everything boiled down to the memory allocation on the golang level. It was very counterintuitive to have two completely separate pieces of code (running as a part of the same binary) affecting the performance of each other only because one of them was allocating memory too fast. But connecting all the dots and getting to the bottom of regression like this gives great satisfaction." + +Tyczynski said that "It's not only debugging regressions, but it's also debugging and finding bottlenecks. In general, those can be regressions, but those can be things we can improve. The other significant area is extending what we want to guarantee to users. Extending SLA and SLO coverage of the system so users can rely on what they can expect from the system in terms of performance and scalability. Matt is doing much work in extending our tests to be more representative and cover more Kubernetes concepts." + +## Give SIG Scalability a try + +The SIG Scalability team is always in need of new members, and if you're the sort of developer or tester who loves taking on new complex challenges, and perhaps loves learning things the hard way, consider joining this SIG. As the team points out, adding Kubernetes expertise to your resume is never a bad idea, and this is the one SIG where you can learn it all from top to bottom. + +See [the SIG's documentation](https://github.com/kubernetes/community/tree/master/sig-scalability#scalability-special-interest-group) to learn about upcoming meetings, its charter, and more. You can also join the [#sig-scalability Slack channel](https://kubernetes.slack.com/archives/C09QZTRH7) to see what it's like. We hope to see you join in to take advantage of this great opportunity to learn Kubernetes and contribute back at the same time. diff --git a/content/en/blog/_posts/Kong-Ingress-Controller-and-Service-Mesh.md b/content/en/blog/_posts/Kong-Ingress-Controller-and-Service-Mesh.md new file mode 100644 index 0000000000..9e9a4a5dd4 --- /dev/null +++ b/content/en/blog/_posts/Kong-Ingress-Controller-and-Service-Mesh.md @@ -0,0 +1,198 @@ +--- +layout: blog +title: 'Kong Ingress Controller and Service Mesh: Setting up Ingress to Istio on Kubernetes' +date: 2020-03-18 +slug: kong-ingress-controller-and-istio-service-mesh +--- + +**Author:** Kevin Chen, Kong + +Kubernetes has become the de facto way to orchestrate containers and the services within services. But how do we give services outside our cluster access to what is within? Kubernetes comes with the Ingress API object that manages external access to services within a cluster. + +Ingress is a group of rules that will proxy inbound connections to endpoints defined by a backend. However, Kubernetes does not know what to do with Ingress resources without an Ingress controller, which is where an open source controller can come into play. In this post, we are going to use one option for this: the Kong Ingress Controller. The Kong Ingress Controller was open-sourced a year ago and recently reached one million downloads. In the recent 0.7 release, service mesh support was also added. Other features of this release include: + +* **Built-In Kubernetes Admission Controller,** which validates Custom Resource Definitions (CRD) as they are created or updated and rejects any invalid configurations. +* **n-Memory Mode** - Each pod’s controller actively configures the Kong container in its pod, which limits the blast radius of failure of a single container of Kong or controller container to that pod only. +* **Native gRPC Routing** - gRPC traffic can now be routed via Kong Ingress Controller natively with support for method-based routing. + +![K4K-gRPC](/images/blog/Kong-Ingress-Controller-and-Service-Mesh/KIC-gRPC.png) + +If you would like a deeper dive into Kong Ingress Controller 0.7, please check out the [GitHub repository](https://github.com/Kong/kubernetes-ingress-controller). + +But let’s get back to the service mesh support since that will be the main focal point of this blog post. Service mesh allows organizations to address microservices challenges related to security, reliability, and observability by abstracting inter-service communication into a mesh layer. But what if our mesh layer sits within Kubernetes and we still need to expose certain services beyond our cluster? Then you need an Ingress controller such as the Kong Ingress Controller. In this blog post, we’ll cover how to deploy Kong Ingress Controller as your Ingress layer to an Istio mesh. Let’s dive right in: + +![Kong Kubernetes Ingress Controller](/images/blog/Kong-Ingress-Controller-and-Service-Mesh/k4k8s.png) + +### Part 0: Set up Istio on Kubernetes + +This blog will assume you have Istio set up on Kubernetes. If you need to catch up to this point, please check out the [Istio documentation](https://istio.io/docs/setup/). It will walk you through setting up Istio on Kubernetes. + +### 1. Install the Bookinfo Application + +First, we need to label the namespaces that will host our application and Kong proxy. To label our default namespace where the bookinfo app sits, run this command: + +``` +$ kubectl label namespace default istio-injection=enabled +namespace/default labeled +``` + +Then create a new namespace that will be hosting our Kong gateway and the Ingress controller: + +``` +$ kubectl create namespace kong +namespace/kong created +``` + +Because Kong will be sitting outside the default namespace, be sure you also label the Kong namespace with istio-injection enabled as well: + +``` +$ kubectl label namespace kong istio-injection=enabled +namespace/kong labeled +``` + +Having both namespaces labeled istio-injection=enabled is necessary. Or else the default configuration will not inject a sidecar into the pods of your namespaces. + +Now deploy your BookInfo application with the following command: + +``` +$ kubectl apply -f http://bit.ly/bookinfoapp +service/details created +serviceaccount/bookinfo-details created +deployment.apps/details-v1 created +service/ratings created +serviceaccount/bookinfo-ratings created +deployment.apps/ratings-v1 created +service/reviews created +serviceaccount/bookinfo-reviews created +deployment.apps/reviews-v1 created +deployment.apps/reviews-v2 created +deployment.apps/reviews-v3 created +service/productpage created +serviceaccount/bookinfo-productpage created +deployment.apps/productpage-v1 created +``` + +Let’s double-check our services and pods to make sure that we have it all set up correctly: + +``` +$ kubectl get services +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +details ClusterIP 10.97.125.254 9080/TCP 29s +kubernetes ClusterIP 10.96.0.1 443/TCP 29h +productpage ClusterIP 10.97.62.68 9080/TCP 28s +ratings ClusterIP 10.96.15.180 9080/TCP 28s +reviews ClusterIP 10.104.207.136 9080/TCP 28s +``` + +You should see four new services: details, productpage, ratings, and reviews. None of them have an external IP so we will use the [Kong gateway](https://github.com/Kong/kong) to expose the necessary services. And to check pods, run the following command: + +``` +NAME READY STATUS RESTARTS AGE +details-v1-c5b5f496d-9wm29 2/2 Running 0 101s +productpage-v1-7d6cfb7dfd-5mc96 2/2 Running 0 100s +ratings-v1-f745cf57b-hmkwf 2/2 Running 0 101s +reviews-v1-85c474d9b8-kqcpt 2/2 Running 0 101s +reviews-v2-ccffdd984-9jnsj 2/2 Running 0 101s +reviews-v3-98dc67b68-nzw97 2/2 Running 0 101s +``` + +is command outputs useful data, so let’s take a second to understand it. If you examine the READY column, each pod has two containers running: the service and an Envoy sidecar injected alongside it. Another thing to highlight is that there are three review pods but only 1 review service. The Envoy sidecar will load balance the traffic to three different review pods that contain different versions, giving us the ability to A/B test our changes. With that said, you should now be able to access your product page! + +``` +$ kubectl exec -it $(kubectl get pod -l app=ratings -o jsonpath='{.items[0].metadata.name}') -c ratings -- curl productpage:9080/productpage | grep -o ".*" +Simple Bookstore App +``` + +### 2. Kong Kubernetes Ingress Controller Without Database + +To expose your services to the world, we will deploy Kong as the north-south traffic gateway. [Kong 1.1](https://github.com/Kong/kong/releases/tag/1.1.2) released with declarative configuration and DB-less mode. Declarative configuration allows you to specify the desired system state through a YAML or JSON file instead of a sequence of API calls. Using declarative config provides several key benefits to reduce complexity, increase automation and enhance system performance. And with the Kong Ingress Controller, any Ingress rules you apply to the cluster will automatically be configured on the Kong proxy. Let’s set up the Kong Ingress Controller and the actual Kong proxy first like this: + +``` +$ kubectl apply -f https://bit.ly/k4k8s +namespace/kong configured +customresourcedefinition.apiextensions.k8s.io/kongconsumers.configuration.konghq.com created +customresourcedefinition.apiextensions.k8s.io/kongcredentials.configuration.konghq.com created +customresourcedefinition.apiextensions.k8s.io/kongingresses.configuration.konghq.com created +customresourcedefinition.apiextensions.k8s.io/kongplugins.configuration.konghq.com created +serviceaccount/kong-serviceaccount created +clusterrole.rbac.authorization.k8s.io/kong-ingress-clusterrole created +clusterrolebinding.rbac.authorization.k8s.io/kong-ingress-clusterrole-nisa-binding created +configmap/kong-server-blocks created +service/kong-proxy created +service/kong-validation-webhook created +deployment.apps/ingress-kong created +``` + +To check if the Kong pod is up and running, run: + +``` +$ kubectl get pods -n kong +NAME READY STATUS RESTARTS AGE +pod/ingress-kong-8b44c9856-9s42v 3/3 Running 0 2m26s +``` + +There will be three containers within this pod. The first container is the Kong Gateway that will be the Ingress point to your cluster. The second container is the Ingress controller. It uses Ingress resources and updates the proxy to follow rules defined in the resource. And lastly, the third container is the Envoy proxy injected by Istio. Kong will route traffic through the Envoy sidecar proxy to the appropriate service. To send requests into the cluster via our newly deployed Kong Gateway, setup an environment variable with the IP address at which Kong is accessible. + +``` +$ export PROXY_IP=$(minikube service -n kong kong-proxy --url | head -1) +$ echo $PROXY_IP +http://192.168.99.100:32728 +``` + +Next, we need to change some configuration so that the side-car Envoy process can route the request correctly based on the host/authority header of the request. Run the following to stop the route from preserving host: + +``` +$ echo " +apiVersion: configuration.konghq.com/v1 +kind: KongIngress +metadata: + name: do-not-preserve-host +route: + preserve_host: false +" | kubectl apply -f - +kongingress.configuration.konghq.com/do-not-preserve-host created +``` + +And annotate the existing productpage service to set service-upstream as true: + +``` +$ kubectl annotate svc productpage Ingress.kubernetes.io/service-upstream="true" +service/productpage annotated +``` + +Now that we have everything set up, we can look at how to use the Ingress resource to help route external traffic to the services within your Istio mesh. We’ll create an Ingress rule that routes all traffic with the path of `/` to our productpage service: + +``` +$ echo " +apiVersion: extensions/v1beta1 +kind: Ingress +metadata: + name: productpage + annotations: + configuration.konghq.com: do-not-preserve-host +spec: + rules: + - http: + paths: + - path: / + backend: + serviceName: productpage + servicePort: 9080 +" | kubectl apply -f - +ingress.extensions/productpage created +``` + +And just like that, the Kong Ingress Controller is able to understand the rules you defined in the Ingress resource and routes it to the productpage service! To view the product page service’s GUI, go to [http://](http://{Your)$PROXY_IP/productpage. Or to test it in your command line, try: + +``` +$ curl $PROXY_IP/productpage +``` + +That is all I have for this walk-through. If you enjoyed the technologies used in this post, please check out their repositories since they are all open source and would love to have more contributors! Here are their links for your convenience: + +* Kong: [[GitHub](https://github.com/Kong/kubernetes-ingress-controller)] [[Twitter](https://twitter.com/thekonginc)] +* Kubernetes: [[GitHub](https://github.com/kubernetes/kubernetes)] [[Twitter](https://twitter.com/kubernetesio)] +* Istio: [[GitHub](https://github.com/istio/istio)] [[Twitter](https://twitter.com/IstioMesh)] +* Envoy: [[GitHub](https://github.com/envoyproxy/envoy)] [[Twitter](https://twitter.com/EnvoyProxy)] + +Thank you for following along! diff --git a/content/en/docs/concepts/architecture/nodes.md b/content/en/docs/concepts/architecture/nodes.md index 0b740ad46c..338e9a2408 100644 --- a/content/en/docs/concepts/architecture/nodes.md +++ b/content/en/docs/concepts/architecture/nodes.md @@ -131,6 +131,8 @@ Kubernetes creates a node object internally (the representation), and validates the node by health checking based on the `metadata.name` field. If the node is valid -- that is, if all necessary services are running -- it is eligible to run a pod. Otherwise, it is ignored for any cluster activity until it becomes valid. +The name of a Node object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). {{< note >}} Kubernetes keeps the object for the invalid node and keeps checking to see whether it becomes valid. @@ -157,7 +159,7 @@ controller deletes the node from its list of nodes. The third is monitoring the nodes' health. The node controller is responsible for updating the NodeReady condition of NodeStatus to ConditionUnknown when a node becomes unreachable (i.e. the node controller stops -receiving heartbeats for some reason, e.g. due to the node being down), and then later evicting +receiving heartbeats for some reason, for example due to the node being down), and then later evicting all the pods from the node (using graceful termination) if the node continues to be unreachable. (The default timeouts are 40s to start reporting ConditionUnknown and 5m after that to start evicting pods.) The node controller diff --git a/content/en/docs/concepts/cluster-administration/cloud-providers.md b/content/en/docs/concepts/cluster-administration/cloud-providers.md index 9c031807e0..b9a320192c 100644 --- a/content/en/docs/concepts/cluster-administration/cloud-providers.md +++ b/content/en/docs/concepts/cluster-administration/cloud-providers.md @@ -94,7 +94,7 @@ Different settings can be applied to a load balancer service in AWS using _annot * `service.beta.kubernetes.io/aws-load-balancer-access-log-s3-bucket-prefix`: Used to specify access log s3 bucket prefix. * `service.beta.kubernetes.io/aws-load-balancer-additional-resource-tags`: Used on the service to specify a comma-separated list of key-value pairs which will be recorded as additional tags in the ELB. For example: `"Key1=Val1,Key2=Val2,KeyNoVal1=,KeyNoVal2"`. * `service.beta.kubernetes.io/aws-load-balancer-backend-protocol`: Used on the service to specify the protocol spoken by the backend (pod) behind a listener. If `http` (default) or `https`, an HTTPS listener that terminates the connection and parses headers is created. If set to `ssl` or `tcp`, a "raw" SSL listener is used. If set to `http` and `aws-load-balancer-ssl-cert` is not used then a HTTP listener is used. -* `service.beta.kubernetes.io/aws-load-balancer-ssl-cert`: Used on the service to request a secure listener. Value is a valid certificate ARN. For more, see [ELB Listener Config](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-listener-config.html) CertARN is an IAM or CM certificate ARN, e.g. `arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012`. +* `service.beta.kubernetes.io/aws-load-balancer-ssl-cert`: Used on the service to request a secure listener. Value is a valid certificate ARN. For more, see [ELB Listener Config](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-listener-config.html) CertARN is an IAM or CM certificate ARN, for example `arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012`. * `service.beta.kubernetes.io/aws-load-balancer-connection-draining-enabled`: Used on the service to enable or disable connection draining. * `service.beta.kubernetes.io/aws-load-balancer-connection-draining-timeout`: Used on the service to specify a connection draining timeout. * `service.beta.kubernetes.io/aws-load-balancer-connection-idle-timeout`: Used on the service to specify the idle connection timeout. diff --git a/content/en/docs/concepts/cluster-administration/cluster-administration-overview.md b/content/en/docs/concepts/cluster-administration/cluster-administration-overview.md index a825335304..0512cabc90 100644 --- a/content/en/docs/concepts/cluster-administration/cluster-administration-overview.md +++ b/content/en/docs/concepts/cluster-administration/cluster-administration-overview.md @@ -44,7 +44,7 @@ Note: Not all distros are actively maintained. Choose distros which have been te * [Certificates](/docs/concepts/cluster-administration/certificates/) describes the steps to generate certificates using different tool chains. -* [Kubernetes Container Environment](/docs/concepts/containers/container-environment-variables/) describes the environment for Kubelet managed containers on a Kubernetes node. +* [Kubernetes Container Environment](/docs/concepts/containers/container-environment/) describes the environment for Kubelet managed containers on a Kubernetes node. * [Controlling Access to the Kubernetes API](/docs/reference/access-authn-authz/controlling-access/) describes how to set up permissions for users and service accounts. diff --git a/content/en/docs/concepts/cluster-administration/federation.md b/content/en/docs/concepts/cluster-administration/federation.md deleted file mode 100644 index 7900b53d27..0000000000 --- a/content/en/docs/concepts/cluster-administration/federation.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: Federation -content_template: templates/concept -weight: 80 ---- - -{{% capture overview %}} - -{{< deprecationfilewarning >}} -{{< include "federation-deprecation-warning-note.md" >}} -{{< /deprecationfilewarning >}} - -This page explains why and how to manage multiple Kubernetes clusters using -federation. -{{% /capture %}} - -{{% capture body %}} -## Why federation - -Federation makes it easy to manage multiple clusters. It does so by providing 2 -major building blocks: - - * Sync resources across clusters: Federation provides the ability to keep - resources in multiple clusters in sync. For example, you can ensure that the same deployment exists in multiple clusters. - * Cross cluster discovery: Federation provides the ability to auto-configure DNS servers and load balancers with backends from all clusters. For example, you can ensure that a global VIP or DNS record can be used to access backends from multiple clusters. - -Some other use cases that federation enables are: - -* High Availability: By spreading load across clusters and auto configuring DNS - servers and load balancers, federation minimises the impact of cluster - failure. -* Avoiding provider lock-in: By making it easier to migrate applications across - clusters, federation prevents cluster provider lock-in. - - -Federation is not helpful unless you have multiple clusters. Some of the reasons -why you might want multiple clusters are: - -* Low latency: Having clusters in multiple regions minimises latency by serving - users from the cluster that is closest to them. -* Fault isolation: It might be better to have multiple small clusters rather - than a single large cluster for fault isolation (for example: multiple - clusters in different availability zones of a cloud provider). -* Scalability: There are scalability limits to a single kubernetes cluster (this - should not be the case for most users. For more details: - [Kubernetes Scaling and Performance Goals](https://git.k8s.io/community/sig-scalability/goals.md)). -* [Hybrid cloud](#hybrid-cloud-capabilities): You can have multiple clusters on different cloud providers or - on-premises data centers. - -### Caveats - -While there are a lot of attractive use cases for federation, there are also -some caveats: - -* Increased network bandwidth and cost: The federation control plane watches all - clusters to ensure that the current state is as expected. This can lead to - significant network cost if the clusters are running in different regions on - a cloud provider or on different cloud providers. -* Reduced cross cluster isolation: A bug in the federation control plane can - impact all clusters. This is mitigated by keeping the logic in federation - control plane to a minimum. It mostly delegates to the control plane in - kubernetes clusters whenever it can. The design and implementation also errs - on the side of safety and avoiding multi-cluster outage. -* Maturity: The federation project is relatively new and is not very mature. - Not all resources are available and many are still alpha. [Issue - 88](https://github.com/kubernetes/federation/issues/88) enumerates - known issues with the system that the team is busy solving. - -### Hybrid cloud capabilities - -Federations of Kubernetes Clusters can include clusters running in -different cloud providers (e.g. Google Cloud, AWS), and on-premises -(e.g. on OpenStack). [Kubefed](/docs/tasks/federation/set-up-cluster-federation-kubefed/) is the recommended way to deploy federated clusters. - -Thereafter, your [API resources](#api-resources) can span different clusters -and cloud providers. - -## Setting up federation - -To be able to federate multiple clusters, you first need to set up a federation -control plane. -Follow the [setup guide](/docs/tutorials/federation/set-up-cluster-federation-kubefed/) to set up the -federation control plane. - -## API resources - -Once you have the control plane set up, you can start creating federation API -resources. -The following guides explain some of the resources in detail: - -* [Cluster](/docs/tasks/federation/administer-federation/cluster/) -* [ConfigMap](/docs/tasks/federation/administer-federation/configmap/) -* [DaemonSets](/docs/tasks/federation/administer-federation/daemonset/) -* [Deployment](/docs/tasks/federation/administer-federation/deployment/) -* [Events](/docs/tasks/federation/administer-federation/events/) -* [Hpa](/docs/tasks/federation/administer-federation/hpa/) -* [Ingress](/docs/tasks/federation/administer-federation/ingress/) -* [Jobs](/docs/tasks/federation/administer-federation/job/) -* [Namespaces](/docs/tasks/federation/administer-federation/namespaces/) -* [ReplicaSets](/docs/tasks/federation/administer-federation/replicaset/) -* [Secrets](/docs/tasks/federation/administer-federation/secret/) -* [Services](/docs/concepts/cluster-administration/federation-service-discovery/) - - -The [API reference docs](/docs/reference/federation/) list all the -resources supported by federation apiserver. - -## Cascading deletion - -Kubernetes version 1.6 includes support for cascading deletion of federated -resources. With cascading deletion, when you delete a resource from the -federation control plane, you also delete the corresponding resources in all underlying clusters. - -Cascading deletion is not enabled by default when using the REST API. To enable -it, set the option `DeleteOptions.orphanDependents=false` when you delete a -resource from the federation control plane using the REST API. Using `kubectl -delete` -enables cascading deletion by default. You can disable it by running `kubectl -delete --cascade=false` - -Note: Kubernetes version 1.5 included cascading deletion support for a subset of -federation resources. - -## Scope of a single cluster - -On IaaS providers such as Google Compute Engine or Amazon Web Services, a VM exists in a -[zone](https://cloud.google.com/compute/docs/zones) or [availability -zone](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html). -We suggest that all the VMs in a Kubernetes cluster should be in the same availability zone, because: - - - compared to having a single global Kubernetes cluster, there are fewer single-points of failure. - - compared to a cluster that spans availability zones, it is easier to reason about the availability properties of a - single-zone cluster. - - when the Kubernetes developers are designing the system (e.g. making assumptions about latency, bandwidth, or - correlated failures) they are assuming all the machines are in a single data center, or otherwise closely connected. - -It is recommended to run fewer clusters with more VMs per availability zone; but it is possible to run multiple clusters per availability zones. - -Reasons to prefer fewer clusters per availability zone are: - - - improved bin packing of Pods in some cases with more nodes in one cluster (less resource fragmentation). - - reduced operational overhead (though the advantage is diminished as ops tooling and processes mature). - - reduced costs for per-cluster fixed resource costs, e.g. apiserver VMs (but small as a percentage - of overall cluster cost for medium to large clusters). - -Reasons to have multiple clusters include: - - - strict security policies requiring isolation of one class of work from another (but, see Partitioning Clusters - below). - - test clusters to canary new Kubernetes releases or other cluster software. - -## Selecting the right number of clusters - -The selection of the number of Kubernetes clusters may be a relatively static choice, only revisited occasionally. -By contrast, the number of nodes in a cluster and the number of pods in a service may change frequently according to -load and growth. - -To pick the number of clusters, first, decide which regions you need to be in to have adequate latency to all your end users, for services that will run -on Kubernetes (if you use a Content Distribution Network, the latency requirements for the CDN-hosted content need not -be considered). Legal issues might influence this as well. For example, a company with a global customer base might decide to have clusters in US, EU, AP, and SA regions. -Call the number of regions to be in `R`. - -Second, decide how many clusters should be able to be unavailable at the same time, while still being available. Call -the number that can be unavailable `U`. If you are not sure, then 1 is a fine choice. - -If it is allowable for load-balancing to direct traffic to any region in the event of a cluster failure, then -you need at least the larger of `R` or `U + 1` clusters. If it is not (e.g. you want to ensure low latency for all -users in the event of a cluster failure), then you need to have `R * (U + 1)` clusters -(`U + 1` in each of `R` regions). In any case, try to put each cluster in a different zone. - -Finally, if any of your clusters would need more than the maximum recommended number of nodes for a Kubernetes cluster, then -you may need even more clusters. Kubernetes v1.3 supports clusters up to 1000 nodes in size. Kubernetes v1.8 supports -clusters up to 5000 nodes. See [Building Large Clusters](/docs/setup/best-practices/cluster-large/) for more guidance. - -{{% /capture %}} - -{{% capture whatsnext %}} -* Learn more about the [Federation - proposal](https://github.com/kubernetes/community/blob/{{< param "githubbranch" >}}/contributors/design-proposals/multicluster/federation.md). -* See this [setup guide](/docs/tutorials/federation/set-up-cluster-federation-kubefed/) for cluster federation. -* See this [Kubecon2016 talk on federation](https://www.youtube.com/watch?v=pq9lbkmxpS8) -* See this [Kubecon2017 Europe update on federation](https://www.youtube.com/watch?v=kwOvOLnFYck) -* See this [Kubecon2018 Europe update on sig-multicluster](https://www.youtube.com/watch?v=vGZo5DaThQU) -* See this [Kubecon2018 Europe Federation-v2 prototype presentation](https://youtu.be/q27rbaX5Jis?t=7m20s) -* See this [Federation-v2 Userguide](https://github.com/kubernetes-sigs/federation-v2/blob/master/docs/userguide.md) -{{% /capture %}} diff --git a/content/en/docs/concepts/cluster-administration/logging.md b/content/en/docs/concepts/cluster-administration/logging.md index 2c1ab5f3fe..e464a2869e 100644 --- a/content/en/docs/concepts/cluster-administration/logging.md +++ b/content/en/docs/concepts/cluster-administration/logging.md @@ -76,7 +76,7 @@ should set up a solution to address that. For example, in Kubernetes clusters, deployed by the `kube-up.sh` script, there is a [`logrotate`](https://linux.die.net/man/8/logrotate) tool configured to run each hour. You can also set up a container runtime to -rotate application's logs automatically, e.g. by using Docker's `log-opt`. +rotate application's logs automatically, for example by using Docker's `log-opt`. In the `kube-up.sh` script, the latter approach is used for COS image on GCP, and the former approach is used in any other environment. In both cases, by default rotation is configured to take place when log file exceeds 10MB. diff --git a/content/en/docs/concepts/cluster-administration/manage-deployment.md b/content/en/docs/concepts/cluster-administration/manage-deployment.md index 39e9695062..eedafce1a3 100644 --- a/content/en/docs/concepts/cluster-administration/manage-deployment.md +++ b/content/en/docs/concepts/cluster-administration/manage-deployment.md @@ -424,16 +424,16 @@ At some point, you'll eventually need to update your deployed application, typic We'll guide you through how to create and update applications with Deployments. -Let's say you were running version 1.7.9 of nginx: +Let's say you were running version 1.14.2 of nginx: ```shell -kubectl run my-nginx --image=nginx:1.7.9 --replicas=3 +kubectl run my-nginx --image=nginx:1.14.2 --replicas=3 ``` ```shell deployment.apps/my-nginx created ``` -To update to version 1.9.1, simply change `.spec.template.spec.containers[0].image` from `nginx:1.7.9` to `nginx:1.9.1`, with the kubectl commands we learned above. +To update to version 1.16.1, simply change `.spec.template.spec.containers[0].image` from `nginx:1.14.2` to `nginx:1.16.1`, with the kubectl commands we learned above. ```shell kubectl edit deployment/my-nginx diff --git a/content/en/docs/concepts/configuration/assign-pod-node.md b/content/en/docs/concepts/configuration/assign-pod-node.md index 2c5becff54..2323cd76f4 100644 --- a/content/en/docs/concepts/configuration/assign-pod-node.md +++ b/content/en/docs/concepts/configuration/assign-pod-node.md @@ -17,7 +17,7 @@ There are several ways to do this, and the recommended approaches all use [label selectors](/docs/concepts/overview/working-with-objects/labels/) to make the selection. Generally such constraints are unnecessary, as the scheduler will automatically do a reasonable placement (e.g. spread your pods across nodes, not place the pod on a node with insufficient free resources, etc.) -but there are some circumstances where you may want more control on a node where a pod lands, e.g. to ensure +but there are some circumstances where you may want more control on a node where a pod lands, for example to ensure that a pod ends up on a machine with an SSD attached to it, or to co-locate pods from two different services that communicate a lot into the same availability zone. @@ -111,9 +111,10 @@ For example, `example.com.node-restriction.kubernetes.io/fips=true` or `example. `nodeSelector` provides a very simple way to constrain pods to nodes with particular labels. The affinity/anti-affinity feature, greatly expands the types of constraints you can express. The key enhancements are -1. the language is more expressive (not just "AND or exact match") +1. The affinity/anti-affinity language is more expressive. The language offers more matching rules + besides exact matches created with a logical AND operation; 2. you can indicate that the rule is "soft"/"preference" rather than a hard requirement, so if the scheduler - can't satisfy it, the pod will still be scheduled + can't satisfy it, the pod will still be scheduled; 3. you can constrain against labels on other pods running on the node (or other topological domain), rather than against labels on the node itself, which allows rules about which pods can and cannot be co-located @@ -159,9 +160,9 @@ You can use `NotIn` and `DoesNotExist` to achieve node anti-affinity behavior, o If you specify both `nodeSelector` and `nodeAffinity`, *both* must be satisfied for the pod to be scheduled onto a candidate node. -If you specify multiple `nodeSelectorTerms` associated with `nodeAffinity` types, then the pod can be scheduled onto a node **if one of** the `nodeSelectorTerms` is satisfied. +If you specify multiple `nodeSelectorTerms` associated with `nodeAffinity` types, then the pod can be scheduled onto a node **only if all** `nodeSelectorTerms` can be satisfied. -If you specify multiple `matchExpressions` associated with `nodeSelectorTerms`, then the pod can be scheduled onto a node **only if all** `matchExpressions` can be satisfied. +If you specify multiple `matchExpressions` associated with `nodeSelectorTerms`, then the pod can be scheduled onto a node **if one of** the `matchExpressions` is satisfied. If you remove or change the label of the node where the pod is scheduled, the pod won't be removed. In other words, the affinity selection works only at the time of scheduling the pod. @@ -176,7 +177,7 @@ Y is expressed as a LabelSelector with an optional associated list of namespaces (and therefore the labels on pods are implicitly namespaced), a label selector over pod labels must specify which namespaces the selector should apply to. Conceptually X is a topology domain like node, rack, cloud provider zone, cloud provider region, etc. You express it using a `topologyKey` which is the -key for the node label that the system uses to denote such a topology domain, e.g. see the label keys listed above +key for the node label that the system uses to denote such a topology domain; for example, see the label keys listed above in the section [Interlude: built-in node labels](#built-in-node-labels). {{< note >}} @@ -228,7 +229,7 @@ for performance and security reasons, there are some constraints on topologyKey: 1. For affinity and for `requiredDuringSchedulingIgnoredDuringExecution` pod anti-affinity, empty `topologyKey` is not allowed. 2. For `requiredDuringSchedulingIgnoredDuringExecution` pod anti-affinity, the admission controller `LimitPodHardAntiAffinityTopology` was introduced to limit `topologyKey` to `kubernetes.io/hostname`. If you want to make it available for custom topologies, you may modify the admission controller, or simply disable it. -3. For `preferredDuringSchedulingIgnoredDuringExecution` pod anti-affinity, empty `topologyKey` is interpreted as "all topologies" ("all topologies" here is now limited to the combination of `kubernetes.io/hostname`, `failure-domain.beta.kubernetes.io/zone` and `failure-domain.beta.kubernetes.io/region`). +3. For `preferredDuringSchedulingIgnoredDuringExecution` pod anti-affinity, empty `topologyKey` is not allowed. 4. Except for the above cases, the `topologyKey` can be any legal label-key. In addition to `labelSelector` and `topologyKey`, you can optionally specify a list `namespaces` @@ -318,7 +319,7 @@ spec: topologyKey: "kubernetes.io/hostname" containers: - name: web-app - image: nginx:1.12-alpine + image: nginx:1.16-alpine ``` If we create the above two deployments, our three node cluster should look like below. @@ -366,7 +367,7 @@ Some of the limitations of using `nodeName` to select nodes are: some cases may be automatically deleted. - If the named node does not have the resources to accommodate the pod, the pod will fail and its reason will indicate why, - e.g. OutOfmemory or OutOfcpu. + for example OutOfmemory or OutOfcpu. - Node names in cloud environments are not always predictable or stable. diff --git a/content/en/docs/concepts/configuration/manage-compute-resources-container.md b/content/en/docs/concepts/configuration/manage-compute-resources-container.md index 43e71b15f7..576a008ba9 100644 --- a/content/en/docs/concepts/configuration/manage-compute-resources-container.md +++ b/content/en/docs/concepts/configuration/manage-compute-resources-container.md @@ -191,7 +191,7 @@ resource limits, see the The resource usage of a Pod is reported as part of the Pod status. -If [optional monitoring](http://releases.k8s.io/{{< param "githubbranch" >}}/cluster/addons/cluster-monitoring/README.md) +If [optional monitoring](/docs/tasks/debug-application-cluster/resource-metrics-pipeline/) is configured for your cluster, then Pod resource usage can be retrieved from the monitoring system. diff --git a/content/en/docs/concepts/configuration/pod-priority-preemption.md b/content/en/docs/concepts/configuration/pod-priority-preemption.md index 399f8b4e22..1d24c2f094 100644 --- a/content/en/docs/concepts/configuration/pod-priority-preemption.md +++ b/content/en/docs/concepts/configuration/pod-priority-preemption.md @@ -16,42 +16,25 @@ importance of a Pod relative to other Pods. If a Pod cannot be scheduled, the scheduler tries to preempt (evict) lower priority Pods to make scheduling of the pending Pod possible. -In Kubernetes 1.9 and later, Priority also affects scheduling order of Pods and -out-of-resource eviction ordering on the Node. - -Pod priority and preemption graduated to beta in Kubernetes 1.11 and to GA in -Kubernetes 1.14. They have been enabled by default since 1.11. - -In Kubernetes versions where Pod priority and preemption is still an alpha-level -feature, you need to explicitly enable it. To use these features in the older -versions of Kubernetes, follow the instructions in the documentation for your -Kubernetes version, by going to the documentation archive version for your -Kubernetes version. - -Kubernetes Version | Priority and Preemption State | Enabled by default ------------------- | :---------------------------: | :----------------: -1.8 | alpha | no -1.9 | alpha | no -1.10 | alpha | no -1.11 | beta | yes -1.14 | stable | yes - -{{< warning >}}In a cluster where not all users are trusted, a -malicious user could create pods at the highest possible priorities, causing -other pods to be evicted/not get scheduled. To resolve this issue, -[ResourceQuota](/docs/concepts/policy/resource-quotas/) is -augmented to support Pod priority. An admin can create ResourceQuota for users -at specific priority levels, preventing them from creating pods at high -priorities. This feature is in beta since Kubernetes 1.12. -{{< /warning >}} - {{% /capture %}} {{% capture body %}} + +{{< warning >}} +In a cluster where not all users are trusted, a malicious user could create Pods +at the highest possible priorities, causing other Pods to be evicted/not get +scheduled. +An administrator can use ResourceQuota to prevent users from creating pods at +high priorities. + +See [limit Priority Class consumption by default](/docs/concepts/policy/resource-quotas/#limit-priority-class-consumption-by-default) +for details. +{{< /warning >}} + ## How to use priority and preemption -To use priority and preemption in Kubernetes 1.11 and later, follow these steps: +To use priority and preemption: 1. Add one or more [PriorityClasses](#priorityclass). @@ -77,21 +60,20 @@ Pods. ## How to disable preemption -{{< note >}} -In Kubernetes 1.12+, critical pods rely on scheduler preemption to be scheduled -when a cluster is under resource pressure. For this reason, it is not -recommended to disable preemption. -{{< /note >}} +{{< caution >}} +Critical pods rely on scheduler preemption to be scheduled when a cluster +is under resource pressure. For this reason, it is not recommended to +disable preemption. +{{< /caution >}} {{< note >}} -In Kubernetes 1.15 and later, -if the feature `NonPreemptingPriority` is enabled, +In Kubernetes 1.15 and later, if the feature `NonPreemptingPriority` is enabled, PriorityClasses have the option to set `preemptionPolicy: Never`. This will prevent pods of that PriorityClass from preempting other pods. {{< /note >}} -In Kubernetes 1.11 and later, preemption is controlled by a kube-scheduler flag -`disablePreemption`, which is set to `false` by default. +Preemption is controlled by a kube-scheduler flag `disablePreemption`, which is +set to `false` by default. If you want to disable preemption despite the above note, you can set `disablePreemption` to `true`. @@ -117,6 +99,9 @@ priority class name to the integer value of the priority. The name is specified in the `name` field of the PriorityClass object's metadata. The value is specified in the required `value` field. The higher the value, the higher the priority. +The name of a PriorityClass object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names), +and it cannot be prefixed with `system-`. A PriorityClass object can have any 32-bit integer value smaller than or equal to 1 billion. Larger numbers are reserved for critical system Pods that should @@ -158,12 +143,9 @@ globalDefault: false description: "This priority class should be used for XYZ service pods only." ``` -### Non-preempting PriorityClasses (alpha) {#non-preempting-priority-class} +## Non-preempting PriorityClass {#non-preempting-priority-class} -1.15 adds the `PreemptionPolicy` field as an alpha feature. -It is disabled by default in 1.15, -and requires the `NonPreemptingPriority`[feature gate](/docs/reference/command-line-tools-reference/feature-gates/ -) to be enabled. +{{< feature-state for_k8s_version="1.15" state="alpha" >}} Pods with `PreemptionPolicy: Never` will be placed in the scheduling queue ahead of lower-priority pods, @@ -187,6 +169,10 @@ which will allow pods of that PriorityClass to preempt lower-priority pods If `PreemptionPolicy` is set to `Never`, pods in that PriorityClass will be non-preempting. +The use of the `PreemptionPolicy` field requires the `NonPreemptingPriority` +[feature gate](/docs/reference/command-line-tools-reference/feature-gates/) +to be enabled. + An example use case is for data science workloads. A user may submit a job that they want to be prioritized above other workloads, but do not wish to discard existing work by preempting running pods. @@ -194,7 +180,7 @@ The high priority job with `PreemptionPolicy: Never` will be scheduled ahead of other queued pods, as soon as sufficient cluster resources "naturally" become free. -#### Example Non-preempting PriorityClass +### Example Non-preempting PriorityClass ```yaml apiVersion: scheduling.k8s.io/v1 @@ -236,12 +222,12 @@ spec: ### Effect of Pod priority on scheduling order -In Kubernetes 1.9 and later, when Pod priority is enabled, scheduler orders -pending Pods by their priority and a pending Pod is placed ahead of other -pending Pods with lower priority in the scheduling queue. As a result, the -higher priority Pod may be scheduled sooner than Pods with lower priority if its -scheduling requirements are met. If such Pod cannot be scheduled, scheduler will -continue and tries to schedule other lower priority Pods. +When Pod priority is enabled, the scheduler orders pending Pods by +their priority and a pending Pod is placed ahead of other pending Pods +with lower priority in the scheduling queue. As a result, the higher +priority Pod may be scheduled sooner than Pods with lower priority if +its scheduling requirements are met. If such Pod cannot be scheduled, +scheduler will continue and tries to schedule other lower priority Pods. ## Preemption @@ -287,12 +273,12 @@ point that scheduler preempts victims and the time that Pod P is scheduled. In order to minimize this gap, one can set graceful termination period of lower priority Pods to zero or a small number. -#### PodDisruptionBudget is supported, but not guaranteed! +#### PodDisruptionBudget is supported, but not guaranteed A [Pod Disruption Budget (PDB)](/docs/concepts/workloads/pods/disruptions/) allows application owners to limit the number of Pods of a replicated application -that are down simultaneously from voluntary disruptions. Kubernetes 1.9 supports -PDB when preempting Pods, but respecting PDB is best effort. The Scheduler tries +that are down simultaneously from voluntary disruptions. Kubernetes supports +PDB when preempting Pods, but respecting PDB is best effort. The scheduler tries to find victims whose PDB are not violated by preemption, but if no such victims are found, preemption will still happen, and lower priority Pods will be removed despite their PDBs being violated. @@ -343,28 +329,23 @@ gone, and Pod P could possibly be scheduled on Node N. We may consider adding cross Node preemption in future versions if there is enough demand and if we find an algorithm with reasonable performance. -## Debugging Pod Priority and Preemption +## Troubleshooting -Pod Priority and Preemption is a major feature that could potentially disrupt -Pod scheduling if it has bugs. +Pod priority and pre-emption can have unwanted side effects. Here are some +examples of potential problems and ways to deal with them. -### Potential problems caused by Priority and Preemption - -The followings are some of the potential problems that could be caused by bugs -in the implementation of the feature. This list is not exhaustive. - -#### Pods are preempted unnecessarily +### Pods are preempted unnecessarily Preemption removes existing Pods from a cluster under resource pressure to make -room for higher priority pending Pods. If a user gives high priorities to -certain Pods by mistake, these unintentional high priority Pods may cause -preemption in the cluster. As mentioned above, Pod priority is specified by -setting the `priorityClassName` field of `podSpec`. The integer value of +room for higher priority pending Pods. If you give high priorities to +certain Pods by mistake, these unintentionally high priority Pods may cause +preemption in your cluster. Pod priority is specified by setting the +`priorityClassName` field in the Pod's specification. The integer value for priority is then resolved and populated to the `priority` field of `podSpec`. -To resolve the problem, `priorityClassName` of the Pods must be changed to use -lower priority classes or should be left empty. Empty `priorityClassName` is -resolved to zero by default. +To address the problem, you can change the `priorityClassName` for those Pods +to use lower priority classes, or leave that field empty. An empty +`priorityClassName` is resolved to zero by default. When a Pod is preempted, there will be events recorded for the preempted Pod. Preemption should happen only when a cluster does not have enough resources for @@ -373,29 +354,31 @@ Pod (preemptor) is higher than the victim Pods. Preemption must not happen when there is no pending Pod, or when the pending Pods have equal or lower priority than the victims. If preemption happens in such scenarios, please file an issue. -#### Pods are preempted, but the preemptor is not scheduled +### Pods are preempted, but the preemptor is not scheduled When pods are preempted, they receive their requested graceful termination -period, which is by default 30 seconds, but it can be any different value as -specified in the PodSpec. If the victim Pods do not terminate within this period, -they are force-terminated. Once all the victims go away, the preemptor Pod can -be scheduled. +period, which is by default 30 seconds. If the victim Pods do not terminate within +this period, they are forcibly terminated. Once all the victims go away, the +preemptor Pod can be scheduled. While the preemptor Pod is waiting for the victims to go away, a higher priority -Pod may be created that fits on the same node. In this case, the scheduler will +Pod may be created that fits on the same Node. In this case, the scheduler will schedule the higher priority Pod instead of the preemptor. -In the absence of such a higher priority Pod, we expect the preemptor Pod to be -scheduled after the graceful termination period of the victims is over. +This is expected behavior: the Pod with the higher priority should take the place +of a Pod with a lower priority. Other controller actions, such as +[cluster autoscaling](/docs/tasks/administer-cluster/cluster-management/#cluster-autoscaling), +may eventually provide capacity to schedule the pending Pods. -#### Higher priority Pods are preempted before lower priority pods +### Higher priority Pods are preempted before lower priority pods -The scheduler tries to find nodes that can run a pending Pod and if no node is -found, it tries to remove Pods with lower priority from one node to make room -for the pending pod. If a node with low priority Pods is not feasible to run the -pending Pod, the scheduler may choose another node with higher priority Pods -(compared to the Pods on the other node) for preemption. The victims must still -have lower priority than the preemptor Pod. +The scheduler tries to find nodes that can run a pending Pod. If no node is +found, the scheduler tries to remove Pods with lower priority from an arbitrary +node in order to make room for the pending pod. +If a node with low priority Pods is not feasible to run the pending Pod, the scheduler +may choose another node with higher priority Pods (compared to the Pods on the +other node) for preemption. The victims must still have lower priority than the +preemptor Pod. When there are multiple nodes available for preemption, the scheduler tries to choose the node with a set of Pods with lowest priority. However, if such Pods @@ -403,13 +386,11 @@ have PodDisruptionBudget that would be violated if they are preempted then the scheduler may choose another node with higher priority Pods. When multiple nodes exist for preemption and none of the above scenarios apply, -we expect the scheduler to choose a node with the lowest priority. If that is -not the case, it may indicate a bug in the scheduler. +the scheduler chooses a node with the lowest priority. -## Interactions of Pod priority and QoS +## Interactions between Pod priority and quality of service {#interactions-of-pod-priority-and-qos} -Pod priority and -[QoS](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node/resource-qos.md) +Pod priority and {{< glossary_tooltip text="QoS class" term_id="qos-class" >}} are two orthogonal features with few interactions and no default restrictions on setting the priority of a Pod based on its QoS classes. The scheduler's preemption logic does not consider QoS when choosing preemption targets. @@ -420,15 +401,20 @@ to schedule the preemptor Pod, or if the lowest priority Pods are protected by `PodDisruptionBudget`. The only component that considers both QoS and Pod priority is -[Kubelet out-of-resource eviction](/docs/tasks/administer-cluster/out-of-resource/). +[kubelet out-of-resource eviction](/docs/tasks/administer-cluster/out-of-resource/). The kubelet ranks Pods for eviction first by whether or not their usage of the starved resource exceeds requests, then by Priority, and then by the consumption of the starved compute resource relative to the Pods’ scheduling requests. See -[Evicting end-user pods](/docs/tasks/administer-cluster/out-of-resource/#evicting-end-user-pods) -for more details. Kubelet out-of-resource eviction does not evict Pods whose +[evicting end-user pods](/docs/tasks/administer-cluster/out-of-resource/#evicting-end-user-pods) +for more details. + +kubelet out-of-resource eviction does not evict Pods wheir their usage does not exceed their requests. If a Pod with lower priority is not exceeding its requests, it won't be evicted. Another Pod with higher priority that exceeds its requests may be evicted. {{% /capture %}} +{{% capture whatsnext %}} +* Read about using ResourceQuotas in connection with PriorityClasses: [limit Priority Class consumption by default](/docs/concepts/policy/resource-quotas/#limit-priority-class-consumption-by-default) +{{% /capture %}} diff --git a/content/en/docs/concepts/configuration/secret.md b/content/en/docs/concepts/configuration/secret.md index 61995234e3..356c252fb5 100644 --- a/content/en/docs/concepts/configuration/secret.md +++ b/content/en/docs/concepts/configuration/secret.md @@ -68,6 +68,8 @@ echo -n '1f2d1e2e67df' > ./password.txt The `kubectl create secret` command packages these files into a Secret and creates the object on the API server. +The name of a Secret object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). ```shell kubectl create secret generic db-user-pass --from-file=./username.txt --from-file=./password.txt @@ -137,8 +139,10 @@ See [decoding a secret](#decoding-a-secret) to learn how to view the contents of #### Creating a Secret manually You can also create a Secret in a file first, in JSON or YAML format, -and then create that object. The -[Secret](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#secret-v1-core) +and then create that object. +The name of a Secret object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). +The [Secret](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#secret-v1-core) contains two maps: `data` and `stringData`. The `data` field is used to store arbitrary data, encoded using base64. The `stringData` field is provided for convenience, and allows you to provide diff --git a/content/en/docs/concepts/containers/container-environment-variables.md b/content/en/docs/concepts/containers/container-environment.md similarity index 98% rename from content/en/docs/concepts/containers/container-environment-variables.md rename to content/en/docs/concepts/containers/container-environment.md index b8b3c28a6b..86b595661d 100644 --- a/content/en/docs/concepts/containers/container-environment-variables.md +++ b/content/en/docs/concepts/containers/container-environment.md @@ -2,7 +2,7 @@ reviewers: - mikedanese - thockin -title: Container Environment Variables +title: Container Environment content_template: templates/concept weight: 20 --- diff --git a/content/en/docs/concepts/containers/container-lifecycle-hooks.md b/content/en/docs/concepts/containers/container-lifecycle-hooks.md index 3d4f81152d..fe810d23c5 100644 --- a/content/en/docs/concepts/containers/container-lifecycle-hooks.md +++ b/content/en/docs/concepts/containers/container-lifecycle-hooks.md @@ -116,7 +116,7 @@ Events: {{% capture whatsnext %}} -* Learn more about the [Container environment](/docs/concepts/containers/container-environment-variables/). +* Learn more about the [Container environment](/docs/concepts/containers/container-environment/). * Get hands-on experience [attaching handlers to Container lifecycle events](/docs/tasks/configure-pod-container/attach-handler-lifecycle-event/). diff --git a/content/en/docs/concepts/containers/overview.md b/content/en/docs/concepts/containers/overview.md new file mode 100644 index 0000000000..968ba7104a --- /dev/null +++ b/content/en/docs/concepts/containers/overview.md @@ -0,0 +1,45 @@ +--- +reviewers: +- erictune +- thockin +title: Containers overview +content_template: templates/concept +weight: 1 +--- + +{{% capture overview %}} + +Containers are a technnology for packaging the (compiled) code for an +application along with the dependencies it needs at run time. Each +container that you run is repeatable; the standardisation from having +dependencies included means that you get the same behavior wherever you +run it. + +Containers decouple applications from underlying host infrastructure. +This makes deployment easier in different cloud or OS environments. + +{{% /capture %}} + + +{{% capture body %}} + +## Container images +A [container image](/docs/concepts/containers/images/) is a ready-to-run +software package, containing everything needed to run an application: +the code and any runtime it requires, application and system libraries, +and default values for any essential settings. + +By design, a container is immutable: you cannot change the code of a +container that is already running. If you have a containerized application +and want to make changes, you need to build a new container that includes +the change, then recreate the container to start from the updated image. + +## Container runtimes + +{{< glossary_definition term_id="container-runtime" length="all" >}} + +{{% /capture %}} +{{% capture whatsnext %}} +* Read about [container images](/docs/concepts/containers/images/) +* Read about [Pods](/docs/concepts/workloads/pods/) +{{% /capture %}} diff --git a/content/en/docs/concepts/containers/runtime-class.md b/content/en/docs/concepts/containers/runtime-class.md index 00bd9fae34..9ea21fa6b0 100644 --- a/content/en/docs/concepts/containers/runtime-class.md +++ b/content/en/docs/concepts/containers/runtime-class.md @@ -82,6 +82,9 @@ metadata: handler: myconfiguration # The name of the corresponding CRI configuration ``` +The name of a RuntimeClass object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + {{< note >}} It is recommended that RuntimeClass write operations (create/update/patch/delete) be restricted to the cluster administrator. This is typically the default. See [Authorization diff --git a/content/en/docs/concepts/extend-kubernetes/api-extension/apiserver-aggregation.md b/content/en/docs/concepts/extend-kubernetes/api-extension/apiserver-aggregation.md index bf2d550192..8bc6e22861 100644 --- a/content/en/docs/concepts/extend-kubernetes/api-extension/apiserver-aggregation.md +++ b/content/en/docs/concepts/extend-kubernetes/api-extension/apiserver-aggregation.md @@ -5,30 +5,34 @@ reviewers: - cheftako - chenopis content_template: templates/concept -weight: 10 +weight: 20 --- {{% capture overview %}} -The aggregation layer allows Kubernetes to be extended with additional APIs, beyond what is offered by the core Kubernetes APIs. +The aggregation layer allows Kubernetes to be extended with additional APIs, beyond what is offered by the core Kubernetes APIs. +The additional APIs can either be ready-made solutions such as [service-catalog](/docs/concepts/extend-kubernetes/service-catalog/), or APIs that you develop yourself. + +The aggregation layer is different from [Custom Resources](/docs/concepts/extend-kubernetes/api-extension/custom-resources/), which are a way to make the {{< glossary_tooltip term_id="kube-apiserver" text="kube-apiserver" >}} recognise new kinds of object. {{% /capture %}} {{% capture body %}} -## Overview +## Aggregation layer -The aggregation layer enables installing additional Kubernetes-style APIs in your cluster. These can either be pre-built, existing 3rd party solutions, such as [service-catalog](https://github.com/kubernetes-incubator/service-catalog/blob/master/README.md), or user-created APIs like [apiserver-builder](https://github.com/kubernetes-incubator/apiserver-builder/blob/master/README.md), which can get you started. +The aggregation layer runs in-process with the kube-apiserver. Until an extension resource is registered, the aggregation layer will do nothing. To register an API, you add an _APIService_ object, which "claims" the URL path in the Kubernetes API. At that point, the aggregation layer will proxy anything sent to that API path (e.g. `/apis/myextension.mycompany.io/v1/…`) to the registered APIService. -The aggregation layer runs in-process with the kube-apiserver. Until an extension resource is registered, the aggregation layer will do nothing. To register an API, users must add an APIService object, which "claims" the URL path in the Kubernetes API. At that point, the aggregation layer will proxy anything sent to that API path (e.g. /apis/myextension.mycompany.io/v1/…) to the registered APIService. +The most common way to implement the APIService is to run an *extension API server* in Pod(s) that run in your cluster. If you're using the extension API server to manage resources in your cluster, the extension API server (also written as "extension-apiserver") is typically paired with one or more {{< glossary_tooltip text="controllers" term_id="controller" >}}. The apiserver-builder library provides a skeleton for both extension API servers and the associated controller(s). -Ordinarily, the APIService will be implemented by an *extension-apiserver* in a pod running in the cluster. This extension-apiserver will normally need to be paired with one or more controllers if active management of the added resources is needed. As a result, the apiserver-builder will actually provide a skeleton for both. As another example, when the service-catalog is installed, it provides both the extension-apiserver and controller for the services it provides. +### Response latency -Extension-apiservers should have low latency connections to and from the kube-apiserver. -In particular, discovery requests are required to round-trip from the kube-apiserver in five seconds or less. -If your deployment cannot achieve this, you should consider how to change it. For now, setting the -`EnableAggregatedDiscoveryTimeout=false` feature gate on the kube-apiserver -will disable the timeout restriction. It will be removed in a future release. +Extension API servers should have low latency networking to and from the kube-apiserver. +Discovery requests are required to round-trip from the kube-apiserver in five seconds or less. + +If your extension API server cannot achieve that latency requirement, consider making changes that let you meet it. You can also set the +`EnableAggregatedDiscoveryTimeout=false` [feature gate](/docs/reference/command-line-tools-reference/feature-gates/) on the kube-apiserver +to disable the timeout restriction. This deprecated feature gate will be removed in a future release. {{% /capture %}} @@ -37,7 +41,6 @@ will disable the timeout restriction. It will be removed in a future release. * To get the aggregator working in your environment, [configure the aggregation layer](/docs/tasks/access-kubernetes-api/configure-aggregation-layer/). * Then, [setup an extension api-server](/docs/tasks/access-kubernetes-api/setup-extension-api-server/) to work with the aggregation layer. * Also, learn how to [extend the Kubernetes API using Custom Resource Definitions](/docs/tasks/access-kubernetes-api/extend-api-custom-resource-definitions/). +* Read the specification for [APIService](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#apiservice-v1-apiregistration-k8s-io) {{% /capture %}} - - diff --git a/content/en/docs/concepts/extend-kubernetes/api-extension/custom-resources.md b/content/en/docs/concepts/extend-kubernetes/api-extension/custom-resources.md index 15f3f7e234..f2d4b814ad 100644 --- a/content/en/docs/concepts/extend-kubernetes/api-extension/custom-resources.md +++ b/content/en/docs/concepts/extend-kubernetes/api-extension/custom-resources.md @@ -4,7 +4,7 @@ reviewers: - enisoc - deads2k content_template: templates/concept -weight: 20 +weight: 10 --- {{% capture overview %}} @@ -167,7 +167,7 @@ CRDs are easier to create than Aggregated APIs. | CRDs | Aggregated API | | --------------------------- | -------------- | -| Do not require programming. Users can choose any language for a CRD controller. | Requires programming in Go and building binary and image. Users can choose any language for a CRD controller. | +| Do not require programming. Users can choose any language for a CRD controller. | Requires programming in Go and building binary and image. | | No additional service to run; CRs are handled by API Server. | An additional service to create and that could fail. | | No ongoing support once the CRD is created. Any bug fixes are picked up as part of normal Kubernetes Master upgrades. | May need to periodically pickup bug fixes from upstream and rebuild and update the Aggregated APIserver. | | No need to handle multiple versions of your API. For example: when you control the client for this resource, you can upgrade it in sync with the API. | You need to handle multiple versions of your API, for example: when developing an extension to share with the world. | @@ -184,7 +184,7 @@ Aggregated APIs offer more advanced API features and customization of other feat | Custom Storage | If you need storage with a different performance mode (for example, time-series database instead of key-value store) or isolation for security (for example, encryption secrets or different | No | Yes | | Custom Business Logic | Perform arbitrary checks or actions when creating, reading, updating or deleting an object | Yes, using [Webhooks](/docs/reference/access-authn-authz/extensible-admission-controllers/#admission-webhooks). | Yes | | Scale Subresource | Allows systems like HorizontalPodAutoscaler and PodDisruptionBudget interact with your new resource | [Yes](/docs/tasks/access-kubernetes-api/extend-api-custom-resource-definitions/#scale-subresource) | Yes | -| Status Subresource |
  • Finer-grained access control: user writes spec section, controller writes status section.
  • Allows incrementing object Generation on custom resource data mutation (requires separate spec and status sections in the resource)
| [Yes](/docs/tasks/access-kubernetes-api/extend-api-custom-resource-definitions/#status-subresource) | Yes | +| Status Subresource | Allows fine-grained access control where user writes the spec section and the controller writes the status section. Allows incrementing object Generation on custom resource data mutation (requires separate spec and status sections in the resource) | [Yes](/docs/tasks/access-kubernetes-api/extend-api-custom-resource-definitions/#status-subresource) | Yes | | Other Subresources | Add operations other than CRUD, such as "logs" or "exec". | No | Yes | | strategic-merge-patch | The new endpoints support PATCH with `Content-Type: application/strategic-merge-patch+json`. Useful for updating objects that may be modified both locally, and by the server. For more information, see ["Update API Objects in Place Using kubectl patch"](/docs/tasks/run-application/update-api-object-kubectl-patch/) | No | Yes | | Protocol Buffers | The new resource supports clients that want to use Protocol Buffers | No | Yes | diff --git a/content/en/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins.md b/content/en/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins.md index 3cb5f3ffa8..a9b76cdd51 100644 --- a/content/en/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins.md +++ b/content/en/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins.md @@ -154,7 +154,7 @@ most network plugins. Where needed, you can specify the MTU explicitly with the `network-plugin-mtu` kubelet option. For example, on AWS the `eth0` MTU is typically 9001, so you might specify `--network-plugin-mtu=9001`. If you're using IPSEC you -might reduce it to allow for encapsulation overhead e.g. `--network-plugin-mtu=8873`. +might reduce it to allow for encapsulation overhead; for example: `--network-plugin-mtu=8873`. This option is provided to the network-plugin; currently **only kubenet supports `network-plugin-mtu`**. diff --git a/content/en/docs/concepts/extend-kubernetes/poseidon-firmament-alternate-scheduler.md b/content/en/docs/concepts/extend-kubernetes/poseidon-firmament-alternate-scheduler.md index 1afbc17c09..4c5ab12c03 100644 --- a/content/en/docs/concepts/extend-kubernetes/poseidon-firmament-alternate-scheduler.md +++ b/content/en/docs/concepts/extend-kubernetes/poseidon-firmament-alternate-scheduler.md @@ -1,117 +1,111 @@ --- -title: Poseidon-Firmament - An alternate scheduler +title: Poseidon-Firmament Scheduler content_template: templates/concept weight: 80 --- {{% capture overview %}} -**Current release of Poseidon-Firmament scheduler is an alpha release.** +{{< feature-state for_k8s_version="v1.6" state="alpha" >}} -Poseidon-Firmament scheduler is an alternate scheduler that can be deployed alongside the default Kubernetes scheduler. +The Poseidon-Firmament scheduler is an alternate scheduler that can be deployed alongside the default Kubernetes scheduler. {{% /capture %}} {{% capture body %}} -## Introduction +## Introduction -Poseidon is a service that acts as the integration glue for the [Firmament scheduler](https://github.com/Huawei-PaaS/firmament) with Kubernetes. Poseidon-Firmament scheduler augments the current Kubernetes scheduling capabilities. It incorporates novel flow network graph based scheduling capabilities alongside the default Kubernetes Scheduler. Firmament scheduler models workloads and clusters as flow networks and runs min-cost flow optimizations over these networks to make scheduling decisions. +Poseidon is a service that acts as the integration glue between the [Firmament scheduler](https://github.com/Huawei-PaaS/firmament) and Kubernetes. Poseidon-Firmament augments the current Kubernetes scheduling capabilities. It incorporates novel flow network graph based scheduling capabilities alongside the default Kubernetes scheduler. The Firmament scheduler models workloads and clusters as flow networks and runs min-cost flow optimizations over these networks to make scheduling decisions. -It models the scheduling problem as a constraint-based optimization over a flow network graph. This is achieved by reducing scheduling to a min-cost max-flow optimization problem. The Poseidon-Firmament scheduler dynamically refines the workload placements. +Firmament models the scheduling problem as a constraint-based optimization over a flow network graph. This is achieved by reducing scheduling to a min-cost max-flow optimization problem. The Poseidon-Firmament scheduler dynamically refines the workload placements. -Poseidon-Firmament scheduler runs alongside the default Kubernetes Scheduler as an alternate scheduler, so multiple schedulers run simultaneously. +Poseidon-Firmament scheduler runs alongside the default Kubernetes scheduler as an alternate scheduler. You can simultaneously run multiple, different schedulers. -## Key Advantages +Flow graph scheduling with the Poseidon-Firmament scheduler provides the following advantages: -### Flow graph scheduling based Poseidon-Firmament scheduler provides the following key advantages: -- Workloads (pods) are bulk scheduled to enable scheduling at massive scale.. -- Based on the extensive performance test results, Poseidon-Firmament scales much better than the Kubernetes default scheduler as the number of nodes increase in a cluster. This is due to the fact that Poseidon-Firmament is able to amortize more and more work across workloads. -- Poseidon-Firmament Scheduler outperforms the Kubernetes default scheduler by a wide margin when it comes to throughput performance numbers for scenarios where compute resource requirements are somewhat uniform across jobs (Replicasets/Deployments/Jobs). Poseidon-Firmament scheduler end-to-end throughput performance numbers, including bind time, consistently get better as the number of nodes in a cluster increase. For example, for a 2,700 node cluster (shown in the graphs [here](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/benchmark/README.md)), Poseidon-Firmament scheduler achieves a 7X or greater end-to-end throughput than the Kubernetes default scheduler, which includes bind time. +- Workloads (Pods) are bulk scheduled to enable scheduling at massive scale. + The Poseidon-Firmament scheduler outperforms the Kubernetes default scheduler by a wide margin when it comes to throughput performance for scenarios where compute resource requirements are somewhat uniform across your workload (Deployments, ReplicaSets, Jobs). +- The Poseidon-Firmament's scheduler's end-to-end throughput performance and bind time improves as the number of nodes in a cluster increases. As you scale out, Poseidon-Firmament scheduler is able to amortize more and more work across workloads. +- Scheduling in Poseidon-Firmament is dynamic; it keeps cluster resources in a global optimal state during every scheduling run. +- The Poseidon-Firmament scheduler supports scheduling complex rule constraints. -- Availability of complex rule constraints. -- Scheduling in Poseidon-Firmament is dynamic; it keeps cluster resources in a global optimal state during every scheduling run. -- Highly efficient resource utilizations. +## How the Poseidon-Firmament scheduler works -## Poseidon-Firmament Scheduler - How it works +Kubernetes supports [using multiple schedulers](/docs/tasks/administer-cluster/configure-multiple-schedulers/). You can specify, for a particular Pod, that it is scheduled by a custom scheduler (“poseidon” for this case), by setting the `schedulerName` field in the PodSpec at the time of pod creation. The default scheduler will ignore that Pod and allow Poseidon-Firmament scheduler to schedule the Pod on a relevant node. -As part of the Kubernetes multiple schedulers support, each new pod is typically scheduled by the default scheduler. Kubernetes can be instructed to use another scheduler by specifying the name of another custom scheduler (“poseidon” in our case) in the **schedulerName** field of the PodSpec at the time of pod creation. In this case, the default scheduler will ignore that Pod and allow Poseidon scheduler to schedule the Pod on a relevant node. +For example: ```yaml apiVersion: v1 kind: Pod - ... spec: - schedulerName: poseidon -``` + schedulerName: poseidon +... +``` - -{{< note >}} -For details about the design of this project see the [design document](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/design/README.md). -{{< /note >}} - -## Possible Use Case Scenarios - When to use it +## Batch scheduling As mentioned earlier, Poseidon-Firmament scheduler enables an extremely high throughput scheduling environment at scale due to its bulk scheduling approach versus Kubernetes pod-at-a-time approach. In our extensive tests, we have observed substantial throughput benefits as long as resource requirements (CPU/Memory) for incoming Pods are uniform across jobs (Replicasets/Deployments/Jobs), mainly due to efficient amortization of work across jobs. Although, Poseidon-Firmament scheduler is capable of scheduling various types of workloads, such as service, batch, etc., the following are a few use cases where it excels the most: -1. For “Big Data/AI” jobs consisting of large number of tasks, throughput benefits are tremendous. -2. Service or batch jobs where workload resource requirements are uniform across jobs (Replicasets/Deployments/Jobs). +1. For “Big Data/AI” jobs consisting of large number of tasks, throughput benefits are tremendous. +2. Service or batch jobs where workload resource requirements are uniform across jobs (Replicasets/Deployments/Jobs). -## Current Project Stage +## Feature state -- **Alpha Release - Incubation repo.** at https://github.com/kubernetes-sigs/poseidon. -- Currently, Poseidon-Firmament scheduler **does not provide support for high availability**, our implementation assumes that the scheduler cannot fail. The [design document](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/design/README.md) describes possible ways to enable high availability, but we leave this to future work. -- We are **not aware of any production deployment** of Poseidon-Firmament scheduler at this time. -- Poseidon-Firmament is supported from Kubernetes release 1.6 and works with all subsequent releases. -- Release process for Poseidon and Firmament repos are in lock step. The current Poseidon release can be found [here](https://github.com/kubernetes-sigs/poseidon/releases) and the corresponding Firmament release can be found [here](https://github.com/Huawei-PaaS/firmament/releases). +Poseidon-Firmament is designed to work with Kubernetes release 1.6 and all subsequent releases. -## Features Comparison Matrix +{{< caution >}} +Poseidon-Firmament scheduler does not provide support for high availability; its implementation assumes that the scheduler cannot fail. +{{< /caution >}} +## Feature comparison {#feature-comparison-matrix} +{{< table caption="Feature comparison of Kubernetes and Poseidon-Firmament schedulers." >}} |Feature|Kubernetes Default Scheduler|Poseidon-Firmament Scheduler|Notes| |--- |--- |--- |--- | |Node Affinity/Anti-Affinity|Y|Y|| -|Pod Affinity/Anti-Affinity - including support for pod anti-affinity symmetry|Y|Y|Currently, the default scheduler outperforms the Poseidon-Firmament scheduler pod affinity/anti-affinity functionality. We are working towards resolving this.| +|Pod Affinity/Anti-Affinity - including support for pod anti-affinity symmetry|Y|Y|The default scheduler outperforms the Poseidon-Firmament scheduler pod affinity/anti-affinity functionality.| |Taints & Tolerations|Y|Y|| -|Baseline Scheduling capability in accordance to available compute resources (CPU & Memory) on a node|Y|Y**|Not all Predicates & Priorities are supported at this time.| -|Extreme Throughput at scale|Y**|Y|Bulk scheduling approach scales or increases workload placement. Substantial throughput benefits using Firmament scheduler as long as resource requirements (CPU/Memory) for incoming Pods is uniform across Replicasets/Deployments/Jobs. This is mainly due to efficient amortization of work across Replicasets/Deployments/Jobs . 1) For “Big Data/AI” jobs consisting of large no. of tasks, throughput benefits are tremendous. 2) Substantial throughput benefits also for service or batch job scenarios where workload resource requirements are uniform across Replicasets/Deployments/Jobs.| -|Optimal Scheduling|Pod-by-Pod scheduler, processes one pod at a time (may result into sub-optimal scheduling)|Bulk Scheduling (Optimal scheduling)|Pod-by-Pod Kubernetes default scheduler may assign tasks to a sub-optimal machine. By contrast, Firmament considers all unscheduled tasks at the same time together with their soft and hard constraints.| -|Colocation Interference Avoidance|N|N**|Planned in Poseidon-Firmament.| -|Priority Pre-emption|Y|N**|Partially exists in Poseidon-Firmament versus extensive support in Kubernetes default scheduler.| -|Inherent Re-Scheduling|N|Y**|Poseidon-Firmament scheduler supports workload re-scheduling. In each scheduling run it considers all the pods, including running pods, and as a result can migrate or evict pods – a globally optimal scheduling environment.| +|Baseline Scheduling capability in accordance to available compute resources (CPU & Memory) on a node|Y|Y†|**†** Not all Predicates & Priorities are supported with Poseidon-Firmament.| +|Extreme Throughput at scale|Y†|Y|**†** Bulk scheduling approach scales or increases workload placement. Firmament scheduler offers high throughput when resource requirements (CPU/Memory) for incoming Pods are uniform across ReplicaSets/Deployments/Jobs.| +|Colocation Interference Avoidance|N|N|| +|Priority Preemption|Y|N†|**†** Partially exists in Poseidon-Firmament versus extensive support in Kubernetes default scheduler.| +|Inherent Rescheduling|N|Y†|**†** Poseidon-Firmament scheduler supports workload re-scheduling. In each scheduling run, Poseidon-Firmament considers all Pods, including running Pods, and as a result can migrate or evict Pods – a globally optimal scheduling environment.| |Gang Scheduling|N|Y|| |Support for Pre-bound Persistence Volume Scheduling|Y|Y|| -|Support for Local Volume & Dynamic Persistence Volume Binding Scheduling|Y|N**|Planned.| -|High Availability|Y|N**|Planned.| -|Real-time metrics based scheduling|N|Y**|Initially supported using Heapster (now deprecated) for placing pods using actual cluster utilization statistics rather than reservations. Plans to switch over to "metric server".| +|Support for Local Volume & Dynamic Persistence Volume Binding Scheduling|Y|N|| +|High Availability|Y|N|| +|Real-time metrics based scheduling|N|Y†|**†** Partially supported in Poseidon-Firmament using Heapster (now deprecated) for placing Pods using actual cluster utilization statistics rather than reservations.| |Support for Max-Pod per node|Y|Y|Poseidon-Firmament scheduler seamlessly co-exists with Kubernetes default scheduler.| |Support for Ephemeral Storage, in addition to CPU/Memory|Y|Y|| +{{< /table >}} +## Installation -## Installation +The [Poseidon-Firmament installation guide](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/install/README.md#Installation) explains how to deploy Poseidon-Firmament to your cluster. -For in-cluster installation of Poseidon, please start at the [Installation instructions](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/install/README.md). - - -## Development - -For developers, please refer to the [Developer Setup instructions](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/devel/README.md). - -## Latest Throughput Performance Testing Results - -Pod-by-pod schedulers, such as the Kubernetes default scheduler, typically process one pod at a time. These schedulers have the following crucial drawbacks: - -1. The scheduler commits to a pod placement early and restricts the choices for other pods that wait to be placed. -2. There is limited opportunities for amortizing work across pods because they are considered for placement individually. - -These downsides of pod-by-pod schedulers are addressed by batching or bulk scheduling in Poseidon-Firmament scheduler. Processing several pods in a batch allows the scheduler to jointly consider their placement, and thus to find the best trade-off for the whole batch instead of one pod. At the same time it amortizes work across pods resulting in much higher throughput. +## Performance comparison {{< note >}} Please refer to the [latest benchmark results](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/benchmark/README.md) for detailed throughput performance comparison test results between Poseidon-Firmament scheduler and the Kubernetes default scheduler. {{< /note >}} +Pod-by-pod schedulers, such as the Kubernetes default scheduler, process Pods in small batches (typically one at a time). These schedulers have the following crucial drawbacks: + +1. The scheduler commits to a pod placement early and restricts the choices for other pods that wait to be placed. +2. There is limited opportunities for amortizing work across pods because they are considered for placement individually. + +These downsides of pod-by-pod schedulers are addressed by batching or bulk scheduling in Poseidon-Firmament scheduler. Processing several pods in a batch allows the scheduler to jointly consider their placement, and thus to find the best trade-off for the whole batch instead of one pod. At the same time it amortizes work across pods resulting in much higher throughput. + +{{% /capture %}} +{{% capture whatsnext %}} +* See [Poseidon-Firmament](https://github.com/kubernetes-sigs/poseidon#readme) on GitHub for more information. +* See the [design document](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/design/README.md) for Poseidon. +* Read [Firmament: Fast, Centralized Cluster Scheduling at Scale](https://www.usenix.org/system/files/conference/osdi16/osdi16-gog.pdf), the academic paper on the Firmament scheduling design. +* If you'd like to contribute to Poseidon-Firmament, refer to the [developer setup instructions](https://github.com/kubernetes-sigs/poseidon/blob/master/docs/devel/README.md). {{% /capture %}} diff --git a/content/en/docs/concepts/overview/kubernetes-api.md b/content/en/docs/concepts/overview/kubernetes-api.md index 1c6066f4db..ad9569ede6 100644 --- a/content/en/docs/concepts/overview/kubernetes-api.md +++ b/content/en/docs/concepts/overview/kubernetes-api.md @@ -121,21 +121,22 @@ There are two supported paths to extending the API with [custom resources](/docs to make it seamless for clients. -## Enabling API groups +## Enabling or disabling API groups Certain resources and API groups are enabled by default. They can be enabled or disabled by setting `--runtime-config` -on apiserver. `--runtime-config` accepts comma separated values. For ex: to disable batch/v1, set +on apiserver. `--runtime-config` accepts comma separated values. For example: to disable batch/v1, set `--runtime-config=batch/v1=false`, to enable batch/v2alpha1, set `--runtime-config=batch/v2alpha1`. The flag accepts comma separated set of key=value pairs describing runtime configuration of the apiserver. -IMPORTANT: Enabling or disabling groups or resources requires restarting apiserver and controller-manager -to pick up the `--runtime-config` changes. +{{< note >}}Enabling or disabling groups or resources requires restarting apiserver and controller-manager +to pick up the `--runtime-config` changes.{{< /note >}} -## Enabling resources in the groups +## Enabling specific resources in the extensions/v1beta1 group -DaemonSets, Deployments, HorizontalPodAutoscalers, Ingresses, Jobs and ReplicaSets are enabled by default. -Other extensions resources can be enabled by setting `--runtime-config` on -apiserver. `--runtime-config` accepts comma separated values. For example: to disable deployments and ingress, set -`--runtime-config=extensions/v1beta1/deployments=false,extensions/v1beta1/ingresses=false` +DaemonSets, Deployments, StatefulSet, NetworkPolicies, PodSecurityPolicies and ReplicaSets in the `extensions/v1beta1` API group are disabled by default. +For example: to enable deployments and daemonsets, set +`--runtime-config=extensions/v1beta1/deployments=true,extensions/v1beta1/daemonsets=true`. + +{{< note >}}Individual resource enablement/disablement is only supported in the `extensions/v1beta1` API group for legacy reasons.{{< /note >}} {{% /capture %}} diff --git a/content/en/docs/concepts/overview/what-is-kubernetes.md b/content/en/docs/concepts/overview/what-is-kubernetes.md index 34e1ba2f8f..4dbb673382 100644 --- a/content/en/docs/concepts/overview/what-is-kubernetes.md +++ b/content/en/docs/concepts/overview/what-is-kubernetes.md @@ -3,6 +3,8 @@ reviewers: - bgrant0607 - mikedanese title: What is Kubernetes +description: > + Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available. content_template: templates/concept weight: 10 card: @@ -17,9 +19,10 @@ This page is an overview of Kubernetes. {{% capture body %}} Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available. -The name Kubernetes originates from Greek, meaning helmsman or pilot. Google open-sourced the Kubernetes project in 2014. Kubernetes builds upon a [decade and a half of experience that Google has with running production workloads at scale](https://ai.google/research/pubs/pub43438), combined with best-of-breed ideas and practices from the community. +The name Kubernetes originates from Greek, meaning helmsman or pilot. Google open-sourced the Kubernetes project in 2014. Kubernetes combines [over 15 years of Google's experience](/blog/2015/04/borg-predecessor-to-kubernetes/) running production workloads at scale with best-of-breed ideas and practices from the community. ## Going back in time + Let's take a look at why Kubernetes is so useful by going back in time. ![Deployment evolution](/images/docs/Container_Evolution.svg) @@ -42,13 +45,13 @@ Containers have become popular because they provide extra benefits, such as: * Dev and Ops separation of concerns: create application container images at build/release time rather than deployment time, thereby decoupling applications from infrastructure. * Observability not only surfaces OS-level information and metrics, but also application health and other signals. * Environmental consistency across development, testing, and production: Runs the same on a laptop as it does in the cloud. -* Cloud and OS distribution portability: Runs on Ubuntu, RHEL, CoreOS, on-prem, Google Kubernetes Engine, and anywhere else. +* Cloud and OS distribution portability: Runs on Ubuntu, RHEL, CoreOS, on-premises, on major public clouds, and anywhere else. * Application-centric management: Raises the level of abstraction from running an OS on virtual hardware to running an application on an OS using logical resources. * Loosely coupled, distributed, elastic, liberated micro-services: applications are broken into smaller, independent pieces and can be deployed and managed dynamically – not a monolithic stack running on one big single-purpose machine. * Resource isolation: predictable application performance. * Resource utilization: high efficiency and density. -## Why you need Kubernetes and what can it do +## Why you need Kubernetes and what it can do {#why-you-need-kubernetes-and-what-can-it-do} Containers are a good way to bundle and run your applications. In a production environment, you need to manage the containers that run the applications and ensure that there is no downtime. For example, if a container goes down, another container needs to start. Wouldn't it be easier if this behavior was handled by a system? diff --git a/content/en/docs/concepts/overview/working-with-objects/annotations.md b/content/en/docs/concepts/overview/working-with-objects/annotations.md index 7e2446ba5a..f88c6a0003 100644 --- a/content/en/docs/concepts/overview/working-with-objects/annotations.md +++ b/content/en/docs/concepts/overview/working-with-objects/annotations.md @@ -82,7 +82,7 @@ metadata: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/docs/concepts/overview/working-with-objects/kubernetes-objects.md b/content/en/docs/concepts/overview/working-with-objects/kubernetes-objects.md index 0ce8d81bf6..7364596306 100644 --- a/content/en/docs/concepts/overview/working-with-objects/kubernetes-objects.md +++ b/content/en/docs/concepts/overview/working-with-objects/kubernetes-objects.md @@ -26,10 +26,27 @@ To work with Kubernetes objects--whether to create, modify, or delete them--you' ### Object Spec and Status -Every Kubernetes object includes two nested object fields that govern the object's configuration: the object *spec* and the object *status*. The *spec*, which you must provide, describes your desired state for the object--the characteristics that you want the object to have. The *status* describes the *actual state* of the object, and is supplied and updated by the Kubernetes system. At any given time, the Kubernetes Control Plane actively manages an object's actual state to match the desired state you supplied. +Almost every Kubernetes object includes two nested object fields that govern +the object's configuration: the object *`spec`* and the object *`status`*. +For objects that have a `spec`, you have to set this when you create the object, +providing a description of the characteristics you want the resource to have: +its _desired state_. +The `status` describes the _current state_ of the object, supplied and updated +by the Kubernetes and its components. The Kubernetes +{{< glossary_tooltip text="control plane" term_id="control-plane" >}} continually +and actively manages every object's actual state to match the desired state you +supplied. -For example, a Kubernetes Deployment is an object that can represent an application running on your cluster. When you create the Deployment, you might set the Deployment spec to specify that you want three replicas of the application to be running. The Kubernetes system reads the Deployment spec and starts three instances of your desired application--updating the status to match your spec. If any of those instances should fail (a status change), the Kubernetes system responds to the difference between spec and status by making a correction--in this case, starting a replacement instance. +For example: in Kubernetes, a Deployment is an object that can represent an +application running on your cluster. When you create the Deployment, you +might set the Deployment `spec` to specify that you want three replicas of +the application to be running. The Kubernetes system reads the Deployment +spec and starts three instances of your desired application--updating +the status to match your spec. If any of those instances should fail +(a status change), the Kubernetes system responds to the difference +between spec and status by making a correction--in this case, starting +a replacement instance. For more information on the object spec, status, and metadata, see the [Kubernetes API Conventions](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md). diff --git a/content/en/docs/concepts/overview/working-with-objects/labels.md b/content/en/docs/concepts/overview/working-with-objects/labels.md index a74e219103..0de7f04a8c 100644 --- a/content/en/docs/concepts/overview/working-with-objects/labels.md +++ b/content/en/docs/concepts/overview/working-with-objects/labels.md @@ -69,7 +69,7 @@ metadata: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/docs/concepts/overview/working-with-objects/names.md b/content/en/docs/concepts/overview/working-with-objects/names.md index 60c07391a5..01bb53b56d 100644 --- a/content/en/docs/concepts/overview/working-with-objects/names.md +++ b/content/en/docs/concepts/overview/working-with-objects/names.md @@ -64,7 +64,7 @@ metadata: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 ``` diff --git a/content/en/docs/concepts/policy/limit-range.md b/content/en/docs/concepts/policy/limit-range.md index b4a9579a36..dfc941681b 100644 --- a/content/en/docs/concepts/policy/limit-range.md +++ b/content/en/docs/concepts/policy/limit-range.md @@ -9,56 +9,58 @@ weight: 10 {{% capture overview %}} By default, containers run with unbounded [compute resources](/docs/user-guide/compute-resources) on a Kubernetes cluster. -With Resource quotas, cluster administrators can restrict the resource consumption and creation on a namespace basis. -Within a namespace, a Pod or Container can consume as much CPU and memory as defined by the namespace's resource quota. There is a concern that one Pod or Container could monopolize all of the resources. Limit Range is a policy to constrain resource by Pod or Container in a namespace. +With resource quotas, cluster administrators can restrict resource consumption and creation on a namespace basis. +Within a namespace, a Pod or Container can consume as much CPU and memory as defined by the namespace's resource quota. There is a concern that one Pod or Container could monopolize all available resources. A LimitRange is a policy to constrain resource allocations (to Pods or Containers) in a namespace. {{% /capture %}} {{% capture body %}} -A limit range, defined by a `LimitRange` object, provides constraints that can: +A _LimitRange_ provides constraints that can: - Enforce minimum and maximum compute resources usage per Pod or Container in a namespace. - Enforce minimum and maximum storage request per PersistentVolumeClaim in a namespace. - Enforce a ratio between request and limit for a resource in a namespace. - Set default request/limit for compute resources in a namespace and automatically inject them to Containers at runtime. -## Enabling Limit Range +## Enabling LimitRange -Limit Range support is enabled by default for many Kubernetes distributions. It is +LimitRange support is enabled by default for many Kubernetes distributions. It is enabled when the apiserver `--enable-admission-plugins=` flag has `LimitRanger` admission controller as one of its arguments. -A limit range is enforced in a particular namespace when there is a -`LimitRange` object in that namespace. +A LimitRange is enforced in a particular namespace when there is a +LimitRange object in that namespace. -### Overview of Limit Range: +The name of a LimitRange object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + +### Overview of Limit Range - The administrator creates one `LimitRange` in one namespace. - Users create resources like Pods, Containers, and PersistentVolumeClaims in the namespace. -- The `LimitRanger` admission controller enforces defaults limits for all Pods and Container that do not set compute resource requirements and tracks usage to ensure it does not exceed resource minimum , maximum and ratio defined in any `LimitRange` present in the namespace. -- If creating or updating a resource (Pod, Container, PersistentVolumeClaim) violates a limit range constraint, the request to the API server will fail with HTTP status code `403 FORBIDDEN` and a message explaining the constraint that would have been violated. -- If limit range is activated in a namespace for compute resources like `cpu` and `memory`, users must specify - requests or limits for those values; otherwise, the system may reject pod creation. -- LimitRange validations occurs only at Pod Admission stage, not on Running pods. - +- The `LimitRanger` admission controller enforces defaults and limits for all Pods and Containers that do not set compute resource requirements and tracks usage to ensure it does not exceed resource minimum, maximum and ratio defined in any LimitRange present in the namespace. +- If creating or updating a resource (Pod, Container, PersistentVolumeClaim) that violates a LimitRange constraint, the request to the API server will fail with an HTTP status code `403 FORBIDDEN` and a message explaining the constraint that have been violated. +- If a LimitRange is activated in a namespace for compute resources like `cpu` and `memory`, users must specify + requests or limits for those values. Otherwise, the system may reject Pod creation. +- LimitRange validations occurs only at Pod Admission stage, not on Running Pods. Examples of policies that could be created using limit range are: -- In a 2 node cluster with a capacity of 8 GiB RAM, and 16 cores, constrain Pods in a namespace to request 100m and not exceeds 500m for CPU , request 200Mi and not exceed 600Mi -- Define default CPU limits and request to 150m and Memory default request to 300Mi for containers started with no cpu and memory requests in their spec. +- In a 2 node cluster with a capacity of 8 GiB RAM and 16 cores, constrain Pods in a namespace to request 100m of CPU with a max limit of 500m for CPU and request 200Mi for Memory with a max limit of 600Mi for Memory. +- Define default CPU limit and request to 150m and memory default request to 300Mi for Containers started with no cpu and memory requests in their specs. In the case where the total limits of the namespace is less than the sum of the limits of the Pods/Containers, -there may be contention for resources; The Containers or Pods will not be created. +there may be contention for resources. In this case, the Containers or Pods will not be created. -Neither contention nor changes to limitrange will affect already created resources. +Neither contention nor changes to a LimitRange will affect already created resources. ## Limiting Container compute resources The following section discusses the creation of a LimitRange acting at Container Level. -A Pod with 04 containers is first created; each container within the Pod has a specific `spec.resource` configuration -each container within the pod is handled differently by the LimitRanger admission controller. +A Pod with 04 Containers is first created. Each Container within the Pod has a specific `spec.resource` configuration. +Each Container within the Pod is handled differently by the `LimitRanger` admission controller. Create a namespace `limitrange-demo` using the following kubectl command: @@ -75,7 +77,7 @@ kubectl config set-context --current --namespace=limitrange-demo Here is the configuration file for a LimitRange object: {{< codenew file="admin/resource/limit-mem-cpu-container.yaml" >}} -This object defines minimum and maximum Memory/CPU limits, default cpu/Memory requests and default limits for CPU/Memory resources to be apply to containers. +This object defines minimum and maximum CPU/Memory limits, default CPU/Memory requests, and default limits for CPU/Memory resources to be apply to containers. Create the `limit-mem-cpu-per-container` LimitRange in the `limitrange-demo` namespace with the following kubectl command: @@ -94,7 +96,7 @@ Container cpu 100m 800m 110m 700m - Container memory 99Mi 1Gi 111Mi 900Mi - ``` -Here is the configuration file for a Pod with 04 containers to demonstrate LimitRange features : +Here is the configuration file for a Pod with 04 Containers to demonstrate LimitRange features: {{< codenew file="admin/resource/limit-range-pod-1.yaml" >}} Create the `busybox1` Pod: @@ -125,9 +127,9 @@ kubectl get po/busybox1 -n limitrange-demo -o json | jq ".spec.containers[0].res ``` - The `busybox-cnt01` Container inside `busybox` Pod defined `requests.cpu=100m` and `requests.memory=100Mi`. -- `100m <= 500m <= 800m` , The container cpu limit (500m) falls inside the authorized CPU limit range. -- `99Mi <= 200Mi <= 1Gi` , The container memory limit (200Mi) falls inside the authorized Memory limit range. -- No request/limits ratio validation for CPU/Memory , thus the container is valid and created. +- `100m <= 500m <= 800m` , The Container cpu limit (500m) falls inside the authorized CPU LimitRange. +- `99Mi <= 200Mi <= 1Gi` , The Container memory limit (200Mi) falls inside the authorized Memory LimitRange. +- No request/limits ratio validation for CPU/Memory, so the Container is valid and created. ### Container spec with a valid CPU/Memory requests but no limits @@ -151,14 +153,15 @@ kubectl get po/busybox1 -n limitrange-demo -o json | jq ".spec.containers[1].res } ``` - The `busybox-cnt02` Container inside `busybox1` Pod defined `requests.cpu=100m` and `requests.memory=100Mi` but not limits for cpu and memory. -- The container do not have a limits section, the default limits defined in the limit-mem-cpu-per-container LimitRange object are injected to this container `limits.cpu=700mi` and `limits.memory=900Mi`. -- `100m <= 700m <= 800m` , The container cpu limit (700m) falls inside the authorized CPU limit range. -- `99Mi <= 900Mi <= 1Gi` , The container memory limit (900Mi) falls inside the authorized Memory limit range. -- No request/limits ratio set , thus the container is valid and created. +- The Container does not have a limits section. The default limits defined in the `limit-mem-cpu-per-container` LimitRange object are injected in to this Container: `limits.cpu=700mi` and `limits.memory=900Mi`. +- `100m <= 700m <= 800m` , The Container cpu limit (700m) falls inside the authorized CPU limit range. +- `99Mi <= 900Mi <= 1Gi` , The Container memory limit (900Mi) falls inside the authorized Memory limit range. +- No request/limits ratio set, so the Container is valid and created. -### Container spec with a valid CPU/Memory limits but no requests -View the `busybox-cnt03` resource configuration +### Container spec with a valid CPU/Memory limits but no requests + +View the `busybox-cnt03` resource configuration: ```shell kubectl get po/busybox1 -n limitrange-demo -o json | jq ".spec.containers[2].resources" @@ -177,10 +180,10 @@ kubectl get po/busybox1 -n limitrange-demo -o json | jq ".spec.containers[2].res ``` - The `busybox-cnt03` Container inside `busybox1` Pod defined `limits.cpu=500m` and `limits.memory=200Mi` but no `requests` for cpu and memory. -- The container do not define a request section, the defaultRequest defined in the limit-mem-cpu-per-container LimitRange is not used to fill its limits section but the limits defined by the container are set as requests `limits.cpu=500m` and `limits.memory=200Mi`. -- `100m <= 500m <= 800m` , The container cpu limit (500m) falls inside the authorized CPU limit range. -- `99Mi <= 200Mi <= 1Gi` , The container memory limit (200Mi) falls inside the authorized Memory limit range. -- No request/limits ratio set , thus the container is valid and created. +- The Container does not define a request section. The default request defined in the limit-mem-cpu-per-container LimitRange is not used to fill its limits section, but the limits defined by the Container are set as requests `limits.cpu=500m` and `limits.memory=200Mi`. +- `100m <= 500m <= 800m` , The Container cpu limit (500m) falls inside the authorized CPU limit range. +- `99Mi <= 200Mi <= 1Gi` , The Container memory limit (200Mi) falls inside the authorized Memory limit range. +- No request/limits ratio set, so the Container is valid and created. ### Container spec with no CPU/Memory requests/limits @@ -204,27 +207,27 @@ kubectl get po/busybox1 -n limitrange-demo -o json | jq ".spec.containers[3].res ``` - The `busybox-cnt04` Container inside `busybox1` define neither `limits` nor `requests`. -- The container do not define a limit section, the default limit defined in the limit-mem-cpu-per-container LimitRange is used to fill its request +- The Container do not define a limit section, the default limit defined in the limit-mem-cpu-per-container LimitRange is used to fill its request `limits.cpu=700m and` `limits.memory=900Mi` . -- The container do not define a request section, the defaultRequest defined in the limit-mem-cpu-per-container LimitRange is used to fill its request section requests.cpu=110m and requests.memory=111Mi -- `100m <= 700m <= 800m` , The container cpu limit (700m) falls inside the authorized CPU limit range. -- `99Mi <= 900Mi <= 1Gi` , The container memory limit (900Mi) falls inside the authorized Memory limitrange . -- No request/limits ratio set , thus the container is valid and created. +- The Container do not define a request section, the defaultRequest defined in the `limit-mem-cpu-per-container` LimitRange is used to fill its request section requests.cpu=110m and requests.memory=111Mi +- `100m <= 700m <= 800m` , The Container cpu limit (700m) falls inside the authorized CPU limit range. +- `99Mi <= 900Mi <= 1Gi` , The Container memory limit (900Mi) falls inside the authorized Memory limit range . +- No request/limits ratio set, so the Container is valid and created. -All containers defined in the `busybox` Pod passed LimitRange validations, this the Pod is valid and create in the namespace. +All Containers defined in the `busybox` Pod passed LimitRange validations, so this the Pod is valid and created in the namespace. ## Limiting Pod compute resources -The following section discusses how to constrain resources at Pod level. +The following section discusses how to constrain resources at the Pod level. {{< codenew file="admin/resource/limit-mem-cpu-pod.yaml" >}} -Without having to delete `busybox1` Pod, create the `limit-mem-cpu-pod` LimitRange in the `limitrange-demo` namespace: +Without having to delete the `busybox1` Pod, create the `limit-mem-cpu-pod` LimitRange in the `limitrange-demo` namespace: ```shell kubectl apply -f https://k8s.io/examples/admin/resource/limit-mem-cpu-pod.yaml -n limitrange-demo ``` -The limitrange is created and limits CPU to 2 Core and Memory to 2Gi per Pod: +The LimitRange is created and limits CPU to 2 Core and Memory to 2Gi per Pod: ```shell limitrange/limit-mem-cpu-per-pod created @@ -253,7 +256,7 @@ Now create the `busybox2` Pod: kubectl apply -f https://k8s.io/examples/admin/resource/limit-range-pod-2.yaml -n limitrange-demo ``` -The `busybox2` Pod definition is identical to `busybox1` but an error is reported since Pod's resources are now limited: +The `busybox2` Pod definition is identical to `busybox1`, but an error is reported since the Pod's resources are now limited: ```shell Error from server (Forbidden): error when creating "limit-range-pod-2.yaml": pods "busybox2" is forbidden: [maximum cpu usage per Pod is 2, but limit is 2400m., maximum memory usage per Pod is 2Gi, but limit is 2306867200.] @@ -267,12 +270,12 @@ kubectl get po/busybox1 -n limitrange-demo -o json | jq ".spec.containers[].reso "900Mi" ``` -`busybox2` Pod will not be admitted on the cluster since the total memory limit of its container is greater than the limit defined in the LimitRange. +`busybox2` Pod will not be admitted on the cluster since the total memory limit of its Container is greater than the limit defined in the LimitRange. `busybox1` will not be evicted since it was created and admitted on the cluster before the LimitRange creation. ## Limiting Storage resources -You can enforce minimum and maximum size of [storage resources](/docs/concepts/storage/persistent-volumes/) that can be requested by each PersistentVolumeClaim in a namespace using a LimitRange: +You can enforce minimum and maximum size of [storage resources](/docs/concepts/storage/persistent-volumes/) that can be requested by each PersistentVolumeClaim in a namespace using a LimitRange: {{< codenew file="admin/resource/storagelimits.yaml" >}} @@ -328,9 +331,9 @@ Error from server (Forbidden): error when creating "pvc-limit-greater.yaml": per ## Limits/Requests Ratio -If `LimitRangeItem.maxLimitRequestRatio` is specified in the `LimitRangeSpec`, the named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value +If `LimitRangeItem.maxLimitRequestRatio` is specified in the `LimitRangeSpec`, the named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value. -The following `LimitRange` enforces memory limit to be at most twice the amount of the memory request for any pod in the namespace. +The following LimitRange enforces memory limit to be at most twice the amount of the memory request for any Pod in the namespace: {{< codenew file="admin/resource/limit-memory-ratio-pod.yaml" >}} @@ -352,7 +355,7 @@ Type Resource Min Max Default Request Default Limit Max Limit/Reques Pod memory - - - - 2 ``` -Let's create a pod with `requests.memory=100Mi` and `limits.memory=300Mi`: +Create a pod with `requests.memory=100Mi` and `limits.memory=300Mi`: {{< codenew file="admin/resource/limit-range-pod-3.yaml" >}} @@ -360,9 +363,9 @@ Let's create a pod with `requests.memory=100Mi` and `limits.memory=300Mi`: kubectl apply -f https://k8s.io/examples/admin/resource/limit-range-pod-3.yaml ``` -The pod creation failed as the ratio here (`3`) is greater than the enforced limit (`2`) in `limit-memory-ratio-pod` LimitRange +The pod creation failed as the ratio here (`3`) is greater than the enforced limit (`2`) in `limit-memory-ratio-pod` LimitRange: -```shell +``` Error from server (Forbidden): error when creating "limit-range-pod-3.yaml": pods "busybox3" is forbidden: memory max limit to request ratio per Pod is 2, but provided ratio is 3.000000. ``` diff --git a/content/en/docs/concepts/policy/pod-security-policy.md b/content/en/docs/concepts/policy/pod-security-policy.md index 45b48f62ae..f482c5efb2 100644 --- a/content/en/docs/concepts/policy/pod-security-policy.md +++ b/content/en/docs/concepts/policy/pod-security-policy.md @@ -197,6 +197,8 @@ alias kubectl-user='kubectl --as=system:serviceaccount:psp-example:fake-user -n Define the example PodSecurityPolicy object in a file. This is a policy that simply prevents the creation of privileged pods. +The name of a PodSecurityPolicy object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). {{< codenew file="policy/example-psp.yaml" >}} @@ -419,8 +421,10 @@ The **recommended minimum set** of allowed volumes for new PSPs are: - projected {{< warning >}} -PodSecurityPolicy does not limit the types of `PersistentVolume` objects that may be referenced by a `PersistentVolumeClaim`. -Only trusted users should be granted permission to create `PersistentVolume` objects. +PodSecurityPolicy does not limit the types of `PersistentVolume` objects that +may be referenced by a `PersistentVolumeClaim`, and hostPath type +`PersistentVolumes` do not support read-only access mode. Only trusted users +should be granted permission to create `PersistentVolume` objects. {{< /warning >}} **FSGroup** - Controls the supplemental group applied to some volumes. diff --git a/content/en/docs/concepts/policy/resource-quotas.md b/content/en/docs/concepts/policy/resource-quotas.md index 92f43fe3a3..d48c2db88a 100644 --- a/content/en/docs/concepts/policy/resource-quotas.md +++ b/content/en/docs/concepts/policy/resource-quotas.md @@ -37,6 +37,9 @@ Resource quotas work like this: the `LimitRanger` admission controller to force defaults for pods that make no compute resource requirements. See the [walkthrough](/docs/tasks/administer-cluster/quota-memory-cpu-namespace/) for an example of how to avoid this problem. +The name of a `ResourceQuota` object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + Examples of policies that could be created using namespaces and quotas are: - In a cluster with a capacity of 32 GiB RAM, and 16 cores, let team A use 20 GiB and 10 cores, diff --git a/content/en/docs/concepts/services-networking/connect-applications-service.md b/content/en/docs/concepts/services-networking/connect-applications-service.md index 6a958ea31e..bc17b74d15 100644 --- a/content/en/docs/concepts/services-networking/connect-applications-service.md +++ b/content/en/docs/concepts/services-networking/connect-applications-service.md @@ -422,10 +422,8 @@ LoadBalancer Ingress: a320587ffd19711e5a37606cf4a74574-1142138393.us-east-1.el {{% capture whatsnext %}} -Kubernetes also supports Federated Services, which can span multiple -clusters and cloud providers, to provide increased availability, -better fault tolerance and greater scalability for your services. See -the [Federated Services User Guide](/docs/concepts/cluster-administration/federation-service-discovery/) -for further information. +* Learn more about [Using a Service to Access an Application in a Cluster](/docs/tasks/access-application-cluster/service-access-application-cluster/) +* Learn more about [Connecting a Front End to a Back End Using a Service](/docs/tasks/access-application-cluster/connecting-frontend-backend/) +* Learn more about [Creating an External Load Balancer](/docs/tasks/access-application-cluster/create-external-load-balancer/) {{% /capture %}} diff --git a/content/en/docs/concepts/services-networking/endpoint-slices.md b/content/en/docs/concepts/services-networking/endpoint-slices.md index 99df547592..4b347f47ec 100644 --- a/content/en/docs/concepts/services-networking/endpoint-slices.md +++ b/content/en/docs/concepts/services-networking/endpoint-slices.md @@ -32,6 +32,8 @@ for a Kubernetes Service when a {{< glossary_tooltip text="selector" term_id="selector" >}} is specified. These EndpointSlices will include references to any Pods that match the Service selector. EndpointSlices group network endpoints together by unique Service and Port combinations. +The name of a EndpointSlice object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). As an example, here's a sample EndpointSlice resource for the `example` Kubernetes Service. diff --git a/content/en/docs/concepts/services-networking/ingress.md b/content/en/docs/concepts/services-networking/ingress.md index 6739cf1bd0..a46981d28b 100644 --- a/content/en/docs/concepts/services-networking/ingress.md +++ b/content/en/docs/concepts/services-networking/ingress.md @@ -37,7 +37,7 @@ Traffic routing is controlled by rules defined on the Ingress resource. [ Services ] ``` -An Ingress can be configured to give Services externally-reachable URLs, load balance traffic, terminate SSL / TLS, and offer name based virtual hosting. An [Ingress controller](/docs/concepts/services-networking/ingress-controllers) is responsible for fulfilling the Ingress, usually with a load balancer, though it may also configure your edge router or additional frontends to help handle the traffic. +An Ingress may be configured to give Services externally-reachable URLs, load balance traffic, terminate SSL / TLS, and offer name based virtual hosting. An [Ingress controller](/docs/concepts/services-networking/ingress-controllers) is responsible for fulfilling the Ingress, usually with a load balancer, though it may also configure your edge router or additional frontends to help handle the traffic. An Ingress does not expose arbitrary ports or protocols. Exposing services other than HTTP and HTTPS to the internet typically uses a service of type [Service.Type=NodePort](/docs/concepts/services-networking/service/#nodeport) or @@ -78,11 +78,13 @@ spec: servicePort: 80 ``` - As with all other Kubernetes resources, an Ingress needs `apiVersion`, `kind`, and `metadata` fields. - For general information about working with config files, see [deploying applications](/docs/tasks/run-application/run-stateless-application-deployment/), [configuring containers](/docs/tasks/configure-pod-container/configure-pod-configmap/), [managing resources](/docs/concepts/cluster-administration/manage-deployment/). +As with all other Kubernetes resources, an Ingress needs `apiVersion`, `kind`, and `metadata` fields. +The name of an Ingress object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). +For general information about working with config files, see [deploying applications](/docs/tasks/run-application/run-stateless-application-deployment/), [configuring containers](/docs/tasks/configure-pod-container/configure-pod-configmap/), [managing resources](/docs/concepts/cluster-administration/manage-deployment/). Ingress frequently uses annotations to configure some options depending on the Ingress controller, an example of which is the [rewrite-target annotation](https://github.com/kubernetes/ingress-nginx/blob/master/docs/examples/rewrite/README.md). - Different [Ingress controller](/docs/concepts/services-networking/ingress-controllers) support different annotations. Review the documentation for +Different [Ingress controller](/docs/concepts/services-networking/ingress-controllers) support different annotations. Review the documentation for your choice of Ingress controller to learn which annotations are supported. The Ingress [spec](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status) @@ -134,10 +136,10 @@ kubectl get ingress test-ingress ``` NAME HOSTS ADDRESS PORTS AGE -test-ingress * 107.178.254.228 80 59s +test-ingress * 203.0.113.123 80 59s ``` -Where `107.178.254.228` is the IP allocated by the Ingress controller to satisfy +Where `203.0.113.123` is the IP allocated by the Ingress controller to satisfy this Ingress. {{< note >}} diff --git a/content/en/docs/concepts/services-networking/service.md b/content/en/docs/concepts/services-networking/service.md index c568b36231..4e8326b4ae 100644 --- a/content/en/docs/concepts/services-networking/service.md +++ b/content/en/docs/concepts/services-networking/service.md @@ -73,6 +73,8 @@ balancer in between your application and the backend Pods. A Service in Kubernetes is a REST object, similar to a Pod. Like all of the REST objects, you can `POST` a Service definition to the API server to create a new instance. +The name of a Service object must be a valid +[DNS label name](/docs/concepts/overview/working-with-objects/names#dns-label-names). For example, suppose you have a set of Pods that each listen on TCP port 9376 and carry a label `app=MyApp`: @@ -167,6 +169,9 @@ subsets: - port: 9376 ``` +The name of the Endpoints object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + {{< note >}} The endpoint IPs _must not_ be: loopback (127.0.0.0/8 for IPv4, ::1/128 for IPv6), or link-local (169.254.0.0/16 and 224.0.0.0/24 for IPv4, fe80::/64 for IPv6). @@ -1173,19 +1178,6 @@ SCTP is not supported on Windows based nodes. The kube-proxy does not support the management of SCTP associations when it is in userspace mode. {{< /warning >}} -## Future work - -In the future, the proxy policy for Services can become more nuanced than -simple round-robin balancing, for example master-elected or sharded. We also -envision that some Services will have "real" load balancers, in which case the -virtual IP address will simply transport the packets there. - -The Kubernetes project intends to improve support for L7 (HTTP) Services. - -The Kubernetes project intends to have more flexible ingress modes for Services -that encompass the current ClusterIP, NodePort, and LoadBalancer modes and more. - - {{% /capture %}} {{% capture whatsnext %}} diff --git a/content/en/docs/concepts/storage/dynamic-provisioning.md b/content/en/docs/concepts/storage/dynamic-provisioning.md index 6bdca6b8af..77885981f7 100644 --- a/content/en/docs/concepts/storage/dynamic-provisioning.md +++ b/content/en/docs/concepts/storage/dynamic-provisioning.md @@ -46,6 +46,9 @@ To enable dynamic provisioning, a cluster administrator needs to pre-create one or more StorageClass objects for users. StorageClass objects define which provisioner should be used and what parameters should be passed to that provisioner when dynamic provisioning is invoked. +The name of a StorageClass object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + The following manifest creates a storage class "slow" which provisions standard disk-like persistent disks. diff --git a/content/en/docs/concepts/storage/persistent-volumes.md b/content/en/docs/concepts/storage/persistent-volumes.md index c59cb2ee3c..a4451f2867 100644 --- a/content/en/docs/concepts/storage/persistent-volumes.md +++ b/content/en/docs/concepts/storage/persistent-volumes.md @@ -4,6 +4,7 @@ reviewers: - saad-ali - thockin - msau42 +- xing-yang title: Persistent Volumes feature: title: Storage orchestration @@ -41,7 +42,6 @@ resource. See the [detailed walkthrough with working examples](/docs/tasks/configure-pod-container/configure-persistent-volume-storage/). - ## Lifecycle of a volume and claim PVs are resources in the cluster. PVCs are requests for those resources and also act as claim checks to the resource. The interaction between PVs and PVCs follows this lifecycle: @@ -51,9 +51,11 @@ PVs are resources in the cluster. PVCs are requests for those resources and also There are two ways PVs may be provisioned: statically or dynamically. #### Static + A cluster administrator creates a number of PVs. They carry the details of the real storage, which is available for use by cluster users. They exist in the Kubernetes API and are available for consumption. #### Dynamic + When none of the static PVs the administrator created match a user's `PersistentVolumeClaim`, the cluster may try to dynamically provision a volume specially for the PVC. This provisioning is based on `StorageClasses`: the PVC must request a @@ -286,6 +288,8 @@ Expanding EBS volumes is a time-consuming operation. Also, there is a per-volume ## Persistent Volumes Each PV contains a spec and status, which is the specification and status of the volume. +The name of a PersistentVolume object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). ```yaml apiVersion: v1 @@ -440,6 +444,8 @@ The CLI will show the name of the PVC bound to the PV. ## PersistentVolumeClaims Each PVC contains a spec and status, which is the specification and status of the claim. +The name of a PersistentVolumeClaim object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). ```yaml apiVersion: v1 @@ -574,6 +580,7 @@ Support for the additional plugins was added in 1.10. {{< /note >}} ### Persistent Volumes using a Raw Block Volume + ```yaml apiVersion: v1 kind: PersistentVolume @@ -592,6 +599,7 @@ spec: readOnly: false ``` ### Persistent Volume Claim requesting a Raw Block Volume + ```yaml apiVersion: v1 kind: PersistentVolumeClaim @@ -605,7 +613,9 @@ spec: requests: storage: 10Gi ``` + ### Pod specification adding Raw Block Device path in container + ```yaml apiVersion: v1 kind: Pod @@ -654,7 +664,7 @@ Only statically provisioned volumes are supported for alpha release. Administrat ## Volume Snapshot and Restore Volume from Snapshot Support -{{< feature-state for_k8s_version="v1.12" state="alpha" >}} +{{< feature-state for_k8s_version="v1.17" state="beta" >}} Volume snapshot feature was added to support CSI Volume Plugins only. For details, see [volume snapshots](/docs/concepts/storage/volume-snapshots/). @@ -662,6 +672,7 @@ To enable support for restoring a volume from a volume snapshot data source, ena `VolumeSnapshotDataSource` feature gate on the apiserver and controller-manager. ### Create Persistent Volume Claim from Volume Snapshot + ```yaml apiVersion: v1 kind: PersistentVolumeClaim @@ -690,6 +701,7 @@ To enable support for cloning a volume from a PVC data source, enable the `VolumePVCDataSource` feature gate on the apiserver and controller-manager. ### Create Persistent Volume Claim from an existing pvc + ```yaml apiVersion: v1 kind: PersistentVolumeClaim @@ -732,5 +744,17 @@ and need persistent storage, it is recommended that you use the following patter dynamic storage support (in which case the user should create a matching PV) or the cluster has no storage system (in which case the user cannot deploy config requiring PVCs). - +{{% /capture %}} + {{% capture whatsnext %}} + +* Learn more about [Creating a Persistent Volume](/docs/tasks/configure-pod-container/configure-persistent-volume-storage/#create-a-persistentvolume). +* Learn more about [Creating a Persistent Volume Claim](/docs/tasks/configure-pod-container/configure-persistent-volume-storage/#create-a-persistentvolumeclaim). +* Read the [Persistent Storage design document](https://git.k8s.io/community/contributors/design-proposals/storage/persistent-storage.md). + +### Reference + +* [PersistentVolume](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#persistentvolume-v1-core) +* [PersistentVolumeSpec](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#persistentvolumespec-v1-core) +* [PersistentVolumeClaim](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#persistentvolumeclaim-v1-core) +* [PersistentVolumeClaimSpec](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#persistentvolumeclaimspec-v1-core) {{% /capture %}} diff --git a/content/en/docs/concepts/storage/storage-classes.md b/content/en/docs/concepts/storage/storage-classes.md index 89788349b8..5a55665db3 100644 --- a/content/en/docs/concepts/storage/storage-classes.md +++ b/content/en/docs/concepts/storage/storage-classes.md @@ -350,7 +350,7 @@ parameters: contains user password to use when talking to Gluster REST service. These parameters are optional, empty password will be used when both `secretNamespace` and `secretName` are omitted. The provided secret must have - type `"kubernetes.io/glusterfs"`, e.g. created in this way: + type `"kubernetes.io/glusterfs"`, for example created in this way: ``` kubectl create secret generic heketi-secret \ @@ -514,7 +514,7 @@ parameters: same as `adminId`. * `userSecretName`: The name of Ceph Secret for `userId` to map RBD image. It must exist in the same namespace as PVCs. This parameter is required. - The provided secret must have type "kubernetes.io/rbd", e.g. created in this + The provided secret must have type "kubernetes.io/rbd", for example created in this way: ```shell @@ -561,7 +561,7 @@ parameters: * `adminSecretName`: secret that holds information about the Quobyte user and the password to authenticate against the API server. The provided secret must have type "kubernetes.io/quobyte" and the keys `user` and `password`, - e.g. created in this way: + for example: ```shell kubectl create secret generic quobyte-admin-secret \ diff --git a/content/en/docs/concepts/storage/volume-pvc-datasource.md b/content/en/docs/concepts/storage/volume-pvc-datasource.md index 85774f4eb6..3178029419 100644 --- a/content/en/docs/concepts/storage/volume-pvc-datasource.md +++ b/content/en/docs/concepts/storage/volume-pvc-datasource.md @@ -60,6 +60,10 @@ spec: name: pvc-1 ``` +{{< note >}} +You must specify a capacity value for `spec.resources.requests.storage`, and the value you specify must be the same or larger than the capacity of the source volume. +{{< /note >}} + The result is a new PVC with the name `clone-of-pvc-1` that has the exact same content as the specified source `pvc-1`. ## Usage diff --git a/content/en/docs/concepts/storage/volumes.md b/content/en/docs/concepts/storage/volumes.md index cbace11392..ac864327e9 100644 --- a/content/en/docs/concepts/storage/volumes.md +++ b/content/en/docs/concepts/storage/volumes.md @@ -605,6 +605,38 @@ spec: type: Directory ``` +{{< caution >}} +It should be noted that the `FileOrCreate` mode does not create the parent directory of the file. If the parent directory of the mounted file does not exist, the pod fails to start. To ensure that this mode works, you can try to mount directories and files separately, as shown below. +{{< /caution >}} + +#### Example Pod FileOrCreate + +```yaml +apiVersion: v1 +kind: Pod +metadata: + name: test-webserver +spec: + containers: + - name: test-webserver + image: k8s.gcr.io/test-webserver:latest + volumeMounts: + - mountPath: /var/local/aaa + name: mydir + - mountPath: /var/local/aaa/1.txt + name: myfile + volumes: + - name: mydir + hostPath: + # Ensure the file directory is created. + path: /var/local/aaa + type: DirectoryOrCreate + - name: myfile + hostPath: + path: /var/local/aaa/1.txt + type: FileOrCreate +``` + ### iscsi {#iscsi} An `iscsi` volume allows an existing iSCSI (SCSI over IP) volume to be mounted diff --git a/content/en/docs/concepts/workloads/controllers/cron-jobs.md b/content/en/docs/concepts/workloads/controllers/cron-jobs.md index c56467322b..f1bfca9519 100644 --- a/content/en/docs/concepts/workloads/controllers/cron-jobs.md +++ b/content/en/docs/concepts/workloads/controllers/cron-jobs.md @@ -27,7 +27,8 @@ that the cron job controller uses. {{< /caution >}} When creating the manifest for a CronJob resource, make sure the name you provide -is no longer than 52 characters. This is because the CronJob controller will automatically +is a valid [DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). +The name must be no longer than 52 characters. This is because the CronJob controller will automatically append 11 characters to the job name provided and there is a constraint that the maximum length of a Job name is no more than 63 characters. diff --git a/content/en/docs/concepts/workloads/controllers/deployment.md b/content/en/docs/concepts/workloads/controllers/deployment.md index 03c58c6525..4f4fa57819 100644 --- a/content/en/docs/concepts/workloads/controllers/deployment.md +++ b/content/en/docs/concepts/workloads/controllers/deployment.md @@ -64,7 +64,7 @@ In this example: * The Pods are labeled `app: nginx`using the `labels` field. * The Pod template's specification, or `.template.spec` field, indicates that the Pods run one container, `nginx`, which runs the `nginx` - [Docker Hub](https://hub.docker.com/) image at version 1.7.9. + [Docker Hub](https://hub.docker.com/) image at version 1.14.2. * Create one container and name it `nginx` using the `name` field. Follow the steps given below to create the above Deployment: @@ -153,15 +153,15 @@ is changed, for example if the labels or container images of the template are up Follow the steps given below to update your Deployment: -1. Let's update the nginx Pods to use the `nginx:1.9.1` image instead of the `nginx:1.7.9` image. +1. Let's update the nginx Pods to use the `nginx:1.16.1` image instead of the `nginx:1.14.2` image. ```shell - kubectl --record deployment.apps/nginx-deployment set image deployment.v1.apps/nginx-deployment nginx=nginx:1.9.1 + kubectl --record deployment.apps/nginx-deployment set image deployment.v1.apps/nginx-deployment nginx=nginx:1.16.1 ``` or simply use the following command: ```shell - kubectl set image deployment/nginx-deployment nginx=nginx:1.9.1 --record + kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record ``` The output is similar to this: @@ -169,7 +169,7 @@ Follow the steps given below to update your Deployment: deployment.apps/nginx-deployment image updated ``` - Alternatively, you can `edit` the Deployment and change `.spec.template.spec.containers[0].image` from `nginx:1.7.9` to `nginx:1.9.1`: + Alternatively, you can `edit` the Deployment and change `.spec.template.spec.containers[0].image` from `nginx:1.14.2` to `nginx:1.16.1`: ```shell kubectl edit deployment.v1.apps/nginx-deployment @@ -265,7 +265,7 @@ up to 3 replicas, as well as scaling down the old ReplicaSet to 0 replicas. Labels: app=nginx Containers: nginx: - Image: nginx:1.9.1 + Image: nginx:1.16.1 Port: 80/TCP Environment: Mounts: @@ -306,11 +306,11 @@ If you update a Deployment while an existing rollout is in progress, the Deploym as per the update and start scaling that up, and rolls over the ReplicaSet that it was scaling up previously -- it will add it to its list of old ReplicaSets and start scaling it down. -For example, suppose you create a Deployment to create 5 replicas of `nginx:1.7.9`, -but then update the Deployment to create 5 replicas of `nginx:1.9.1`, when only 3 -replicas of `nginx:1.7.9` had been created. In that case, the Deployment immediately starts -killing the 3 `nginx:1.7.9` Pods that it had created, and starts creating -`nginx:1.9.1` Pods. It does not wait for the 5 replicas of `nginx:1.7.9` to be created +For example, suppose you create a Deployment to create 5 replicas of `nginx:1.14.2`, +but then update the Deployment to create 5 replicas of `nginx:1.16.1`, when only 3 +replicas of `nginx:1.14.2` had been created. In that case, the Deployment immediately starts +killing the 3 `nginx:1.14.2` Pods that it had created, and starts creating +`nginx:1.16.1` Pods. It does not wait for the 5 replicas of `nginx:1.14.2` to be created before changing course. ### Label selector updates @@ -347,10 +347,10 @@ This means that when you roll back to an earlier revision, only the Deployment's rolled back. {{< /note >}} -* Suppose that you made a typo while updating the Deployment, by putting the image name as `nginx:1.91` instead of `nginx:1.9.1`: +* Suppose that you made a typo while updating the Deployment, by putting the image name as `nginx:1.161` instead of `nginx:1.16.1`: ```shell - kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.91 --record=true + kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.161 --record=true ``` The output is similar to this: @@ -427,7 +427,7 @@ rolled back. Labels: app=nginx Containers: nginx: - Image: nginx:1.91 + Image: nginx:1.161 Port: 80/TCP Host Port: 0/TCP Environment: @@ -468,13 +468,13 @@ Follow the steps given below to check the rollout history: deployments "nginx-deployment" REVISION CHANGE-CAUSE 1 kubectl apply --filename=https://k8s.io/examples/controllers/nginx-deployment.yaml --record=true - 2 kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.9.1 --record=true - 3 kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.91 --record=true + 2 kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.16.1 --record=true + 3 kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.161 --record=true ``` `CHANGE-CAUSE` is copied from the Deployment annotation `kubernetes.io/change-cause` to its revisions upon creation. You can specify the`CHANGE-CAUSE` message by: - * Annotating the Deployment with `kubectl annotate deployment.v1.apps/nginx-deployment kubernetes.io/change-cause="image updated to 1.9.1"` + * Annotating the Deployment with `kubectl annotate deployment.v1.apps/nginx-deployment kubernetes.io/change-cause="image updated to 1.16.1"` * Append the `--record` flag to save the `kubectl` command that is making changes to the resource. * Manually editing the manifest of the resource. @@ -488,10 +488,10 @@ Follow the steps given below to check the rollout history: deployments "nginx-deployment" revision 2 Labels: app=nginx pod-template-hash=1159050644 - Annotations: kubernetes.io/change-cause=kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.9.1 --record=true + Annotations: kubernetes.io/change-cause=kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.16.1 --record=true Containers: nginx: - Image: nginx:1.9.1 + Image: nginx:1.16.1 Port: 80/TCP QoS Tier: cpu: BestEffort @@ -549,7 +549,7 @@ Follow the steps given below to rollback the Deployment from the current version CreationTimestamp: Sun, 02 Sep 2018 18:17:55 -0500 Labels: app=nginx Annotations: deployment.kubernetes.io/revision=4 - kubernetes.io/change-cause=kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.9.1 --record=true + kubernetes.io/change-cause=kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.16.1 --record=true Selector: app=nginx Replicas: 3 desired | 3 updated | 3 total | 3 available | 0 unavailable StrategyType: RollingUpdate @@ -559,7 +559,7 @@ Follow the steps given below to rollback the Deployment from the current version Labels: app=nginx Containers: nginx: - Image: nginx:1.9.1 + Image: nginx:1.16.1 Port: 80/TCP Host Port: 0/TCP Environment: @@ -722,7 +722,7 @@ apply multiple fixes in between pausing and resuming without triggering unnecess * Then update the image of the Deployment: ```shell - kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.9.1 + kubectl set image deployment.v1.apps/nginx-deployment nginx=nginx:1.16.1 ``` The output is similar to this: diff --git a/content/en/docs/concepts/workloads/controllers/jobs-run-to-completion.md b/content/en/docs/concepts/workloads/controllers/jobs-run-to-completion.md index 70f5c7e0fa..8848774103 100644 --- a/content/en/docs/concepts/workloads/controllers/jobs-run-to-completion.md +++ b/content/en/docs/concepts/workloads/controllers/jobs-run-to-completion.md @@ -39,7 +39,7 @@ It takes around 10s to complete. You can run the example with this command: ```shell -kubectl apply -f https://k8s.io/examples/controllers/job.yaml +kubectl apply -f https://kubernetes.io/examples/controllers/job.yaml ``` ``` job.batch/pi created @@ -114,6 +114,7 @@ The output is similar to this: ## Writing a Job Spec As with all other Kubernetes config, a Job needs `apiVersion`, `kind`, and `metadata` fields. +Its name must be a valid [DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). A Job also needs a [`.spec` section](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status). diff --git a/content/en/docs/concepts/workloads/controllers/replicationcontroller.md b/content/en/docs/concepts/workloads/controllers/replicationcontroller.md index d214fca612..bf020b958b 100644 --- a/content/en/docs/concepts/workloads/controllers/replicationcontroller.md +++ b/content/en/docs/concepts/workloads/controllers/replicationcontroller.md @@ -116,6 +116,8 @@ specifies an expression that just gets the name from each pod in the returned li ## Writing a ReplicationController Spec As with all other Kubernetes config, a ReplicationController needs `apiVersion`, `kind`, and `metadata` fields. +The name of a ReplicationController object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). For general information about working with config files, see [object management ](/docs/concepts/overview/working-with-objects/object-management/). A ReplicationController also needs a [`.spec` section](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status). diff --git a/content/en/docs/concepts/workloads/pods/init-containers.md b/content/en/docs/concepts/workloads/pods/init-containers.md index ef4c5eeed9..14e7054a86 100644 --- a/content/en/docs/concepts/workloads/pods/init-containers.md +++ b/content/en/docs/concepts/workloads/pods/init-containers.md @@ -122,10 +122,10 @@ spec: initContainers: - name: init-myservice image: busybox:1.28 - command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;'] + command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"] - name: init-mydb image: busybox:1.28 - command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;'] + command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"] ``` You can start this Pod by running: diff --git a/content/en/docs/concepts/workloads/pods/pod.md b/content/en/docs/concepts/workloads/pods/pod.md index 7dff25cbb5..d64227be48 100644 --- a/content/en/docs/concepts/workloads/pods/pod.md +++ b/content/en/docs/concepts/workloads/pods/pod.md @@ -175,7 +175,7 @@ An example flow: 1. The Pod in the API server is updated with the time beyond which the Pod is considered "dead" along with the grace period. 1. Pod shows up as "Terminating" when listed in client commands 1. (simultaneous with 3) When the Kubelet sees that a Pod has been marked as terminating because the time in 2 has been set, it begins the Pod shutdown process. - 1. If one of the Pod's containers has defined a [preStop hook](/docs/concepts/containers/container-lifecycle-hooks/#hook-details), it is invoked inside of the container. If the `preStop` hook is still running after the grace period expires, step 2 is then invoked with a small (2 second) extended grace period. + 1. If one of the Pod's containers has defined a [preStop hook](/docs/concepts/containers/container-lifecycle-hooks/#hook-details), it is invoked inside of the container. If the `preStop` hook is still running after the grace period expires, step 2 is then invoked with a small (2 second) one-time extended grace period. You must modify `terminationGracePeriodSeconds` if the `preStop` hook needs longer to complete. 1. The container is sent the TERM signal. Note that not all containers in the Pod will receive the TERM signal at the same time and may each require a `preStop` hook if the order in which they shut down matters. 1. (simultaneous with 3) Pod is removed from endpoints list for service, and are no longer considered part of the set of running Pods for replication controllers. Pods that shutdown slowly cannot continue to serve traffic as load balancers (like the service proxy) remove them from their rotations. 1. When the grace period expires, any processes still running in the Pod are killed with SIGKILL. @@ -203,5 +203,7 @@ Your container runtime must support the concept of a privileged container for th Pod is a top-level resource in the Kubernetes REST API. The [Pod API object](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#pod-v1-core) definition describes the object in detail. +When creating the manifest for a Pod object, make sure the name specified is a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). {{% /capture %}} diff --git a/content/en/docs/contribute/generate-ref-docs/kubectl.md b/content/en/docs/contribute/generate-ref-docs/kubectl.md index 797a0f5371..5930a1f452 100644 --- a/content/en/docs/contribute/generate-ref-docs/kubectl.md +++ b/content/en/docs/contribute/generate-ref-docs/kubectl.md @@ -47,7 +47,7 @@ Get a local clone of the following repositories: go get -u github.com/spf13/pflag go get -u github.com/spf13/cobra go get -u gopkg.in/yaml.v2 -go get -u kubernetes-sigs/reference-docs +go get -u github.com/kubernetes-sigs/reference-docs ``` If you don't already have the kubernetes/website repository, get it now: @@ -140,15 +140,15 @@ need to work with someone who can set the label and milestone for you. Go to ``. On you command line, set the following environment variables. * Set `K8S_ROOT` to ``. -* Set `WEB_ROOT` to ``. +* Set `K8S_WEBROOT` to ``. * Set `K8S_RELEASE` to the version of the docs you want to build. For example, if you want to build docs for Kubernetes 1.17, set `K8S_RELEASE` to 1.17. For example: ```shell -export WEB_ROOT=$(GOPATH)/src/github.com//website -export K8S_ROOT=$(GOPATH)/src/k8s.io/kubernetes +export K8S_WEBROOT=$GOPATH/src/github.com//website +export K8S_ROOT=$GOPATH/src/k8s.io/kubernetes export K8S_RELEASE=1.17 ``` diff --git a/content/en/docs/contribute/intermediate.md b/content/en/docs/contribute/intermediate.md index 2da6ccf523..9e477a90a4 100644 --- a/content/en/docs/contribute/intermediate.md +++ b/content/en/docs/contribute/intermediate.md @@ -911,8 +911,8 @@ deadlines. Some deadlines related to documentation are: If your feature is an Alpha feature and is behind a feature gate, make sure you add it to [Feature gates](/docs/reference/command-line-tools-reference/feature-gates/) -as part of your pull request. If your feature is moving out of Alpha, make sure to -remove it from that file. +as part of your pull request. If your feature is moving to Beta +or to General Availability, update the feature gates file. ## Contribute to other repos diff --git a/content/en/docs/contribute/start.md b/content/en/docs/contribute/start.md index acd5a5bfdf..181e359682 100644 --- a/content/en/docs/contribute/start.md +++ b/content/en/docs/contribute/start.md @@ -209,7 +209,7 @@ to base your work on. Use these guidelines to make the decision: - Some localization teams work with a series of long-lived branches, and periodically merge these to `master`. This kind of branch has a name like dev-\-\.\; for example: - `dev-{{< release-branch >}}-ja.1`. + `dev-{{< latest-semver >}}-ja.1` - If you're writing or updating documentation for a feature change release, then you need to know the major and minor version of Kubernetes that the change will first appear in. @@ -217,8 +217,8 @@ to base your work on. Use these guidelines to make the decision: to beta in the next minor version, you need to know what the next minor version number is. - Find the release branch named for that version. For example, features that - changed in the v{{< release-branch >}} release got documented in the branch - named `dev-{{< release-branch >}}`. + changed in the {{< latest-version >}} release got documented in the branch + named `dev-{{< latest-semver >}}`. If you're still not sure which branch to choose, ask in `#sig-docs` on Slack or attend a weekly SIG Docs meeting to get clarity. diff --git a/content/en/docs/contribute/style/content-guide.md b/content/en/docs/contribute/style/content-guide.md index 5d3f5790c7..b96f28eac7 100644 --- a/content/en/docs/contribute/style/content-guide.md +++ b/content/en/docs/contribute/style/content-guide.md @@ -10,107 +10,68 @@ card: --- {{% capture overview %}} -This page contains guidelines for adding content to the Kubernetes documentation. -If you have questions about allowed content, join the [Kubernetes Slack](http://slack.k8s.io/) #sig-docs channel and ask! Use your best judgment, and feel free to -propose changes to this document in a pull request. -For additional information on creating new content for the Kubernetes -docs, follow the instructions in the [Style guide](/docs/contribute/style/style-guide). +This page contains guidelines for Kubernetes documentation. + +If you have questions about what's allowed, join the #sig-docs channel in +[Kubernetes Slack](http://slack.k8s.io/) and ask! + +You can register for Kubernetes Slack at http://slack.k8s.io/. + +For information on creating new content for the Kubernetes +docs, follow the [style guide](/docs/contribute/style/style-guide). + {{% /capture %}} {{% capture body %}} -## Contributing content -The Kubernetes documentation comprises the content of the -[kubernetes/website](https://github.com/kubernetes/website) source repository. +## Overview + +Source for the Kubernetes website, including the docs, resides in the +[kubernetes/website](https://github.com/kubernetes/website) repository. + Located in the `kubernetes/website/content//docs` folder, the -majority of the Kubernetes documentation is specific to the [Kubernetes -project](https://github.com/kubernetes/kubernetes). The Kubernetes -documentation may also include content from projects in the -[kubernetes](https://github.com/kubernetes) and -[kubernetes-sigs](https://github.com/kubernetes-sigs) GitHub organizations if -those projects do not have their own documentation. Linking to active kubernetes, -kubernetes-sigs, and ({{< glossary_tooltip text="CNCF" term_id="cncf" >}}) projects from the Kubernetes documentation is always -allowed, but linking to vendor-specific products is not. Check the CNCF project lists -([Graduated/Incubating](https://www.cncf.io/projects/), -[Sandbox](https://www.cncf.io/sandbox-projects/), -[Archived](https://www.cncf.io/archived-projects/)) if you are unsure of a -project's CNCF status. +majority of Kubernetes documentation is specific to the [Kubernetes +project](https://github.com/kubernetes/kubernetes). -### Dual-sourced content +## What's allowed -Kubernetes documentation does not include duplicate content sourced from multiple -locations (*dual-sourced* content). Dual-sourced content requires duplicated -effort from project maintainers and tends to become outdated more quickly. -Before adding content, ask yourself this: +Kubernetes docs permit only some kinds of content. -- Is the content about an active CNCF project OR a project in the kubernetes or kubernetes-sigs GitHub organizations? - - If yes, then: - - Does the project have its own documentation? - - if yes, link to the project's documentation from the Kubernetes documentation - - if no, add the content to the project's repository if possible and then link to it from the Kubernetes documentation - - If no, then: - - Stop! - - Adding content about vendor-specific products is not allowed - - Linking to vendor-specific documentation and websites is not allowed +### Third party content +Kubernetes documentation includes applied examples of projects in the Kubernetes project&emdash;projects that live in the [kubernetes](https://github.com/kubernetes) and +[kubernetes-sigs](https://github.com/kubernetes-sigs) GitHub organizations. -### What is and isn't allowed +Links to active content in the Kubernetes project are always allowed. -There are some scenarios in which the Kubernetes documentation includes content from non-Kubernetes projects. -Below are general categories of non-Kubernetes project content along with guidelines of what is and is not allowed: +Kubernetes requires some third party content to function. Examples include container runtimes (containerd, CRI-O, Docker), +[networking policy](/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/) (CNI plugins), [Ingress controllers](https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/), and [logging](https://kubernetes.io/docs/concepts/cluster-administration/logging/). -1. Instructional content involving non-Kubernetes projects during setup or operation of Kubernetes - - Allowed: - - Referring to or linking to existing documentation about a CNCF project or a project in the kubernetes or kubernetes-sigs GitHub organizations - - Example: for installating Kubernetes in a learning environment, including a prerequisite stating that successful installation and configuration of minikube is required and linking to the relevant minikube documentation - - Adding content for kubernetes or kubernetes-sigs projects that don't have their own instructional content - - Example: including [kubeadm](https://github.com/kubernetes/kubeadm) installation and troubleshooting instructions - - Not Allowed: - - Adding content that duplicates documentation in another repository - - Examples: - - Including minikube installation and configuration instructions; minikube has its own [documentation](https://minikube.sigs.k8s.io/docs/) that provides those instructions - - Including instructions for installing Docker, CRI-O, containerd, and other container runtimes on various operating systems - - Including instructions for installing Kubernetes on production environments using various projects: - - Kubernetes Rebar Integrated Bootstrap (KRIB) is a vendor-specific project and content belongs in the vendor's documentation - - [Kubernetes Operations (kops)](https://github.com/kubernetes/kops) has installation instructions and tutorials in its GitHub repository - - [Kubespray](https://kubespray.io) has its own documentation - - Adding a tutorial that explains how to perform a task using a vendor-specific product or an open source project that is not a CNCF project or a project in the kubernetes or kubnetes-sigs GitHub organizations - - Adding a tutorial on how to use a CNCF project or a project in the kubernetes or kubnetes-sigs GitHub organizations if the project has its own documentation -1. Detailed technical content about how to use a non-Kubernetes project or how that project is designed +Docs can link to third-party open source software (OSS) outside the Kubernetes project if it's necessary for Kubernetes to function. - Adding this type of content to the Kubernetes documentation is not allowed. -1. Content that describes a non-Kubernetes project - - Allowed: - - Adding a brief introductory paragraph about a CNCF project or a project in the kubernetes or kubernetes-sigs GitHub organizations; the paragraph may contain links to the project - - Not Allowed: - - Adding content describing a vendor-specific product - - Adding content describing an open source project that is not a CNCF project or a project in the kubernetes or kubnetes-sigs GitHub organizations - - Adding content that duplicates documentation from another project, regardless of source repository - - Example: adding [Kubernetes in Docker (KinD)](https://kind.sigs.k8s.io) documentation to the Kubernetes documentation -1. Content that simply links to information about a non-Kubernetes project - - Allowed: - - Linking to projects in the kubernetes and kubernetes-sigs GitHub organizations - - Example: linking to Kubernetes in Docker (KinD) [documentation](https://kind.sigs.k8s.io/docs/user/quick-start), which resides in the kubernetes-sigs GitHub organization - - Linking to active CNCF projects - - Example: linking to the Prometheus [documentation](https://prometheus.io/docs/introduction/overview/); Prometheus is an active CNCF project - - Not Allowed: - - Linking to vendor-specific products - - Linking to archived CNCF projects - - Linking to inactive projects in the kubernetes and kubernetes-sigs GitHub organizations - - Linking to open source projects that are not CNCF projects or do not reside in the kubernetes or kubernetes-sigs GitHub organizations -1. Content about training courses - - Allowed: - - Linking to vendor-neutral Kubernetes training courses offered by the [CNCF](https://www.cncf.io/), the [Linux Foundation](https://www.linuxfoundation.org/), and the [Linux Academy](https://linuxacademy.com/), which is a partner of the Linux Foundation - - Example: linking to Linux Academy courses such as [Kubernetes Quick Start](https://linuxacademy.com/course/kubernetes-quick-start/) and [Kubernetes Security](https://linuxacademy.com/course/kubernetes-security/) - - Not Allowed: - - Linking to online training outside of the CNCF, the Linux Foundation, or the Linux Academy; the Kubernetes documentation does not link to third-party content - - Example: linking to Kubernetes tutorials or courses on Medium, KodeKloud, Udacity, Coursera, learnk8s, and similar websites - - Linking to vendor-specific tutorials regardless of the training provider - - Example: linking to Linux Academy courses such as [Google Kubernetes Engine Deep Dive](https://linuxacademy.com/google-cloud-platform/training/course/name/google-kubernetes-engine-deep-dive) and [Amazon EKS Deep Dive](https://linuxacademy.com/course/amazon-eks-deep-dive/) +### Dual sourced content + +Wherever possible, Kubernetes docs link to canonical sources instead of hosting +dual-sourced content. + +Dual-sourced content requires double the effort (or more!) to maintain +and grows stale more quickly. + +{{< note >}} + +If you're a maintainer for a Kubernetes project and need help hosting your own docs, +ask for help in [#sig-docs on Kubernetes Slack](https://kubernetes.slack.com/messages/C1J0BPD2M/). + +{{< /note >}} + +### More information If you have questions about allowed content, join the [Kubernetes Slack](http://slack.k8s.io/) #sig-docs channel and ask! + {{% /capture %}} {{% capture whatsnext %}} + * Read the [Style guide](/docs/contribute/style/style-guide). + {{% /capture %}} diff --git a/content/en/docs/contribute/style/content-organization.md b/content/en/docs/contribute/style/content-organization.md index 55997dcaf5..e93cf8126e 100644 --- a/content/en/docs/contribute/style/content-organization.md +++ b/content/en/docs/contribute/style/content-organization.md @@ -107,7 +107,6 @@ Another widely used example is the `includes` bundle. It sets `headless: true` i ```bash en/includes ├── default-storage-class-prereqs.md -├── federated-task-tutorial-prereqs.md ├── index.md ├── partner-script.js ├── partner-style.css diff --git a/content/en/docs/contribute/style/style-guide.md b/content/en/docs/contribute/style/style-guide.md index 30865c49e8..12a6c66839 100644 --- a/content/en/docs/contribute/style/style-guide.md +++ b/content/en/docs/contribute/style/style-guide.md @@ -183,7 +183,7 @@ For field values of type string or integer, use normal style without quotation m Do | Don't :--| :----- Set the value of `imagePullPolicy` to Always. | Set the value of `imagePullPolicy` to "Always". -Set the value of `image` to nginx:1.8. | Set the value of `image` to `nginx:1.8`. +Set the value of `image` to nginx:1.16. | Set the value of `image` to `nginx:1.16`. Set the value of the `replicas` field to 2. | Set the value of the `replicas` field to `2`. {{< /table >}} diff --git a/content/en/docs/home/_index.md b/content/en/docs/home/_index.md index 31f37880ff..692f10dbef 100644 --- a/content/en/docs/home/_index.md +++ b/content/en/docs/home/_index.md @@ -16,6 +16,8 @@ menu: weight: 20 post: >

Learn how to use Kubernetes with conceptual, tutorial, and reference documentation. You can even help contribute to the docs!

+description: > + Kubernetes is an open source container orchestration engine for automating deployment, scaling, and management of containerized applications. The open source project is hosted by the Cloud Native Computing Foundation. overview: > Kubernetes is an open source container orchestration engine for automating deployment, scaling, and management of containerized applications. The open source project is hosted by the Cloud Native Computing Foundation (CNCF). cards: @@ -36,9 +38,14 @@ cards: button_path: "/docs/setup" - name: tasks title: "Learn how to use Kubernetes" - description: "Look up common tasks and how to perform them using a short sequence of steps." + description: "Look up common tasks and how to perform them using a short sequence of steps." button: "View Tasks" button_path: "/docs/tasks" +- name: training + title: "Training" + description: "Get certified in Kubernetes and make your cloud native projects successful!" + button: "View training" + button_path: "/training" - name: reference title: Look up reference information description: Browse terminology, command line syntax, API resource types, and setup tool documentation. diff --git a/content/en/docs/reference/access-authn-authz/admission-controllers.md b/content/en/docs/reference/access-authn-authz/admission-controllers.md index 2ab54051a4..7160c25f45 100644 --- a/content/en/docs/reference/access-authn-authz/admission-controllers.md +++ b/content/en/docs/reference/access-authn-authz/admission-controllers.md @@ -645,21 +645,30 @@ for more information. ### PodTolerationRestriction {#podtolerationrestriction} -This admission controller first verifies any conflict between a pod's tolerations and its -namespace's tolerations, and rejects the pod request if there is a conflict. -It then merges the namespace's tolerations into the pod's tolerations. -The resulting tolerations are checked against the namespace's whitelist of -tolerations. If the check succeeds, the pod request is admitted otherwise -rejected. +The PodTolerationRestriction admission controller verifies any conflict between tolerations of a pod and the tolerations of its namespace. +It rejects the pod request if there is a conflict. +It then merges the tolerations annotated on the namespace into the tolerations of the pod. +The resulting tolerations are checked against a whitelist of tolerations annotated to the namespace. +If the check succeeds, the pod request is admitted otherwise it is rejected. -If the pod's namespace does not have any associated default or whitelist of -tolerations, then the cluster-level default or whitelist of tolerations are used -instead if specified. +If the namespace of the pod does not have any associated default tolerations or a whitelist of +tolerations annotated, the cluster-level default tolerations or cluster-level whitelist of tolerations are used +instead if they are specified. -Tolerations to a namespace are assigned via the -`scheduler.alpha.kubernetes.io/defaultTolerations` and -`scheduler.alpha.kubernetes.io/tolerationsWhitelist` -annotation keys. +Tolerations to a namespace are assigned via the `scheduler.alpha.kubernetes.io/defaultTolerations` annotation key. +The whitelist can be added via the `scheduler.alpha.kubernetes.io/tolerationsWhitelist` annotation key. + +Example for namespace annotations: + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: apps-that-need-nodes-exclusively + annotations: + scheduler.alpha.kubernetes.io/defaultTolerations: '{"operator": "Exists", "effect": "NoSchedule", "key": "dedicated-node"}' + scheduler.alpha.kubernetes.io/tolerationsWhitelist: '{"operator": "Exists", "effect": "NoSchedule", "key": "dedicated-node"}' +``` ### Priority {#priority} @@ -732,7 +741,7 @@ For Kubernetes 1.9 and earlier, we recommend running the following set of admiss ``` * It's worth reiterating that in 1.9, these happen in a mutating phase -and a validating phase, and that e.g. `ResourceQuota` runs in the validating +and a validating phase, and that for example `ResourceQuota` runs in the validating phase, and therefore is the last admission controller to run. `MutatingAdmissionWebhook` appears before it in this list, because it runs in the mutating phase. diff --git a/content/en/docs/reference/access-authn-authz/authentication.md b/content/en/docs/reference/access-authn-authz/authentication.md index 0065bf7abe..0089c08a91 100644 --- a/content/en/docs/reference/access-authn-authz/authentication.md +++ b/content/en/docs/reference/access-authn-authz/authentication.md @@ -208,7 +208,7 @@ spec: serviceAccountName: bob-the-bot containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ``` Service account bearer tokens are perfectly valid to use outside the cluster and diff --git a/content/en/docs/reference/access-authn-authz/extensible-admission-controllers.md b/content/en/docs/reference/access-authn-authz/extensible-admission-controllers.md index 4131a79df8..c57bcdaf34 100644 --- a/content/en/docs/reference/access-authn-authz/extensible-admission-controllers.md +++ b/content/en/docs/reference/access-authn-authz/extensible-admission-controllers.md @@ -114,7 +114,7 @@ webhooks: service: namespace: "example-namespace" name: "example-service" - caBundle: "Ci0tLS0tQk......tLS0K" + caBundle: "Ci0tLS0tQk...<`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate.>...tLS0K" admissionReviewVersions: ["v1", "v1beta1"] sideEffects: None timeoutSeconds: 5 @@ -139,7 +139,7 @@ webhooks: service: namespace: "example-namespace" name: "example-service" - caBundle: "Ci0tLS0tQk......tLS0K" + caBundle: "Ci0tLS0tQk...<`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate>...tLS0K" admissionReviewVersions: ["v1beta1"] timeoutSeconds: 5 ``` @@ -1050,7 +1050,7 @@ to turn up in a new cluster. The scheme must be "https"; the URL must begin with "https://". -Attempting to use a user or basic auth e.g. "user:password@" is not allowed. +Attempting to use a user or basic auth (for example "user:password@") is not allowed. Fragments ("#...") and query parameters ("?...") are also not allowed. Here is an example of a mutating webhook configured to call a URL @@ -1122,7 +1122,7 @@ kind: MutatingWebhookConfiguration webhooks: - name: my-webhook.example.com clientConfig: - caBundle: "Ci0tLS0tQk......tLS0K" + caBundle: "Ci0tLS0tQk...<`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate>...tLS0K" service: namespace: my-service-namespace name: my-service-name diff --git a/content/en/docs/reference/access-authn-authz/rbac.md b/content/en/docs/reference/access-authn-authz/rbac.md index 852e73fd79..3e18ae283e 100644 --- a/content/en/docs/reference/access-authn-authz/rbac.md +++ b/content/en/docs/reference/access-authn-authz/rbac.md @@ -74,6 +74,9 @@ rules: verbs: ["get", "watch", "list"] ``` +The name of a Role or a ClusterRole object must be a valid +[path segment name](/docs/concepts/overview/working-with-objects/names#path-segment-names). + ### RoleBinding and ClusterRoleBinding A role binding grants the permissions defined in a role to a user or set of users. @@ -81,6 +84,9 @@ It holds a list of subjects (users, groups, or service accounts), and a referenc Permissions can be granted within a namespace with a `RoleBinding`, or cluster-wide with a `ClusterRoleBinding`. A `RoleBinding` may reference a `Role` in the same namespace. +The name of a `RoleBinding` object must be a valid +[path segment name](/docs/concepts/overview/working-with-objects/names#path-segment-names). + The following `RoleBinding` grants the "pod-reader" role to the user "jane" within the "default" namespace. This allows "jane" to read pods in the "default" namespace. @@ -129,8 +135,10 @@ roleRef: apiGroup: rbac.authorization.k8s.io ``` -Finally, a `ClusterRoleBinding` may be used to grant permission at the cluster level and in all -namespaces. The following `ClusterRoleBinding` allows any user in the group "manager" to read +Finally, a `ClusterRoleBinding` may be used to grant permission at the cluster level and in all namespaces. + The name of a `ClusterRoleBinding` object must be a valid +[path segment name](/docs/concepts/overview/working-with-objects/names#path-segment-names). +The following `ClusterRoleBinding` allows any user in the group "manager" to read secrets in any namespace. ```yaml diff --git a/content/en/docs/reference/glossary/annotation.md b/content/en/docs/reference/glossary/annotation.md index 03feb69a05..474573ef16 100755 --- a/content/en/docs/reference/glossary/annotation.md +++ b/content/en/docs/reference/glossary/annotation.md @@ -14,5 +14,5 @@ tags: -The metadata in an annotation can be small or large, structured or unstructured, and can include characters not permitted by labels. Clients such as tools and libraries can retrieve this metadata. +The metadata in an annotation can be small or large, structured or unstructured, and can include characters not permitted by {{< glossary_tooltip text="labels" term_id="label" >}}. Clients such as tools and libraries can retrieve this metadata. diff --git a/content/en/docs/reference/glossary/cluster-infrastructure.md b/content/en/docs/reference/glossary/cluster-infrastructure.md index 0b8a5377b4..d8a6fe7280 100644 --- a/content/en/docs/reference/glossary/cluster-infrastructure.md +++ b/content/en/docs/reference/glossary/cluster-infrastructure.md @@ -8,6 +8,6 @@ short_description: > aka: tags: -- operations +- operation --- -The infrastructure layer provides and maintains VMs, networking, security groups and others. + The infrastructure layer provides and maintains VMs, networking, security groups and others. diff --git a/content/en/docs/reference/glossary/cluster-operations.md b/content/en/docs/reference/glossary/cluster-operations.md index 424e6579fc..cf4831d935 100644 --- a/content/en/docs/reference/glossary/cluster-operations.md +++ b/content/en/docs/reference/glossary/cluster-operations.md @@ -4,10 +4,18 @@ id: cluster-operations date: 2019-05-12 full_link: short_description: > - Activities such as upgrading the clusters, implementing security, storage, ingress, networking, logging and monitoring, and other operations involved in managing a Kubernetes cluster. + The work involved in managing a Kubernetes cluster. aka: tags: -- operations +- operation --- - Activities such as upgrading the clusters, implementing security, storage, ingress, networking, logging and monitoring, and other operations involved in managing a Kubernetes cluster. + The work involved in managing a Kubernetes cluster: managing +day-to-day operations, and co-ordinating upgrades. + + + + Examples of cluster operations work include: deploying new Nodes to +scale the cluster; performing software upgrades; implementing security +controls; adding or removing storage; configuring cluster networking; +managing cluster-wide observability; and responding to events. diff --git a/content/en/docs/reference/glossary/cluster.md b/content/en/docs/reference/glossary/cluster.md index 2e8aecb23e..8f2659459b 100755 --- a/content/en/docs/reference/glossary/cluster.md +++ b/content/en/docs/reference/glossary/cluster.md @@ -11,7 +11,13 @@ tags: - fundamental - operation --- -A set of worker machines, called nodes, that run containerized applications. Every cluster has at least one worker node. +A set of worker machines, called {{< glossary_tooltip text="nodes" term_id="node" >}}, +that run containerized applications. Every cluster has at least one worker node. -The worker node(s) host the pods that are the components of the application. The Control Plane manages the worker nodes and the pods in the cluster. In production environments, the Control Plane usually runs across multiple computers and a cluster usually runs multiple nodes, providing fault-tolerance and high availability. +The worker node(s) host the {{< glossary_tooltip text="Pods" term_id="pod" >}} that are +the components of the application workload. The +{{< glossary_tooltip text="control plane" term_id="control-plane" >}} manages the worker +nodes and the Pods in the cluster. In production environments, the control plane usually +runs across multiple computers and a cluster usually runs multiple nodes, providing +fault-tolerance and high availability. diff --git a/content/en/docs/reference/glossary/container-env-variables.md b/content/en/docs/reference/glossary/container-env-variables.md index a4682f5719..5e19a1dfa2 100755 --- a/content/en/docs/reference/glossary/container-env-variables.md +++ b/content/en/docs/reference/glossary/container-env-variables.md @@ -10,8 +10,8 @@ aka: tags: - fundamental --- - Container environment variables are name=value pairs that provide useful information into containers running in a Pod. + Container environment variables are name=value pairs that provide useful information into containers running in a {{< glossary_tooltip text="pod" term_id="pod" >}} -Container environment variables provide information that is required by the running containerized applications along with information about important resources to the {{< glossary_tooltip text="Containers" term_id="container" >}}. For example, file system details, information about the container itself, and other cluster resources such as service endpoints. \ No newline at end of file +Container environment variables provide information that is required by the running containerized applications along with information about important resources to the {{< glossary_tooltip text="containers" term_id="container" >}}. For example, file system details, information about the container itself, and other cluster resources such as service endpoints. diff --git a/content/en/docs/reference/glossary/deployment.md b/content/en/docs/reference/glossary/deployment.md index 89a4f7b9b2..b1ea465746 100755 --- a/content/en/docs/reference/glossary/deployment.md +++ b/content/en/docs/reference/glossary/deployment.md @@ -16,5 +16,5 @@ tags: -Each replica is represented by a {{< glossary_tooltip term_id="pod" >}}, and the Pods are distributed among the nodes of a cluster. +Each replica is represented by a {{< glossary_tooltip term_id="pod" >}}, and the Pods are distributed among the {{< glossary_tooltip text="nodes" term_id="node" >}} of a cluster. diff --git a/content/en/docs/reference/glossary/horizontal-pod-autoscaler.md b/content/en/docs/reference/glossary/horizontal-pod-autoscaler.md index 4e3ace729e..d90009583c 100755 --- a/content/en/docs/reference/glossary/horizontal-pod-autoscaler.md +++ b/content/en/docs/reference/glossary/horizontal-pod-autoscaler.md @@ -11,9 +11,9 @@ aka: tags: - operation --- - An API resource that automatically scales the number of pod replicas based on targeted CPU utilization or custom metric targets. + An API resource that automatically scales the number of {{< glossary_tooltip term_id="pod" >}} replicas based on targeted CPU utilization or custom metric targets. -HPA is typically used with {{< glossary_tooltip text="Replication Controllers" term_id="replication-controller" >}}, {{< glossary_tooltip text="Deployments" term_id="deployment" >}}, or Replica Sets. It cannot be applied to objects that cannot be scaled, for example {{< glossary_tooltip text="DaemonSets" term_id="daemonset" >}}. +HPA is typically used with {{< glossary_tooltip text="ReplicationControllers" term_id="replication-controller" >}}, {{< glossary_tooltip text="Deployments" term_id="deployment" >}}, or {{< glossary_tooltip text="ReplicaSets" term_id="replica-set" >}}. It cannot be applied to objects that cannot be scaled, for example {{< glossary_tooltip text="DaemonSets" term_id="daemonset" >}}. diff --git a/content/en/docs/reference/glossary/host-aliases.md b/content/en/docs/reference/glossary/host-aliases.md index fa92be21f4..47bd22d433 100644 --- a/content/en/docs/reference/glossary/host-aliases.md +++ b/content/en/docs/reference/glossary/host-aliases.md @@ -10,7 +10,7 @@ aka: tags: - operation --- - A HostAliases is a mapping between the IP address and hostname to be injected into a Pod's hosts file. + A HostAliases is a mapping between the IP address and hostname to be injected into a {{< glossary_tooltip text="Pod" term_id="pod" >}}'s hosts file. diff --git a/content/en/docs/reference/glossary/image.md b/content/en/docs/reference/glossary/image.md index cdb2c7e02c..d185fc2eed 100755 --- a/content/en/docs/reference/glossary/image.md +++ b/content/en/docs/reference/glossary/image.md @@ -10,9 +10,9 @@ aka: tags: - fundamental --- - Stored instance of a container that holds a set of software needed to run an application. + Stored instance of a {{< glossary_tooltip term_id="container" >}} that holds a set of software needed to run an application. - + A way of packaging software that allows it to be stored in a container registry, pulled to a local system, and run as an application. Meta data is included in the image that can indicate what executable to run, who built it, and other information. diff --git a/content/en/docs/reference/glossary/ingress.md b/content/en/docs/reference/glossary/ingress.md index 0a83428002..6fe935fb4e 100755 --- a/content/en/docs/reference/glossary/ingress.md +++ b/content/en/docs/reference/glossary/ingress.md @@ -16,5 +16,5 @@ tags: -Ingress can provide load balancing, SSL termination and name-based virtual hosting. +Ingress may provide load balancing, SSL termination and name-based virtual hosting. diff --git a/content/en/docs/reference/glossary/init-container.md b/content/en/docs/reference/glossary/init-container.md index 2ea793661c..a999042e30 100755 --- a/content/en/docs/reference/glossary/init-container.md +++ b/content/en/docs/reference/glossary/init-container.md @@ -4,15 +4,14 @@ id: init-container date: 2018-04-12 full_link: short_description: > - One or more initialization containers that must run to completion before any app containers run. + One or more initialization containers that must run to completion before any app containers run. aka: tags: - fundamental --- - One or more initialization containers that must run to completion before any app containers run. + One or more initialization {{< glossary_tooltip text="containers" term_id="container" >}} that must run to completion before any app containers run. -Initialization (init) containers are like regular app containers, with one difference: init containers must run to completion before any app containers can start. Init containers run in series: each init container must run to completion before the next init container begins. - +Initialization (init) containers are like regular app containers, with one difference: init containers must run to completion before any app containers can start. Init containers run in series: each init container must run to completion before the next init container begins. diff --git a/content/en/docs/reference/glossary/kube-proxy.md b/content/en/docs/reference/glossary/kube-proxy.md index 87be7e68ac..3b2a572504 100755 --- a/content/en/docs/reference/glossary/kube-proxy.md +++ b/content/en/docs/reference/glossary/kube-proxy.md @@ -11,15 +11,17 @@ tags: - fundamental - networking --- - [kube-proxy](/docs/reference/command-line-tools-reference/kube-proxy/) is a -network proxy that runs on each node in your cluster, implementing part of -the Kubernetes {{< glossary_tooltip term_id="service">}} concept. + kube-proxy is a network proxy that runs on each +{{< glossary_tooltip text="node" term_id="node" >}} in your cluster, +implementing part of the Kubernetes +{{< glossary_tooltip term_id="service">}} concept. -kube-proxy maintains network rules on nodes. These network rules allow -network communication to your Pods from network sessions inside or outside -of your cluster. +[kube-proxy](/docs/reference/command-line-tools-reference/kube-proxy/) +maintains network rules on nodes. These network rules allow network +communication to your Pods from network sessions inside or outside of +your cluster. kube-proxy uses the operating system packet filtering layer if there is one and it's available. Otherwise, kube-proxy forwards the traffic itself. diff --git a/content/en/docs/reference/glossary/kube-scheduler.md b/content/en/docs/reference/glossary/kube-scheduler.md index 7094a6982a..e3babcab3f 100755 --- a/content/en/docs/reference/glossary/kube-scheduler.md +++ b/content/en/docs/reference/glossary/kube-scheduler.md @@ -4,15 +4,20 @@ id: kube-scheduler date: 2018-04-12 full_link: /docs/reference/generated/kube-scheduler/ short_description: > - Control Plane component that watches for newly created pods with no assigned node, and selects a node for them to run on. + Control plane component that watches for newly created pods with no assigned node, and selects a node for them to run on. aka: tags: - architecture --- - Control Plane component that watches for newly created pods with no assigned node, and selects a node for them to run on. +Control plane component that watches for newly created +{{< glossary_tooltip term_id="node" >}} with no assigned +{{< glossary_tooltip term_id="node" text="node">}}, and selects a node for them +to run on. - - -Factors taken into account for scheduling decisions include individual and collective resource requirements, hardware/software/policy constraints, affinity and anti-affinity specifications, data locality, inter-workload interference and deadlines. + +Factors taken into account for scheduling decisions include: +individual and collective resource requirements, hardware/software/policy +constraints, affinity and anti-affinity specifications, data locality, +inter-workload interference, and deadlines. diff --git a/content/en/docs/reference/glossary/kubeadm.md b/content/en/docs/reference/glossary/kubeadm.md index ce26062270..74cc0d1f6a 100755 --- a/content/en/docs/reference/glossary/kubeadm.md +++ b/content/en/docs/reference/glossary/kubeadm.md @@ -15,5 +15,5 @@ tags: -You can use kubeadm to install both the control plane and the worker node components. +You can use kubeadm to install both the control plane and the {{< glossary_tooltip text="worker node" term_id="node" >}} components. diff --git a/content/en/docs/reference/glossary/kubelet.md b/content/en/docs/reference/glossary/kubelet.md index 0c4ea9425a..0c95ac846e 100755 --- a/content/en/docs/reference/glossary/kubelet.md +++ b/content/en/docs/reference/glossary/kubelet.md @@ -11,9 +11,8 @@ tags: - fundamental - core-object --- - An agent that runs on each node in the cluster. It makes sure that containers are running in a pod. + An agent that runs on each {{< glossary_tooltip text="node" term_id="node" >}} in the cluster. It makes sure that {{< glossary_tooltip text="containers" term_id="container" >}} are running in a {{< glossary_tooltip text="Pod" term_id="pod" >}}. The kubelet takes a set of PodSpecs that are provided through various mechanisms and ensures that the containers described in those PodSpecs are running and healthy. The kubelet doesn’t manage containers which were not created by Kubernetes. - diff --git a/content/en/docs/reference/glossary/persistent-volume-claim.md b/content/en/docs/reference/glossary/persistent-volume-claim.md index dc6314d887..6af54d60f5 100755 --- a/content/en/docs/reference/glossary/persistent-volume-claim.md +++ b/content/en/docs/reference/glossary/persistent-volume-claim.md @@ -11,9 +11,8 @@ tags: - core-object - storage --- - Claims storage resources defined in a PersistentVolume so that it can be mounted as a volume in a container. + Claims storage resources defined in a {{< glossary_tooltip text="PersistentVolume" term_id="persistent-volume" >}} so that it can be mounted as a volume in a {{< glossary_tooltip text="container" term_id="container" >}}. -Specifies the amount of storage, how the storage will be accessed (read-only, read-write and/or exclusive) and how it is reclaimed (retained, recycled or deleted). Details of the storage itself are in the PersistentVolume specification. - +Specifies the amount of storage, how the storage will be accessed (read-only, read-write and/or exclusive) and how it is reclaimed (retained, recycled or deleted). Details of the storage itself are described in the PersistentVolume object. diff --git a/content/en/docs/reference/glossary/pod-priority.md b/content/en/docs/reference/glossary/pod-priority.md index 0b80602b35..994f8bc4d8 100644 --- a/content/en/docs/reference/glossary/pod-priority.md +++ b/content/en/docs/reference/glossary/pod-priority.md @@ -10,7 +10,7 @@ aka: tags: - operation --- - Pod Priority indicates the importance of a Pod relative to other Pods. + Pod Priority indicates the importance of a {{< glossary_tooltip term_id="pod" >}} relative to other Pods. diff --git a/content/en/docs/reference/glossary/podpreset.md b/content/en/docs/reference/glossary/podpreset.md index c60f03cd95..f63187ff71 100755 --- a/content/en/docs/reference/glossary/podpreset.md +++ b/content/en/docs/reference/glossary/podpreset.md @@ -10,9 +10,9 @@ aka: tags: - operation --- - An API object that injects information such as secrets, volume mounts, and environment variables into pods at creation time. + An API object that injects information such as secrets, volume mounts, and environment variables into {{< glossary_tooltip text="Pods" term_id="pod" >}} at creation time. -This object chooses the pods to inject information into using standard selectors. This allows the podspec definitions to be nonspecific, decoupling the podspec from environment specific configuration. +This object chooses the Pods to inject information into using standard selectors. This allows the podspec definitions to be nonspecific, decoupling the podspec from environment specific configuration. diff --git a/content/en/docs/reference/glossary/preemption.md b/content/en/docs/reference/glossary/preemption.md index 0810acfcfc..f27e36c66f 100644 --- a/content/en/docs/reference/glossary/preemption.md +++ b/content/en/docs/reference/glossary/preemption.md @@ -10,7 +10,7 @@ aka: tags: - operation --- - Preemption logic in Kubernetes helps a pending Pod to find a suitable Node by evicting low priority Pods existing on that Node. + Preemption logic in Kubernetes helps a pending {{< glossary_tooltip term_id="pod" >}} to find a suitable {{< glossary_tooltip term_id="node" >}} by evicting low priority Pods existing on that Node. diff --git a/content/en/docs/reference/glossary/replication-controller.md b/content/en/docs/reference/glossary/replication-controller.md index b564c29691..9f4523e0f5 100755 --- a/content/en/docs/reference/glossary/replication-controller.md +++ b/content/en/docs/reference/glossary/replication-controller.md @@ -11,7 +11,7 @@ tags: - workload - core-object --- - Kubernetes service that ensures a specific number of instances of a pod are always running. + Kubernetes service that ensures a specific number of instances of a {{< glossary_tooltip text="Pod" term_id="pod" >}} are always running. diff --git a/content/en/docs/reference/glossary/security-context.md b/content/en/docs/reference/glossary/security-context.md index 9812304e4d..c53e96aa19 100755 --- a/content/en/docs/reference/glossary/security-context.md +++ b/content/en/docs/reference/glossary/security-context.md @@ -4,14 +4,20 @@ id: security-context date: 2018-04-12 full_link: /docs/tasks/configure-pod-container/security-context/ short_description: > - The securityContext field defines privilege and access control settings for a Pod or Container, including the runtime UID and GID. + The securityContext field defines privilege and access control settings for a Pod or container. aka: tags: - security --- - The securityContext field defines privilege and access control settings for a Pod or Container, including the runtime UID and GID. + The `securityContext` field defines privilege and access control settings for +a {{< glossary_tooltip text="Pod" term_id="pod" >}} or +{{< glossary_tooltip text="container" term_id="container" >}}. - + -The securityContext field in a {{< glossary_tooltip term_id="pod" >}} (applying to all containers) or container is used to set the user, groups, capabilities, privilege settings, and security policies (SELinux/AppArmor/Seccomp) and more that container processes use. +In a `securityContext`, you can define: the user that processes run as, +the group that processes run as, and privilege settings. +You can also configure security policies (for example: SELinux, AppArmor or seccomp). + +The `PodSpec.securityContext` setting applies to all containers in a Pod. diff --git a/content/en/docs/reference/glossary/selector.md b/content/en/docs/reference/glossary/selector.md index 9b8a020252..622b24694d 100755 --- a/content/en/docs/reference/glossary/selector.md +++ b/content/en/docs/reference/glossary/selector.md @@ -10,9 +10,9 @@ aka: tags: - fundamental --- - Allows users to filter a list of resources based on labels. + Allows users to filter a list of resources based on {{< glossary_tooltip text="labels" term_id="label" >}}. -Selectors are applied when querying lists of resources to filter them by {{< glossary_tooltip text="Labels" term_id="label" >}}. +Selectors are applied when querying lists of resources to filter them by labels. diff --git a/content/en/docs/reference/glossary/taint.md b/content/en/docs/reference/glossary/taint.md index 9faaee579b..c1aaaf5f65 100644 --- a/content/en/docs/reference/glossary/taint.md +++ b/content/en/docs/reference/glossary/taint.md @@ -11,8 +11,8 @@ tags: - core-object - fundamental --- - A core object consisting of three required properties: key, value, and effect. Taints prevent the scheduling of pods on nodes or node groups. + A core object consisting of three required properties: key, value, and effect. Taints prevent the scheduling of {{< glossary_tooltip text="Pods" term_id="pod" >}} on {{< glossary_tooltip text="nodes" term_id="node" >}} or node groups. -Taints and {{< glossary_tooltip text="tolerations" term_id="toleration" >}} work together to ensure that pods are not scheduled onto inappropriate nodes. One or more taints are applied to a {{< glossary_tooltip text="node" term_id="node" >}}. A node should only schedule a pod with the matching tolerations for the configured taints. +Taints and {{< glossary_tooltip text="tolerations" term_id="toleration" >}} work together to ensure that pods are not scheduled onto inappropriate nodes. One or more taints are applied to a node. A node should only schedule a Pod with the matching tolerations for the configured taints. diff --git a/content/en/docs/reference/glossary/volume.md b/content/en/docs/reference/glossary/volume.md index f162ce0010..2076378bb3 100755 --- a/content/en/docs/reference/glossary/volume.md +++ b/content/en/docs/reference/glossary/volume.md @@ -11,9 +11,10 @@ tags: - core-object - fundamental --- - A directory containing data, accessible to the containers in a {{< glossary_tooltip text="pod" term_id="pod" >}}. + A directory containing data, accessible to the {{< glossary_tooltip text="containers" term_id="container" >}} in a {{< glossary_tooltip term_id="pod" >}}. -A Kubernetes volume lives as long as the {{< glossary_tooltip text="pod" term_id="pod" >}} that encloses it. Consequently, a volume outlives any {{< glossary_tooltip text="containers" term_id="container" >}} that run within the {{< glossary_tooltip text="pod" term_id="pod" >}}, and data is preserved across {{< glossary_tooltip text="container" term_id="container" >}} restarts. +A Kubernetes volume lives as long as the Pod that encloses it. Consequently, a volume outlives any containers that run within the Pod, and data in the volume is preserved across container restarts. +See [storage](https://kubernetes.io/docs/concepts/storage/) for more information. diff --git a/content/en/docs/reference/kubectl/cheatsheet.md b/content/en/docs/reference/kubectl/cheatsheet.md index adb7fb8b6f..8401d00ecf 100644 --- a/content/en/docs/reference/kubectl/cheatsheet.md +++ b/content/en/docs/reference/kubectl/cheatsheet.md @@ -42,7 +42,7 @@ complete -F __start_kubectl k ```bash source <(kubectl completion zsh) # setup autocomplete in zsh into the current shell -echo "if [ $commands[kubectl] ]; then source <(kubectl completion zsh); fi" >> ~/.zshrc # add autocomplete permanently to your zsh shell +echo "[[ $commands[kubectl] ]] && source <(kubectl completion zsh)" >> ~/.zshrc # add autocomplete permanently to your zsh shell ``` ## Kubectl Context and Configuration @@ -95,7 +95,7 @@ kubectl apply -f ./my1.yaml -f ./my2.yaml # create from multiple files kubectl apply -f ./dir # create resource(s) in all manifest files in dir kubectl apply -f https://git.io/vPieo # create resource(s) from url kubectl create deployment nginx --image=nginx # start a single instance of nginx -kubectl explain pods,svc # get the documentation for pod and svc manifests +kubectl explain pods # get the documentation for pod manifests # Create multiple YAML objects from stdin cat <kubectl annotate (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags] | Add or update the annotations of one or more resources. `api-versions` | `kubectl api-versions [flags]` | List the API versions that are available. `apply` | `kubectl apply -f FILENAME [flags]`| Apply a configuration change to a resource from a file or stdin. `attach` | `kubectl attach POD -c CONTAINER [-i] [-t] [flags]` | Attach to a running container either to view the output stream or interact with the container (stdin). -`autoscale` | `kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]` | Automatically scale the set of pods that are managed by a replication controller. +`autoscale` | kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags] | Automatically scale the set of pods that are managed by a replication controller. `cluster-info` | `kubectl cluster-info [flags]` | Display endpoint information about the master and services in the cluster. `config` | `kubectl config SUBCOMMAND [flags]` | Modifies kubeconfig files. See the individual subcommands for details. `create` | `kubectl create -f FILENAME [flags]` | Create one or more resources from a file or stdin. -`delete` | `kubectl delete (-f FILENAME | TYPE [NAME | /NAME | -l label | --all]) [flags]` | Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources. -`describe` | `kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags]` | Display the detailed state of one or more resources. +`delete` | kubectl delete (-f FILENAME | TYPE [NAME | /NAME | -l label | --all]) [flags] | Delete resources either from a file, stdin, or specifying label selectors, names, resource selectors, or resources. +`describe` | kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags] | Display the detailed state of one or more resources. `diff` | `kubectl diff -f FILENAME [flags]`| Diff file or stdin against live configuration (**BETA**) -`edit` | `kubectl edit (-f FILENAME | TYPE NAME | TYPE/NAME) [flags]` | Edit and update the definition of one or more resources on the server by using the default editor. +`edit` | kubectl edit (-f FILENAME | TYPE NAME | TYPE/NAME) [flags] | Edit and update the definition of one or more resources on the server by using the default editor. `exec` | `kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]` | Execute a command against a container in a pod. `explain` | `kubectl explain [--recursive=false] [flags]` | Get documentation of various resources. For instance pods, nodes, services, etc. -`expose` | `kubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags]` | Expose a replication controller, service, or pod as a new Kubernetes service. -`get` | `kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags]` | List one or more resources. -`label` | `kubectl label (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]` | Add or update the labels of one or more resources. +`expose` | kubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags] | Expose a replication controller, service, or pod as a new Kubernetes service. +`get` | kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags] | List one or more resources. +`label` | kubectl label (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags] | Add or update the labels of one or more resources. `logs` | `kubectl logs POD [-c CONTAINER] [--follow] [flags]` | Print the logs for a container in a pod. -`patch` | `kubectl patch (-f FILENAME | TYPE NAME | TYPE/NAME) --patch PATCH [flags]` | Update one or more fields of a resource by using the strategic merge patch process. +`patch` | kubectl patch (-f FILENAME | TYPE NAME | TYPE/NAME) --patch PATCH [flags] | Update one or more fields of a resource by using the strategic merge patch process. `port-forward` | `kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]` | Forward one or more local ports to a pod. `proxy` | `kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]` | Run a proxy to the Kubernetes API server. `replace` | `kubectl replace -f FILENAME` | Replace a resource from a file or stdin. -`rolling-update` | `kubectl rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC) [flags]` | Perform a rolling update by gradually replacing the specified replication controller and its pods. +`rolling-update` | kubectl rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC) [flags] | Perform a rolling update by gradually replacing the specified replication controller and its pods. `run` | `kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [flags]` | Run a specified image on the cluster. -`scale` | `kubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags]` | Update the size of the specified replication controller. +`scale` | kubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags] | Update the size of the specified replication controller. `version` | `kubectl version [--client] [flags]` | Display the Kubernetes version running on the client and server. Remember: For more about command operations, see the [kubectl](/docs/user-guide/kubectl/) reference documentation. diff --git a/content/en/docs/reference/using-api/api-concepts.md b/content/en/docs/reference/using-api/api-concepts.md index 776715c8a2..8c7464d694 100644 --- a/content/en/docs/reference/using-api/api-concepts.md +++ b/content/en/docs/reference/using-api/api-concepts.md @@ -578,7 +578,7 @@ A number of markers were added in Kubernetes 1.16 and 1.17, to allow API develop | 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 | -| `//+listMapKeys` | `x-kubernetes-list-map-keys` | Slice of map keys that uniquely identify entries e.g. `["port", "protocol"]` | Only applicable when `+listType=map`. A slice of strings whose values in combination must uniquely identify list entries. | 1.16 | +| `//+listMapKeys` | `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. | 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 | diff --git a/content/en/docs/reference/using-api/api-overview.md b/content/en/docs/reference/using-api/api-overview.md index a004c86353..3820085e6b 100644 --- a/content/en/docs/reference/using-api/api-overview.md +++ b/content/en/docs/reference/using-api/api-overview.md @@ -91,12 +91,14 @@ The two paths that support extending the API with [custom resources](/docs/conce - [aggregator](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/api-machinery/aggregated-api-servers.md) for a full set of Kubernetes API semantics to implement their own apiserver. -## Enabling API groups +## Enabling or disabling API groups Certain resources and API groups are enabled by default. You can enable or disable them by setting `--runtime-config` on the apiserver. `--runtime-config` accepts comma separated values. For example: + - to disable batch/v1, set `--runtime-config=batch/v1=false` - to enable batch/v2alpha1, set `--runtime-config=batch/v2alpha1` + The flag accepts comma separated set of key=value pairs describing runtime configuration of the apiserver. {{< note >}} @@ -104,12 +106,10 @@ When you enable or disable groups or resources, you need to restart the apiserve to pick up the `--runtime-config` changes. {{< /note >}} -## Enabling resources in the groups - -DaemonSets, Deployments, HorizontalPodAutoscalers, Ingress, Jobs and ReplicaSets are enabled by default. -You can enable other extensions resources by setting `--runtime-config` on -apiserver. `--runtime-config` accepts comma separated values. For example, to disable deployments and jobs, set -`--runtime-config=extensions/v1beta1/deployments=false,extensions/v1beta1/jobs=false` -{{% /capture %}} +## Enabling specific resources in the extensions/v1beta1 group +DaemonSets, Deployments, StatefulSet, NetworkPolicies, PodSecurityPolicies and ReplicaSets in the `extensions/v1beta1` API group are disabled by default. +For example: to enable deployments and daemonsets, set +`--runtime-config=extensions/v1beta1/deployments=true,extensions/v1beta1/daemonsets=true`. +{{< note >}}Individual resource enablement/disablement is only supported in the `extensions/v1beta1` API group for legacy reasons.{{< /note >}} diff --git a/content/en/docs/reference/using-api/client-libraries.md b/content/en/docs/reference/using-api/client-libraries.md index 093490b345..4f76e16352 100644 --- a/content/en/docs/reference/using-api/client-libraries.md +++ b/content/en/docs/reference/using-api/client-libraries.md @@ -60,6 +60,7 @@ their authors, not the Kubernetes team. | PHP | [github.com/allansun/kubernetes-php-client](https://github.com/allansun/kubernetes-php-client) | | PHP | [github.com/travisghansen/kubernetes-client-php](https://github.com/travisghansen/kubernetes-client-php) | | Python | [github.com/eldarion-gondor/pykube](https://github.com/eldarion-gondor/pykube) | +| Python | [github.com/fiaas/k8s](https://github.com/fiaas/k8s) | | Python | [github.com/mnubo/kubernetes-py](https://github.com/mnubo/kubernetes-py) | | Python | [github.com/tomplus/kubernetes_asyncio](https://github.com/tomplus/kubernetes_asyncio) | | Ruby | [github.com/Ch00k/kuber](https://github.com/Ch00k/kuber) | diff --git a/content/en/docs/setup/_index.md b/content/en/docs/setup/_index.md index 6c903d4e60..880dd46024 100644 --- a/content/en/docs/setup/_index.md +++ b/content/en/docs/setup/_index.md @@ -24,7 +24,7 @@ This section covers different options to set up and run Kubernetes. Different Kubernetes solutions meet different requirements: ease of maintenance, security, control, available resources, and expertise required to operate and manage a cluster. -You can deploy a Kubernetes cluster on a local machine, cloud, on-prem datacenter; or choose a managed Kubernetes cluster. You can also create custom solutions across a wide range of cloud providers, or bare metal environments. +You can deploy a Kubernetes cluster on a local machine, cloud, on-prem datacenter, or choose a managed Kubernetes cluster. You can also create custom solutions across a wide range of cloud providers, or bare metal environments. More simply, you can create a Kubernetes cluster in learning and production environments. @@ -53,63 +53,6 @@ If you're learning Kubernetes, use the Docker-based solutions: tools supported b When evaluating a solution for a production environment, consider which aspects of operating a Kubernetes cluster (or _abstractions_) you want to manage yourself or offload to a provider. -Some possible abstractions of a Kubernetes cluster are {{< glossary_tooltip text="applications" term_id="applications" >}}, {{< glossary_tooltip text="data plane" term_id="data-plane" >}}, {{< glossary_tooltip text="control plane" term_id="control-plane" >}}, {{< glossary_tooltip text="cluster infrastructure" term_id="cluster-infrastructure" >}}, and {{< glossary_tooltip text="cluster operations" term_id="cluster-operations" >}}. - -The following diagram lists the possible abstractions of a Kubernetes cluster and whether an abstraction is self-managed or managed by a provider. - -Production environment solutions![Production environment solutions](/images/docs/KubernetesSolutions.svg) - -{{< table caption="Production environment solutions table lists the providers and the solutions." >}} -The following production environment solutions table lists the providers and the solutions that they offer. - -|Providers | Managed | Turnkey cloud | On-prem datacenter | Custom (cloud) | Custom (On-premises VMs)| Custom (Bare Metal) | -| --------- | ------ | ------ | ------ | ------ | ------ | ----- | -| [Agile Stacks](https://www.agilestacks.com/products/kubernetes)| | ✔ | ✔ | | | -| [Alibaba Cloud](https://www.alibabacloud.com/product/kubernetes)| | ✔ | | | | -| [Amazon](https://aws.amazon.com) | [Amazon EKS](https://aws.amazon.com/eks/) |[Amazon EC2](https://aws.amazon.com/ec2/) | | | | -| [AppsCode](https://appscode.com/products/pharmer/) | ✔ | | | | | -| [APPUiO](https://appuio.ch/)  | ✔ | ✔ | ✔ | | | | -| [Banzai Cloud Pipeline Kubernetes Engine (PKE)](https://banzaicloud.com/products/pke/) | | ✔ | | ✔ | ✔ | ✔ | -| [CenturyLink Cloud](https://www.ctl.io/) | | ✔ | | | | -| [Cisco Container Platform](https://cisco.com/go/containers) | | | ✔ | | | -| [Cloud Foundry Container Runtime (CFCR)](https://docs-cfcr.cfapps.io/) | | | | ✔ |✔ | -| [CloudStack](https://cloudstack.apache.org/) | | | | | ✔| -| [Canonical](https://ubuntu.com/kubernetes) | ✔ | ✔ | ✔ | ✔ |✔ | ✔ -| [Containership](https://containership.io) | ✔ |✔ | | | | -| [D2iQ](https://d2iq.com/) | | [Kommander](https://d2iq.com/solutions/ksphere) | [Konvoy](https://d2iq.com/solutions/ksphere/konvoy) | [Konvoy](https://d2iq.com/solutions/ksphere/konvoy) | [Konvoy](https://d2iq.com/solutions/ksphere/konvoy) | [Konvoy](https://d2iq.com/solutions/ksphere/konvoy) | -| [Digital Rebar](https://provision.readthedocs.io/en/tip/README.html) | | | | | | ✔ -| [DigitalOcean](https://www.digitalocean.com/products/kubernetes/) | ✔ | | | | | -| [Docker Enterprise](https://www.docker.com/products/docker-enterprise) | |✔ | ✔ | | | ✔ -| [Gardener](https://gardener.cloud/) | ✔ | ✔ | ✔ | ✔ | ✔ | [Custom Extensions](https://github.com/gardener/gardener/blob/master/docs/extensions/overview.md) | -| [Giant Swarm](https://www.giantswarm.io/) | ✔ | ✔ | ✔ | | -| [Google](https://cloud.google.com/) | [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine/) | [Google Compute Engine (GCE)](https://cloud.google.com/compute/)|[GKE On-Prem](https://cloud.google.com/gke-on-prem/) | | | | | | | | -| [Hidora](https://hidora.com/) | ✔ | ✔| ✔ | | | | | | | | -| [IBM](https://www.ibm.com/in-en/cloud) | [IBM Cloud Kubernetes Service](https://cloud.ibm.com/kubernetes/catalog/cluster)| |[IBM Cloud Private](https://www.ibm.com/in-en/cloud/private) | | -| [Ionos](https://www.ionos.com/enterprise-cloud) | [Ionos Managed Kubernetes](https://www.ionos.com/enterprise-cloud/managed-kubernetes) | [Ionos Enterprise Cloud](https://www.ionos.com/enterprise-cloud) | | -| [Kontena Pharos](https://www.kontena.io/pharos/) | |✔| ✔ | | | -| [KubeOne](https://kubeone.io/) | | ✔ | ✔ | ✔ | ✔ | ✔ | -| [Kubermatic](https://kubermatic.io/) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | -| [KubeSail](https://kubesail.com/) | ✔ | | | | | -| [Kubespray](https://kubespray.io/#/) | | | |✔ | ✔ | ✔ | -| [Kublr](https://kublr.com/) |✔ | ✔ |✔ |✔ |✔ |✔ | -| [Microsoft Azure](https://azure.microsoft.com) | [Azure Kubernetes Service (AKS)](https://azure.microsoft.com/en-us/services/kubernetes-service/) | | | | | -| [Mirantis Cloud Platform](https://www.mirantis.com/software/kubernetes/) | | | ✔ | | | -| [NetApp Kubernetes Service (NKS)](https://cloud.netapp.com/kubernetes-service) | ✔ | ✔ | ✔ | | | -| [Nirmata](https://www.nirmata.com/) | | ✔ | ✔ | | | -| [Nutanix](https://www.nutanix.com/en) | [Nutanix Karbon](https://www.nutanix.com/products/karbon) | [Nutanix Karbon](https://www.nutanix.com/products/karbon) | | | [Nutanix AHV](https://www.nutanix.com/products/acropolis/virtualization) | -| [OpenNebula](https://www.opennebula.org) |[OpenNebula Kubernetes](https://marketplace.opennebula.systems/docs/service/kubernetes.html) | | | | | -| [OpenShift](https://www.openshift.com) |[OpenShift Dedicated](https://www.openshift.com/products/dedicated/) and [OpenShift Online](https://www.openshift.com/products/online/) | | [OpenShift Container Platform](https://www.openshift.com/products/container-platform/) | | [OpenShift Container Platform](https://www.openshift.com/products/container-platform/) |[OpenShift Container Platform](https://www.openshift.com/products/container-platform/) -| [Oracle Cloud Infrastructure Container Engine for Kubernetes (OKE)](https://docs.cloud.oracle.com/iaas/Content/ContEng/Concepts/contengoverview.htm) | ✔ | ✔ | | | | -| [oVirt](https://www.ovirt.org/) | | | | | ✔ | -| [Pivotal](https://pivotal.io/) | | [Enterprise Pivotal Container Service (PKS)](https://pivotal.io/platform/pivotal-container-service) | [Enterprise Pivotal Container Service (PKS)](https://pivotal.io/platform/pivotal-container-service) | | | -| [Platform9](https://platform9.com/) | [Platform9 Managed Kubernetes](https://platform9.com/managed-kubernetes/) | | [Platform9 Managed Kubernetes](https://platform9.com/managed-kubernetes/) | ✔ | ✔ | ✔ -| [Rancher](https://rancher.com/) | | [Rancher 2.x](https://rancher.com/docs/rancher/v2.x/en/) | | [Rancher Kubernetes Engine (RKE)](https://rancher.com/docs/rke/latest/en/) | | [k3s](https://k3s.io/) -| [Supergiant](https://supergiant.io/) | |✔ | | | | -| [SUSE](https://www.suse.com/) | | ✔ | | | | -| [SysEleven](https://www.syseleven.io/) | ✔ | | | | | -| [Tencent Cloud](https://intl.cloud.tencent.com/) | [Tencent Kubernetes Engine](https://intl.cloud.tencent.com/product/tke) | ✔ | ✔ | | | ✔ | -| [VEXXHOST](https://vexxhost.com/) | ✔ | ✔ | | | | -| [VMware](https://cloud.vmware.com/) | [VMware Cloud PKS](https://cloud.vmware.com/vmware-cloud-pks) |[VMware Enterprise PKS](https://cloud.vmware.com/vmware-enterprise-pks) | [VMware Enterprise PKS](https://cloud.vmware.com/vmware-enterprise-pks) | [VMware Essential PKS](https://cloud.vmware.com/vmware-essential-pks) | |[VMware Essential PKS](https://cloud.vmware.com/vmware-essential-pks) -| [Z.A.R.V.I.S.](https://zarvis.ai/) | ✔ | | | | | | +For a list of [Certified Kubernetes](https://github.com/cncf/k8s-conformance/#certified-kubernetes) providers, see "[Partners](https://kubernetes.io/partners/#conformance)". {{% /capture %}} diff --git a/content/en/docs/setup/best-practices/multiple-zones.md b/content/en/docs/setup/best-practices/multiple-zones.md index b01cbceedf..ba58df028f 100644 --- a/content/en/docs/setup/best-practices/multiple-zones.md +++ b/content/en/docs/setup/best-practices/multiple-zones.md @@ -188,7 +188,7 @@ kubernetes-minion-wf8i Ready 2m v1.13.0 Create a volume using the dynamic volume creation (only PersistentVolumes are supported for zone affinity): -```json +```bash kubectl apply -f - < /etc/sysctl.d/k8s.conf +net.bridge.bridge-nf-call-ip6tables = 1 +net.bridge.bridge-nf-call-iptables = 1 +EOF +sysctl --system +``` + +Make sure that the `br_netfilter` module is loaded before this step. This can be done by running `lsmod | grep br_netfilter`. To load it explicitly call `modprobe br_netfilter`. + +For more details please see the [Network Plugin Requirements](https://kubernetes.io/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/#network-plugin-requirements) page. + + ## Ensure iptables tooling does not use the nftables backend In Linux, nftables is available as a modern replacement for the kernel's iptables subsystem. The @@ -230,17 +247,7 @@ systemctl enable --now kubelet - Setting SELinux in permissive mode by running `setenforce 0` and `sed ...` effectively disables it. This is required to allow containers to access the host filesystem, which is needed by pod networks for example. You have to do this until SELinux support is improved in the kubelet. - - Some users on RHEL/CentOS 7 have reported issues with traffic being routed incorrectly due to iptables being bypassed. You should ensure - `net.bridge.bridge-nf-call-iptables` is set to 1 in your `sysctl` config, e.g. - - ```bash - cat < /etc/sysctl.d/k8s.conf - net.bridge.bridge-nf-call-ip6tables = 1 - net.bridge.bridge-nf-call-iptables = 1 - EOF - sysctl --system - ``` - - Make sure that the `br_netfilter` module is loaded before this step. This can be done by running `lsmod | grep br_netfilter`. To load it explicitly call `modprobe br_netfilter`. + {{% /tab %}} {{% tab name="Container Linux" %}} Install CNI plugins (required for most pod network): diff --git a/content/en/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md b/content/en/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md index 31f94ef137..c0c1e2b0b2 100644 --- a/content/en/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md +++ b/content/en/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md @@ -307,17 +307,17 @@ The tracking issue for this problem is [here](https://github.com/kubernetes/kube *Note: This [issue](https://github.com/kubernetes/kubeadm/issues/1358) only applies to tools that marshal kubeadm types (e.g. to a YAML configuration file). It will be fixed in kubeadm API v1beta2.* -By default, kubeadm applies the `role.kubernetes.io/master:NoSchedule` taint to control-plane nodes. +By default, kubeadm applies the `node-role.kubernetes.io/master:NoSchedule` taint to control-plane nodes. If you prefer kubeadm to not taint the control-plane node, and set `InitConfiguration.NodeRegistration.Taints` to an empty slice, the field will be omitted when marshalling. When the field is omitted, kubeadm applies the default taint. There are at least two workarounds: -1. Use the `role.kubernetes.io/master:PreferNoSchedule` taint instead of an empty slice. [Pods will get scheduled on masters](/docs/concepts/configuration/taint-and-toleration/), unless other nodes have capacity. +1. Use the `node-role.kubernetes.io/master:PreferNoSchedule` taint instead of an empty slice. [Pods will get scheduled on masters](/docs/concepts/configuration/taint-and-toleration/), unless other nodes have capacity. 2. Remove the taint after kubeadm init exits: ```bash -kubectl taint nodes NODE_NAME role.kubernetes.io/master:NoSchedule- +kubectl taint nodes NODE_NAME node-role.kubernetes.io/master:NoSchedule- ``` ## `/usr` is mounted read-only on nodes {#usr-mounted-read-only} diff --git a/content/en/docs/setup/production-environment/windows/user-guide-windows-containers.md b/content/en/docs/setup/production-environment/windows/user-guide-windows-containers.md index 2366f61018..a4f177b364 100644 --- a/content/en/docs/setup/production-environment/windows/user-guide-windows-containers.md +++ b/content/en/docs/setup/production-environment/windows/user-guide-windows-containers.md @@ -107,6 +107,14 @@ Port mapping is also supported, but for simplicity in this example the container Windows container hosts are not able to access the IP of services scheduled on them due to current platform limitations of the Windows networking stack. Only Windows pods are able to access service IPs. {{< /note >}} +## Observability + +### Capturing logs from workloads + +Logs are an important element of observability; they enable users to gain insights into the operational aspect of workloads and are a key ingredient to troubleshooting issues. Because Windows containers and workloads inside Windows containers behave differently from Linux containers, users had a hard time collecting logs, limiting operational visibility. Windows workloads for example are usually configured to log to ETW (Event Tracing for Windows) or push entries to the application event log. [LogMonitor](https://github.com/microsoft/windows-container-tools/tree/master/LogMonitor), an open source tool by Microsoft, is the recommended way to monitor configured log sources inside a Windows container. LogMonitor supports monitoring event logs, ETW providers, and custom application logs, piping them to STDOUT for consumption by `kubectl logs `. + +Follow the instructions in the LogMonitor GitHub page to copy its binaries and configuration files to all your containers and add the necessary entrypoints for LogMonitor to push your logs to STDOUT. + ## Using configurable Container usernames Starting with Kubernetes v1.16, Windows containers can be configured to run their entrypoints and processes with different usernames than the image defaults. The way this is achieved is a bit different from the way it is done for Linux containers. Learn more about it [here](/docs/tasks/configure-pod-container/configure-runasusername/). diff --git a/content/en/docs/tasks/access-application-cluster/connecting-frontend-backend.md b/content/en/docs/tasks/access-application-cluster/connecting-frontend-backend.md index 3cb90383c7..123271be44 100644 --- a/content/en/docs/tasks/access-application-cluster/connecting-frontend-backend.md +++ b/content/en/docs/tasks/access-application-cluster/connecting-frontend-backend.md @@ -39,7 +39,7 @@ frontend and backend are connected using a Kubernetes {{% capture lessoncontent %}} -### Creating the backend using a Deployment +## Creating the backend using a Deployment The backend is a simple hello greeter microservice. Here is the configuration file for the backend Deployment: @@ -95,7 +95,7 @@ Events: ... ``` -### Creating the backend Service object +## Creating the backend Service object The key to connecting a frontend to a backend is the backend Service. A Service creates a persistent IP address and DNS name entry @@ -119,7 +119,7 @@ kubectl apply -f https://k8s.io/examples/service/access/hello-service.yaml At this point, you have a backend Deployment running, and you have a Service that can route traffic to it. -### Creating the frontend +## Creating the frontend Now that you have your backend, you can create a frontend that connects to the backend. The frontend connects to the backend worker Pods by using the DNS name @@ -158,7 +158,7 @@ be to use a so that you can change the configuration more easily. {{< /note >}} -### Interact with the frontend Service +## Interact with the frontend Service Once you’ve created a Service of type LoadBalancer, you can use this command to find the external IP: @@ -186,7 +186,7 @@ frontend LoadBalancer 10.51.252.116 XXX.XXX.XXX.XXX 80/TCP 1m That IP can now be used to interact with the `frontend` service from outside the cluster. -### Send traffic through the frontend +## Send traffic through the frontend The frontend and backends are now connected. You can hit the endpoint by using the curl command on the external IP of your frontend Service. diff --git a/content/en/docs/tasks/access-application-cluster/list-all-running-container-images.md b/content/en/docs/tasks/access-application-cluster/list-all-running-container-images.md index caf20d7f2e..b3fb886d11 100644 --- a/content/en/docs/tasks/access-application-cluster/list-all-running-container-images.md +++ b/content/en/docs/tasks/access-application-cluster/list-all-running-container-images.md @@ -23,7 +23,7 @@ In this exercise you will use kubectl to fetch all of the Pods running in a cluster, and format the output to pull out the list of Containers for each. -## List all Containers in all namespaces +## List all Container images in all namespaces - Fetch all Pods in all namespaces using `kubectl get pods --all-namespaces` - Format the output to include only the list of Container image names @@ -63,12 +63,12 @@ The jsonpath is interpreted as follows: - `.image`: get the image {{< note >}} -When fetching a single Pod by name, e.g. `kubectl get pod nginx`, +When fetching a single Pod by name, for example `kubectl get pod nginx`, the `.items[*]` portion of the path should be omitted because a single Pod is returned instead of a list of items. {{< /note >}} -## List Containers by Pod +## List Container images by Pod The formatting can be controlled further by using the `range` operation to iterate over elements individually. @@ -78,7 +78,7 @@ kubectl get pods --all-namespaces -o=jsonpath='{range .items[*]}{"\n"}{.metadata sort ``` -## List Containers filtering by Pod label +## List Container images filtering by Pod label To target only Pods matching a specific label, use the -l flag. The following matches only Pods with labels matching `app=nginx`. @@ -87,7 +87,7 @@ following matches only Pods with labels matching `app=nginx`. kubectl get pods --all-namespaces -o=jsonpath="{..image}" -l app=nginx ``` -## List Containers filtering by Pod namespace +## List Container images filtering by Pod namespace To target only pods in a specific namespace, use the namespace flag. The following matches only Pods in the `kube-system` namespace. @@ -96,7 +96,7 @@ following matches only Pods in the `kube-system` namespace. kubectl get pods --namespace kube-system -o jsonpath="{..image}" ``` -## List Containers using a go-template instead of jsonpath +## List Container images using a go-template instead of jsonpath As an alternative to jsonpath, Kubectl supports using [go-templates](https://golang.org/pkg/text/template/) for formatting the output: diff --git a/content/en/docs/tasks/access-application-cluster/port-forward-access-application-cluster.md b/content/en/docs/tasks/access-application-cluster/port-forward-access-application-cluster.md index 4a3b201ff3..fc24022d0c 100644 --- a/content/en/docs/tasks/access-application-cluster/port-forward-access-application-cluster.md +++ b/content/en/docs/tasks/access-application-cluster/port-forward-access-application-cluster.md @@ -2,6 +2,7 @@ title: Use Port Forwarding to Access Applications in a Cluster content_template: templates/task weight: 40 +min-kubernetes-server-version: v1.10 --- {{% capture overview %}} @@ -26,104 +27,157 @@ for database debugging. ## Creating Redis deployment and service -1. Create a Redis deployment: +1. Create a Deployment that runs Redis: - kubectl apply -f https://k8s.io/examples/application/guestbook/redis-master-deployment.yaml + ```shell + kubectl apply -f https://k8s.io/examples/application/guestbook/redis-master-deployment.yaml + ``` The output of a successful command verifies that the deployment was created: - deployment.apps/redis-master created + ``` + deployment.apps/redis-master created + ``` View the pod status to check that it is ready: - kubectl get pods + ```shell + kubectl get pods + ``` The output displays the pod created: - NAME READY STATUS RESTARTS AGE - redis-master-765d459796-258hz 1/1 Running 0 50s + ``` + NAME READY STATUS RESTARTS AGE + redis-master-765d459796-258hz 1/1 Running 0 50s + ``` - View the deployment status: + View the Deployment's status: - kubectl get deployment + ```shell + kubectl get deployment + ``` - The output displays that the deployment was created: + The output displays that the Deployment was created: - NAME READY UP-TO-DATE AVAILABLE AGE - redis-master 1/1 1 1 55s + ``` + NAME READY UP-TO-DATE AVAILABLE AGE + redis-master 1/1 1 1 55s + ``` - View the replicaset status using: + The Deployment automatically manages a ReplicaSet. + View the ReplicaSet status using: - kubectl get rs + ```shell + kubectl get replicaset + ``` - The output displays that the replicaset was created: + The output displays that the ReplicaSet was created: - NAME DESIRED CURRENT READY AGE - redis-master-765d459796 1 1 1 1m + ``` + NAME DESIRED CURRENT READY AGE + redis-master-765d459796 1 1 1 1m + ``` -2. Create a Redis service: +2. Create a Service to expose Redis on the network: - kubectl apply -f https://k8s.io/examples/application/guestbook/redis-master-service.yaml + ```shell + kubectl apply -f https://k8s.io/examples/application/guestbook/redis-master-service.yaml + ``` - The output of a successful command verifies that the service was created: + The output of a successful command verifies that the Service was created: - service/redis-master created + ``` + service/redis-master created + ``` - Check the service created: + Check the Service created: - kubectl get svc | grep redis + ```shell + kubectl get service redis-master + ``` The output displays the service created: - NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE - redis-master ClusterIP 10.0.0.213 6379/TCP 27s + ``` + NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE + redis-master ClusterIP 10.0.0.213 6379/TCP 27s + ``` -3. Verify that the Redis server is running in the pod and listening on port 6379: +3. Verify that the Redis server is running in the Pod, and listening on port 6379: - kubectl get pods redis-master-765d459796-258hz --template='{{(index (index .spec.containers 0).ports 0).containerPort}}{{"\n"}}' + ```shell + # Change redis-master-765d459796-258hz to the name of the Pod + kubectl get pod redis-master-765d459796-258hz --template='{{(index (index .spec.containers 0).ports 0).containerPort}}{{"\n"}}' + ``` - The output displays the port: + The output displays the port for Redis in that Pod: - 6379 + ``` + 6379 + ``` + + (this is the TCP port allocated to Redis on the internet). + +## Forward a local port to a port on the Pod + +1. `kubectl port-forward` allows using resource name, such as a pod name, to select a matching pod to port forward to. -## Forward a local port to a port on the pod - -1. `kubectl port-forward` allows using resource name, such as a pod name, to select a matching pod to port forward to since Kubernetes v1.10. - - kubectl port-forward redis-master-765d459796-258hz 7000:6379 + ```shell + # Change redis-master-765d459796-258hz to the name of the Pod + kubectl port-forward redis-master-765d459796-258hz 7000:6379 + ``` which is the same as - kubectl port-forward pods/redis-master-765d459796-258hz 7000:6379 + ```shell + kubectl port-forward pods/redis-master-765d459796-258hz 7000:6379 + ``` or - kubectl port-forward deployment/redis-master 7000:6379 + ```shell + kubectl port-forward deployment/redis-master 7000:6379 + ``` or - kubectl port-forward rs/redis-master 7000:6379 + ```shell + kubectl port-forward replicaset/redis-master 7000:6379 + ``` or - kubectl port-forward svc/redis-master 7000:6379 + ```shell + kubectl port-forward service/redis-master 7000:6379 + ``` Any of the above commands works. The output is similar to this: - I0710 14:43:38.274550 3655 portforward.go:225] Forwarding from 127.0.0.1:7000 -> 6379 - I0710 14:43:38.274797 3655 portforward.go:225] Forwarding from [::1]:7000 -> 6379 + ``` + I0710 14:43:38.274550 3655 portforward.go:225] Forwarding from 127.0.0.1:7000 -> 6379 + I0710 14:43:38.274797 3655 portforward.go:225] Forwarding from [::1]:7000 -> 6379 + ``` 2. Start the Redis command line interface: - redis-cli -p 7000 + ```shell + redis-cli -p 7000 + ``` 3. At the Redis command line prompt, enter the `ping` command: - 127.0.0.1:7000>ping + ``` + ping + ``` - A successful ping request returns PONG. + A successful ping request returns: + + ``` + PONG + ``` {{% /capture %}} @@ -132,15 +186,15 @@ for database debugging. ## Discussion -Connections made to local port 7000 are forwarded to port 6379 of the pod that -is running the Redis server. With this connection in place you can use your -local workstation to debug the database that is running in the pod. +Connections made to local port 7000 are forwarded to port 6379 of the Pod that +is running the Redis server. With this connection in place, you can use your +local workstation to debug the database that is running in the Pod. -{{< warning >}} -Due to known limitations, port forward today only works for TCP protocol. -The support to UDP protocol is being tracked in +{{< note >}} +`kubectl port-forward` is implemented for TCP ports only. +The support for UDP protocol is tracked in [issue 47862](https://github.com/kubernetes/kubernetes/issues/47862). -{{< /warning >}} +{{< /note >}} {{% /capture %}} @@ -148,6 +202,3 @@ The support to UDP protocol is being tracked in {{% capture whatsnext %}} Learn more about [kubectl port-forward](/docs/reference/generated/kubectl/kubectl-commands/#port-forward). {{% /capture %}} - - - diff --git a/content/en/docs/tasks/access-application-cluster/web-ui-dashboard.md b/content/en/docs/tasks/access-application-cluster/web-ui-dashboard.md index 9b5e997782..ecda7709cf 100644 --- a/content/en/docs/tasks/access-application-cluster/web-ui-dashboard.md +++ b/content/en/docs/tasks/access-application-cluster/web-ui-dashboard.md @@ -113,7 +113,7 @@ track=stable - **Image Pull Secret**: In case the specified Docker container image is private, it may require [pull secret](/docs/concepts/configuration/secret/) credentials. - Dashboard offers all available secrets in a dropdown list, and allows you to create a new secret. The secret name must follow the DNS domain name syntax, e.g. `new.image-pull.secret`. The content of a secret must be base64-encoded and specified in a [`.dockercfg`](/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod) file. The secret name may consist of a maximum of 253 characters. + Dashboard offers all available secrets in a dropdown list, and allows you to create a new secret. The secret name must follow the DNS domain name syntax, for example `new.image-pull.secret`. The content of a secret must be base64-encoded and specified in a [`.dockercfg`](/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod) file. The secret name may consist of a maximum of 253 characters. In case the creation of the image pull secret is successful, it is selected by default. If the creation fails, no secret is applied. diff --git a/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definition-versioning.md b/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definition-versioning.md index f730fb3660..184e870fc3 100644 --- a/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definition-versioning.md +++ b/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definition-versioning.md @@ -502,7 +502,7 @@ to turn up in a new cluster. The scheme must be "https"; the URL must begin with "https://". -Attempting to use a user or basic auth e.g. "user:password@" is not allowed. +Attempting to use a user or basic auth (for example "user:password@") is not allowed. Fragments ("#...") and query parameters ("?...") are also not allowed. Here is an example of a conversion webhook configured to call a URL diff --git a/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions.md b/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions.md index b2d5703b1c..dd96f2d6d6 100644 --- a/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions.md +++ b/content/en/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions.md @@ -366,7 +366,7 @@ Structural schemas are a requirement for `apiextensions.k8s.io/v1`, and disables {{< feature-state state="stable" for_kubernetes_version="1.16" >}} -CustomResourceDefinitions traditionally store any (possibly validated) JSON as is in etcd. This means that unspecified fields (if there is a [OpenAPI v3.0 validation schema](/docs/tasks/access-kubernetes-api/extend-api-custom-resource-definitions/#validation) at all) are persisted. This is in contrast to native Kubernetes resources like e.g. a pod where unknown fields are dropped before being persisted to etcd. We call this "pruning" of unknown fields. +CustomResourceDefinitions traditionally store any (possibly validated) JSON as is in etcd. This means that unspecified fields (if there is a [OpenAPI v3.0 validation schema](/docs/tasks/access-kubernetes-api/extend-api-custom-resource-definitions/#validation) at all) are persisted. This is in contrast to native Kubernetes resources such as a pod where unknown fields are dropped before being persisted to etcd. We call this "pruning" of unknown fields. {{< tabs name="CustomResourceDefinition_pruning" >}} {{% tab name="apiextensions.k8s.io/v1" %}} diff --git a/content/en/docs/tasks/administer-cluster/change-default-storage-class.md b/content/en/docs/tasks/administer-cluster/change-default-storage-class.md index 4c3351956d..a2070bcfe3 100644 --- a/content/en/docs/tasks/administer-cluster/change-default-storage-class.md +++ b/content/en/docs/tasks/administer-cluster/change-default-storage-class.md @@ -62,10 +62,10 @@ for details about addon manager and how to disable individual addons. To mark a StorageClass as non-default, you need to change its value to `false`: ```bash - kubectl patch storageclass -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}' + kubectl patch storageclass standard -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}' ``` - where `` is the name of your chosen StorageClass. + where `standard` is the name of your chosen StorageClass. 1. Mark a StorageClass as default: @@ -73,7 +73,7 @@ for details about addon manager and how to disable individual addons. `storageclass.kubernetes.io/is-default-class=true`. ```bash - kubectl patch storageclass -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' + kubectl patch storageclass gold -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}' ``` Please note that at most one StorageClass can be marked as default. If two diff --git a/content/en/docs/tasks/administer-cluster/cluster-management.md b/content/en/docs/tasks/administer-cluster/cluster-management.md index bceb4fef96..65728ec4ee 100644 --- a/content/en/docs/tasks/administer-cluster/cluster-management.md +++ b/content/en/docs/tasks/administer-cluster/cluster-management.md @@ -24,7 +24,7 @@ To install Kubernetes on a set of machines, consult one of the existing [Getting ## Upgrading a cluster -The current state of cluster upgrades is provider dependent, and some releases may require special care when upgrading. It is recommended that administrators consult both the [release notes](https://git.k8s.io/kubernetes/CHANGELOG.md), as well as the version specific upgrade notes prior to upgrading their clusters. +The current state of cluster upgrades is provider dependent, and some releases may require special care when upgrading. It is recommended that administrators consult both the [release notes](https://git.k8s.io/kubernetes/CHANGELOG/README.md), as well as the version specific upgrade notes prior to upgrading their clusters. ### Upgrading an Azure Kubernetes Service (AKS) cluster diff --git a/content/en/docs/tasks/administer-cluster/declare-network-policy.md b/content/en/docs/tasks/administer-cluster/declare-network-policy.md index edb389c46f..0fdbff57b8 100644 --- a/content/en/docs/tasks/administer-cluster/declare-network-policy.md +++ b/content/en/docs/tasks/administer-cluster/declare-network-policy.md @@ -90,10 +90,11 @@ To limit the access to the `nginx` service so that only Pods with the label `acc {{< codenew file="service/networking/nginx-policy.yaml" >}} +The name of a NetworkPolicy object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + {{< note >}} - NetworkPolicy includes a `podSelector` which selects the grouping of Pods to which the policy applies. You can see this policy selects Pods with the label `app=nginx`. The label was automatically added to the Pod in the `nginx` Deployment. An empty `podSelector` selects all pods in the namespace. - {{< /note >}} ## Assign the policy to the service diff --git a/content/en/docs/tasks/administer-cluster/dns-debugging-resolution.md b/content/en/docs/tasks/administer-cluster/dns-debugging-resolution.md index 352a709386..8c494935b6 100644 --- a/content/en/docs/tasks/administer-cluster/dns-debugging-resolution.md +++ b/content/en/docs/tasks/administer-cluster/dns-debugging-resolution.md @@ -265,15 +265,6 @@ work properly owing to a known issue with Alpine. Check [here](https://github.com/kubernetes/kubernetes/issues/30215) for more information. -## Kubernetes Federation (Multiple Zone support) - -Release 1.3 introduced Cluster Federation support for multi-site Kubernetes -installations. This required some minor (backward-compatible) changes to the -way the Kubernetes cluster DNS server processes DNS queries, to facilitate -the lookup of federated services (which span multiple Kubernetes clusters). -See the [Cluster Federation Administrators' Guide](/docs/concepts/cluster-administration/federation/) -for more details on Cluster Federation and multi-site support. - ## References - [DNS for Services and Pods](/docs/concepts/services-networking/dns-pod-service/) diff --git a/content/en/docs/tasks/administer-cluster/ip-masq-agent.md b/content/en/docs/tasks/administer-cluster/ip-masq-agent.md index 3cce9c7153..bdc871ddd9 100644 --- a/content/en/docs/tasks/administer-cluster/ip-masq-agent.md +++ b/content/en/docs/tasks/administer-cluster/ip-masq-agent.md @@ -37,7 +37,7 @@ The agent configuration file must be written in YAML or JSON syntax, and may con * **nonMasqueradeCIDRs:** A list of strings in [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation that specify the non-masquerade ranges. * **masqLinkLocal:** A Boolean (true / false) which indicates whether to masquerade traffic to the link local prefix 169.254.0.0/16. False by default. -* **resyncInterval:** An interval at which the agent attempts to reload config from disk. e.g. '30s' where 's' is seconds, 'ms' is milliseconds etc... +* **resyncInterval:** A time interval at which the agent attempts to reload config from disk. For example: '30s', where 's' means seconds, 'ms' means milliseconds, etc... Traffic to 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16) ranges will NOT be masqueraded. Any other traffic (assumed to be internet) will be masqueraded. An example of a local destination from a pod could be its Node's IP address as well as another node's address or one of the IP addresses in Cluster's IP range. Any other traffic will be masqueraded by default. The below entries show the default set of rules that are applied by the ip-masq-agent: diff --git a/content/en/docs/tasks/administer-cluster/namespaces-walkthrough.md b/content/en/docs/tasks/administer-cluster/namespaces-walkthrough.md index bd136e3ae2..9a69058ceb 100644 --- a/content/en/docs/tasks/administer-cluster/namespaces-walkthrough.md +++ b/content/en/docs/tasks/administer-cluster/namespaces-walkthrough.md @@ -224,12 +224,14 @@ At this point, all requests we make to the Kubernetes cluster from the command l Let's create some contents. +{{< codenew file="admin/snowflake-deployment.yaml" >}} + +Apply the manifest to create a Deployment + ```shell -kubectl run snowflake --image=k8s.gcr.io/serve_hostname --replicas=2 +kubectl apply -f https://k8s.io/examples/admin/snowflake-deployment.yaml ``` 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 diff --git a/content/en/docs/tasks/administer-cluster/namespaces.md b/content/en/docs/tasks/administer-cluster/namespaces.md index ef12b24c98..de2230a6a4 100644 --- a/content/en/docs/tasks/administer-cluster/namespaces.md +++ b/content/en/docs/tasks/administer-cluster/namespaces.md @@ -101,7 +101,8 @@ See the [design doc](https://git.k8s.io/community/contributors/design-proposals/ kubectl create namespace ``` -Note that the name of your namespace must be a DNS compatible label. +The name of your namespace must be a valid +[DNS label](/docs/concepts/overview/working-with-objects/names#dns-label-names). There's an optional field `finalizers`, which allows observables to purge resources whenever the namespace is deleted. Keep in mind that if you specify a nonexistent finalizer, the namespace will be created but will get stuck in the `Terminating` state if the user tries to delete it. @@ -187,88 +188,22 @@ This delete is asynchronous, so for a time you will see the namespace in the `Te To demonstrate this, let's spin up a simple Deployment and Pods in the `development` namespace. - We first check what is the current context: - ```shell - kubectl config view - ``` - ```yaml - apiVersion: v1 - clusters: - cluster: - certificate-authority-data: REDACTED - server: https://130.211.122.180 - name: lithe-cocoa-92103_kubernetes - contexts: - context: - cluster: lithe-cocoa-92103_kubernetes - user: lithe-cocoa-92103_kubernetes - name: lithe-cocoa-92103_kubernetes - current-context: lithe-cocoa-92103_kubernetes - kind: Config - preferences: {} - users: - name: lithe-cocoa-92103_kubernetes - user: - client-certificate-data: REDACTED - client-key-data: REDACTED - token: 65rZW78y8HbwXXtSXuUw9DbP4FLjHi4b - name: lithe-cocoa-92103_kubernetes-basic-auth - user: - password: h5M0FtUUIflBSdI7 - username: admin - ``` - - ```shell - kubectl config current-context - ``` - ``` - lithe-cocoa-92103_kubernetes - ``` - - The next step is to define a context for the kubectl client to work in each namespace. The values of "cluster" and "user" fields are copied from the current context. - - ```shell - kubectl config set-context dev --namespace=development --cluster=lithe-cocoa-92103_kubernetes --user=lithe-cocoa-92103_kubernetes - kubectl config set-context prod --namespace=production --cluster=lithe-cocoa-92103_kubernetes --user=lithe-cocoa-92103_kubernetes - ``` - - The above commands provided two request contexts you can alternate against depending on what namespace you - wish to work against. - - Let's switch to operate in the `development` namespace. - - ```shell - kubectl config use-context dev - ``` - - You can verify your current context by doing the following: - - ```shell - kubectl config current-context - dev - ``` - - At this point, all requests we make to the Kubernetes cluster from the command line are scoped to the `development` namespace. - - Let's create some contents. - - ```shell - kubectl run snowflake --image=k8s.gcr.io/serve_hostname --replicas=2 + kubectl run snowflake --image=k8s.gcr.io/serve_hostname --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 + kubectl get deployment -n=development ``` ``` NAME READY UP-TO-DATE AVAILABLE AGE snowflake 2/2 2 2 2m ``` ```shell - kubectl get pods -l run=snowflake + kubectl get pods -l run=snowflake -n=development ``` ``` NAME READY STATUS RESTARTS AGE @@ -280,23 +215,19 @@ This delete is asynchronous, so for a time you will see the namespace in the `Te Let's switch to the `production` namespace and show how resources in one namespace are hidden from the other. - ```shell - kubectl config use-context prod - ``` - The `production` namespace should be empty, and the following commands should return nothing. ```shell - kubectl get deployment - kubectl get pods + kubectl get deployment -n=production + kubectl get pods -n=production ``` Production likes to run cattle, so let's create some cattle pods. ```shell - kubectl run cattle --image=k8s.gcr.io/serve_hostname --replicas=5 + kubectl run cattle --image=k8s.gcr.io/serve_hostname --replicas=5 -n=production - kubectl get deployment + kubectl get deployment -n=production ``` ``` NAME READY UP-TO-DATE AVAILABLE AGE @@ -304,7 +235,7 @@ This delete is asynchronous, so for a time you will see the namespace in the `Te ``` ```shell - kubectl get pods -l run=cattle + kubectl get pods -l run=cattle -n=production ``` ``` NAME READY STATUS RESTARTS AGE diff --git a/content/en/docs/tasks/administer-cluster/nodelocaldns.md b/content/en/docs/tasks/administer-cluster/nodelocaldns.md index 7d15596112..f23525e377 100644 --- a/content/en/docs/tasks/administer-cluster/nodelocaldns.md +++ b/content/en/docs/tasks/administer-cluster/nodelocaldns.md @@ -2,6 +2,7 @@ reviewers: - bowei - zihongz +- sftim title: Using NodeLocal DNSCache in Kubernetes clusters content_template: templates/task --- @@ -47,18 +48,44 @@ This is the path followed by DNS Queries after NodeLocal DNSCache is enabled: {{< figure src="/images/docs/nodelocaldns.jpg" alt="NodeLocal DNSCache flow" title="Nodelocal DNSCache flow" caption="This image shows how NodeLocal DNSCache handles DNS queries." >}} ## Configuration +{{< note >}} The local listen IP address for NodeLocal DNSCache can be any IP in the 169.254.20.0/16 space or any other IP address that can be guaranteed to not collide with any existing IP. This document uses 169.254.20.10 as an example. +{{< /note >}} -This feature can be enabled using the command: +This feature can be enabled using the following steps: -`KUBE_ENABLE_NODELOCAL_DNS=true kubetest --up` +* Prepare a manifest similar to the sample [`nodelocaldns.yaml`](https://github.com/kubernetes/kubernetes/blob/master/cluster/addons/dns/nodelocaldns/nodelocaldns.yaml) and save it as `nodelocaldns.yaml.` +* Substitute the variables in the manifest with the right values: -This works for e2e clusters created on GCE. On all other environments, the following steps will setup NodeLocal DNSCache: + * kubedns=`kubectl get svc kube-dns -n kube-system -o jsonpath={.spec.clusterIP}` + + * domain=`` + + * localdns=`` + + `` is "cluster.local" by default. `` is the local listen IP address chosen for NodeLocal DNSCache. -* A yaml similar to [this](https://github.com/kubernetes/kubernetes/blob/master/cluster/addons/dns/nodelocaldns/nodelocaldns.yaml) can be applied using `kubectl create -f` command. -* No need to modify the --cluster-dns flag since NodeLocal DNSCache listens on both the kube-dns service IP as well as a link-local IP (169.254.20.10 by default) + * If kube-proxy is running in IPTABLES mode: + + ``` bash + sed -i "s/__PILLAR__LOCAL__DNS__/$localdns/g; s/__PILLAR__DNS__DOMAIN__/$domain/g; s/__PILLAR__DNS__SERVER__/$kubedns/g" nodelocaldns.yaml + ``` + + `__PILLAR__CLUSTER__DNS__` and `__PILLAR__UPSTREAM__SERVERS__` will be populated by the node-local-dns pods. + In this mode, node-local-dns pods listen on both the kube-dns service IP as well as ``, so pods can lookup DNS records using either IP address. + + * If kube-proxy is running in IPVS mode: + + ``` bash + sed -i "s/__PILLAR__LOCAL__DNS__/$localdns/g; s/__PILLAR__DNS__DOMAIN__/$domain/g; s/__PILLAR__DNS__SERVER__//g; s/__PILLAR__CLUSTER__DNS__/$kubedns/g" nodelocaldns.yaml + ``` + In this mode, node-local-dns pods listen only on ``. The node-local-dns interface cannot bind the kube-dns cluster IP since the interface used for IPVS loadbalancing already uses this address. + `__PILLAR__UPSTREAM__SERVERS__` will be populated by the node-local-dns pods. + +* Run `kubectl create -f nodelocaldns.yaml` +* If using kube-proxy in IPVS mode, `--cluster-dns` flag to kubelet needs to be modified to use `` that NodeLocal DNSCache is listening on. + Otherwise, there is no need to modify the value of the `--cluster-dns` flag, since NodeLocal DNSCache listens on both the kube-dns service IP as well as ``. Once enabled, node-local-dns Pods will run in the kube-system namespace on each of the cluster nodes. This Pod runs [CoreDNS](https://github.com/coredns/coredns) in cache mode, so all CoreDNS metrics exposed by the different plugins will be available on a per-node basis. -The feature can be disabled by removing the daemonset, using `kubectl delete -f` command. On e2e clusters created on GCE, the daemonset can be removed by deleting the node-local-dns yaml from `/etc/kubernetes/addons/0-dns/nodelocaldns.yaml` - +You can disable this feature by removing the DaemonSet, using `kubectl delete -f ` . You should also revert any changes you made to the kubelet configuration. {{% /capture %}} diff --git a/content/en/docs/tasks/administer-cluster/reserve-compute-resources.md b/content/en/docs/tasks/administer-cluster/reserve-compute-resources.md index e4fe4a5ac9..39d0e825b8 100644 --- a/content/en/docs/tasks/administer-cluster/reserve-compute-resources.md +++ b/content/en/docs/tasks/administer-cluster/reserve-compute-resources.md @@ -94,13 +94,7 @@ be configured to use the `systemd` cgroup driver. `kube-reserved` is meant to capture resource reservation for kubernetes system daemons like the `kubelet`, `container runtime`, `node problem detector`, etc. It is not meant to reserve resources for system daemons that are run as pods. -`kube-reserved` is typically a function of `pod density` on the nodes. [This -performance dashboard](http://node-perf-dash.k8s.io/#/builds) exposes `cpu` and -`memory` usage profiles of `kubelet` and `docker engine` at multiple levels of -pod density. [This blog -post](https://kubernetes.io/blog/2016/11/visualize-kubelet-performance-with-node-dashboard) -explains how the dashboard can be interpreted to come up with a suitable -`kube-reserved` reservation. +`kube-reserved` is typically a function of `pod density` on the nodes. In addition to `cpu`, `memory`, and `ephemeral-storage`, `pid` may be specified to reserve the specified number of process IDs for diff --git a/content/en/docs/tasks/administer-cluster/safely-drain-node.md b/content/en/docs/tasks/administer-cluster/safely-drain-node.md index e7a4a093ac..29006ff754 100644 --- a/content/en/docs/tasks/administer-cluster/safely-drain-node.md +++ b/content/en/docs/tasks/administer-cluster/safely-drain-node.md @@ -9,7 +9,7 @@ content_template: templates/task --- {{% capture overview %}} -This page shows how to safely drain a machine, respecting the PodDisruptionBudget you have defined. +This page shows how to safely drain a node, respecting the PodDisruptionBudget you have defined. {{% /capture %}} {{% capture prerequisites %}} @@ -156,6 +156,7 @@ application owners and cluster owners to establish an agreement on behavior in t {{% capture whatsnext %}} * Follow steps to protect your application by [configuring a Pod Disruption Budget](/docs/tasks/run-application/configure-pdb/). +* Learn more about [maintenance on a node](/docs/tasks/administer-cluster/cluster-management/#maintenance-on-a-node). {{% /capture %}} diff --git a/content/en/docs/tasks/administer-cluster/sysctl-cluster.md b/content/en/docs/tasks/administer-cluster/sysctl-cluster.md index 9f341d046f..5e57c18379 100644 --- a/content/en/docs/tasks/administer-cluster/sysctl-cluster.md +++ b/content/en/docs/tasks/administer-cluster/sysctl-cluster.md @@ -72,9 +72,9 @@ cluster admin on a per-node basis. Pods with disabled unsafe sysctls will be scheduled, but will fail to launch. With the warning above in mind, the cluster admin can allow certain _unsafe_ -sysctls for very special situations like e.g. high-performance or real-time +sysctls for very special situations such as high-performance or real-time application tuning. _Unsafe_ sysctls are enabled on a node-by-node basis with a -flag of the kubelet, e.g.: +flag of the kubelet; for example: ```shell kubelet --allowed-unsafe-sysctls \ diff --git a/content/en/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes.md b/content/en/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes.md index dfa0a1b414..d4b306f02b 100644 --- a/content/en/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes.md +++ b/content/en/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes.md @@ -6,20 +6,20 @@ weight: 110 {{% capture overview %}} -This page shows how to configure liveness, readiness and startup probes for Containers. +This page shows how to configure liveness, readiness and startup probes for containers. The [kubelet](/docs/admin/kubelet/) uses liveness probes to know when to -restart a Container. For example, liveness probes could catch a deadlock, +restart a container. For example, liveness probes could catch a deadlock, where an application is running, but unable to make progress. Restarting a -Container in such a state can help to make the application more available +container in such a state can help to make the application more available despite bugs. -The kubelet uses readiness probes to know when a Container is ready to start -accepting traffic. A Pod is considered ready when all of its Containers are ready. +The kubelet uses readiness probes to know when a container is ready to start +accepting traffic. A Pod is considered ready when all of its containers are ready. One use of this signal is to control which Pods are used as backends for Services. When a Pod is not ready, it is removed from Service load balancers. -The kubelet uses startup probes to know when a Container application has started. +The kubelet uses startup probes to know when a container application has started. If such a probe is configured, it disables liveness and readiness checks until it succeeds, making sure those probes don't interfere with the application startup. This can be used to adopt liveness checks on slow starting containers, avoiding them @@ -41,27 +41,27 @@ Many applications running for long periods of time eventually transition to broken states, and cannot recover except by being restarted. Kubernetes provides liveness probes to detect and remedy such situations. -In this exercise, you create a Pod that runs a Container based on the +In this exercise, you create a Pod that runs a container based on the `k8s.gcr.io/busybox` image. Here is the configuration file for the Pod: {{< codenew file="pods/probe/exec-liveness.yaml" >}} -In the configuration file, you can see that the Pod has a single Container. +In the configuration file, you can see that the Pod has a single `Container`. The `periodSeconds` field specifies that the kubelet should perform a liveness probe every 5 seconds. The `initialDelaySeconds` field tells the kubelet that it should wait 5 second before performing the first probe. To perform a probe, the -kubelet executes the command `cat /tmp/healthy` in the Container. If the -command succeeds, it returns 0, and the kubelet considers the Container to be alive and -healthy. If the command returns a non-zero value, the kubelet kills the Container +kubelet executes the command `cat /tmp/healthy` in the target container. If the +command succeeds, it returns 0, and the kubelet considers the container to be alive and +healthy. If the command returns a non-zero value, the kubelet kills the container and restarts it. -When the Container starts, it executes this command: +When the container starts, it executes this command: ```shell /bin/sh -c "touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600" ``` -For the first 30 seconds of the Container's life, there is a `/tmp/healthy` file. +For the first 30 seconds of the container's life, there is a `/tmp/healthy` file. So during the first 30 seconds, the command `cat /tmp/healthy` returns a success code. After 30 seconds, `cat /tmp/healthy` returns a failure code. @@ -79,7 +79,7 @@ kubectl describe pod liveness-exec The output indicates that no liveness probes have failed yet: -```shell +``` FirstSeen LastSeen Count From SubobjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 24s 24s 1 {default-scheduler } Normal Scheduled Successfully assigned liveness-exec to worker0 @@ -98,7 +98,7 @@ kubectl describe pod liveness-exec At the bottom of the output, there are messages indicating that the liveness probes have failed, and the containers have been killed and recreated. -```shell +``` FirstSeen LastSeen Count From SubobjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 37s 37s 1 {default-scheduler } Normal Scheduled Successfully assigned liveness-exec to worker0 @@ -109,7 +109,7 @@ FirstSeen LastSeen Count From SubobjectPath Type 2s 2s 1 {kubelet worker0} spec.containers{liveness} Warning Unhealthy Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory ``` -Wait another 30 seconds, and verify that the Container has been restarted: +Wait another 30 seconds, and verify that the container has been restarted: ```shell kubectl get pod liveness-exec @@ -117,7 +117,7 @@ kubectl get pod liveness-exec The output shows that `RESTARTS` has been incremented: -```shell +``` NAME READY STATUS RESTARTS AGE liveness-exec 1/1 Running 1 1m ``` @@ -130,23 +130,23 @@ image. {{< codenew file="pods/probe/http-liveness.yaml" >}} -In the configuration file, you can see that the Pod has a single Container. +In the configuration file, you can see that the Pod has a single container. The `periodSeconds` field specifies that the kubelet should perform a liveness probe every 3 seconds. The `initialDelaySeconds` field tells the kubelet that it should wait 3 seconds before performing the first probe. To perform a probe, the -kubelet sends an HTTP GET request to the server that is running in the Container +kubelet sends an HTTP GET request to the server that is running in the container and listening on port 8080. If the handler for the server's `/healthz` path -returns a success code, the kubelet considers the Container to be alive and -healthy. If the handler returns a failure code, the kubelet kills the Container +returns a success code, the kubelet considers the container to be alive and +healthy. If the handler returns a failure code, the kubelet kills the container and restarts it. Any code greater than or equal to 200 and less than 400 indicates success. Any other code indicates failure. You can see the source code for the server in -[server.go](https://github.com/kubernetes/kubernetes/blob/master/test/images/agnhost/liveness/server.go). +[server.go](https://github.com/kubernetes/kubernetes/blob/{{< param "githubbranch" >}}/test/images/agnhost/liveness/server.go). -For the first 10 seconds that the Container is alive, the `/healthz` handler +For the first 10 seconds that the container is alive, the `/healthz` handler returns a status of 200. After that, the handler returns a status of 500. ```go @@ -162,9 +162,9 @@ http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { }) ``` -The kubelet starts performing health checks 3 seconds after the Container starts. +The kubelet starts performing health checks 3 seconds after the container starts. So the first couple of health checks will succeed. But after 10 seconds, the health -checks will fail, and the kubelet will kill and restart the Container. +checks will fail, and the kubelet will kill and restart the container. To try the HTTP liveness check, create a Pod: @@ -173,21 +173,21 @@ kubectl apply -f https://k8s.io/examples/pods/probe/http-liveness.yaml ``` After 10 seconds, view Pod events to verify that liveness probes have failed and -the Container has been restarted: +the container has been restarted: ```shell kubectl describe pod liveness-http ``` In releases prior to v1.13 (including v1.13), if the environment variable -`http_proxy` (or `HTTP_PROXY`) is set on the node where a pod is running, +`http_proxy` (or `HTTP_PROXY`) is set on the node where a Pod is running, the HTTP liveness probe uses that proxy. In releases after v1.13, local HTTP proxy environment variable settings do not affect the HTTP liveness probe. ## Define a TCP liveness probe -A third type of liveness probe uses a TCP Socket. With this configuration, the +A third type of liveness probe uses a TCP socket. With this configuration, the kubelet will attempt to open a socket to your container on the specified port. If it can establish a connection, the container is considered healthy, if it can’t it is considered a failure. @@ -197,7 +197,7 @@ can’t it is considered a failure. As you can see, configuration for a TCP check is quite similar to an HTTP check. This example uses both readiness and liveness probes. The kubelet will send the first readiness probe 5 seconds after the container starts. This will attempt to -connect to the `goproxy` container on port 8080. If the probe succeeds, the pod +connect to the `goproxy` container on port 8080. If the probe succeeds, the Pod will be marked as ready. The kubelet will continue to run this check every 10 seconds. @@ -351,7 +351,7 @@ port to perform the check. The kubelet sends the probe to the pod’s IP address unless the address is overridden by the optional `host` field in `httpGet`. If `scheme` field is set to `HTTPS`, the kubelet sends an HTTPS request skipping the certificate verification. In most scenarios, you do not want to set the `host` field. -Here's one scenario where you would set it. Suppose the Container listens on 127.0.0.1 +Here's one scenario where you would set it. Suppose the container listens on 127.0.0.1 and the Pod's `hostNetwork` field is true. Then `host`, under `httpGet`, should be set to 127.0.0.1. If your pod relies on virtual hosts, which is probably the more common case, you should not use `host`, but rather set the `Host` header in `httpHeaders`. @@ -367,7 +367,7 @@ to resolve it. * Learn more about [Container Probes](/docs/concepts/workloads/pods/pod-lifecycle/#container-probes). -### Reference +You can also read the API references for: * [Pod](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#pod-v1-core) * [Container](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#container-v1-core) diff --git a/content/en/docs/tasks/configure-pod-container/configure-pod-configmap.md b/content/en/docs/tasks/configure-pod-container/configure-pod-configmap.md index dcba78d81a..71fad95de9 100644 --- a/content/en/docs/tasks/configure-pod-container/configure-pod-configmap.md +++ b/content/en/docs/tasks/configure-pod-container/configure-pod-configmap.md @@ -33,6 +33,8 @@ kubectl create configmap ``` where \ is the name you want to assign to the ConfigMap and \ is the directory, file, or literal value to draw the data from. +The name of a ConfigMap object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). When you are creating a ConfigMap based on a file, the key in the \ defaults to the basename of the file, and the value defaults to the file content. diff --git a/content/en/docs/tasks/configure-pod-container/configure-service-account.md b/content/en/docs/tasks/configure-pod-container/configure-service-account.md index f42bc8e1fd..f4917b36a9 100644 --- a/content/en/docs/tasks/configure-pod-container/configure-service-account.md +++ b/content/en/docs/tasks/configure-pod-container/configure-service-account.md @@ -95,6 +95,9 @@ metadata: EOF ``` +The name of a ServiceAccount object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + If you get a complete dump of the service account object, like this: ```shell diff --git a/content/en/docs/tasks/configure-pod-container/static-pod.md b/content/en/docs/tasks/configure-pod-container/static-pod.md index 320d800dc9..fc31526348 100644 --- a/content/en/docs/tasks/configure-pod-container/static-pod.md +++ b/content/en/docs/tasks/configure-pod-container/static-pod.md @@ -63,7 +63,7 @@ For example, this is how to start a simple web server as a static Pod: ssh my-node1 ``` -2. Choose a directory, say `/etc/kubelet.d` and place a web server Pod definition there, e.g. `/etc/kubelet.d/static-web.yaml`: +2. Choose a directory, say `/etc/kubelet.d` and place a web server Pod definition there, for example `/etc/kubelet.d/static-web.yaml`: ```shell # Run this command on the node where kubelet is running diff --git a/content/en/docs/tasks/configure-pod-container/translate-compose-kubernetes.md b/content/en/docs/tasks/configure-pod-container/translate-compose-kubernetes.md index 4d0521722a..847d76f25c 100644 --- a/content/en/docs/tasks/configure-pod-container/translate-compose-kubernetes.md +++ b/content/en/docs/tasks/configure-pod-container/translate-compose-kubernetes.md @@ -580,7 +580,7 @@ If you want to create normal pods without controllers you can use `restart` cons The controller object could be `deployment` or `replicationcontroller`, etc. {{< /note >}} -For e.g. `pival` service will become pod down here. This container calculated value of `pi`. +For example, the `pival` service will become pod down here. This container calculated value of `pi`. ```yaml version: '2' diff --git a/content/en/docs/tasks/debug-application-cluster/audit.md b/content/en/docs/tasks/debug-application-cluster/audit.md index 2c769eb933..8e7497bdb8 100644 --- a/content/en/docs/tasks/debug-application-cluster/audit.md +++ b/content/en/docs/tasks/debug-application-cluster/audit.md @@ -235,6 +235,8 @@ spec: ``` For the complete API definition, see [AuditSink](/docs/reference/generated/kubernetes-api/v1.13/#auditsink-v1alpha1-auditregistration). Multiple objects will exist as independent solutions. +The name of an AuditSink object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). Existing static backends that you configure with runtime flags are not affected by this feature. However, the dynamic backends share the truncate options of the static webhook. If webhook truncate options are set with runtime flags, they are applied to all dynamic backends. @@ -272,7 +274,7 @@ to turn up in a new cluster. The scheme must be "https"; the URL must begin with "https://". -Attempting to use a user or basic auth e.g. "user:password@" is not allowed. +Attempting to use a user or basic auth (for example "user:password@") is not allowed. Fragments ("#...") and query parameters ("?...") are also not allowed. Here is an example of a webhook configured to call a URL diff --git a/content/en/docs/tasks/debug-application-cluster/debug-cluster.md b/content/en/docs/tasks/debug-application-cluster/debug-cluster.md index 4e95d82905..495545ee1a 100644 --- a/content/en/docs/tasks/debug-application-cluster/debug-cluster.md +++ b/content/en/docs/tasks/debug-application-cluster/debug-cluster.md @@ -29,6 +29,11 @@ kubectl get nodes And verify that all of the nodes you expect to see are present and that they are all in the `Ready` state. +To get detailed information about the overall health of your cluster, you can run: + +```shell +kubectl cluster-info dump +``` ## Looking at logs For now, digging deeper into the cluster requires logging into the relevant machines. Here are the locations @@ -55,7 +60,7 @@ This is an incomplete list of things that could go wrong, and how to adjust your - Network partition within cluster, or between cluster and users - Crashes in Kubernetes software - Data loss or unavailability of persistent storage (e.g. GCE PD or AWS EBS volume) - - Operator error, e.g. misconfigured Kubernetes software or application software + - Operator error, for example misconfigured Kubernetes software or application software ### Specific scenarios: diff --git a/content/en/docs/tasks/debug-application-cluster/debug-service.md b/content/en/docs/tasks/debug-application-cluster/debug-service.md index e0683fbd02..a065c9fa85 100644 --- a/content/en/docs/tasks/debug-application-cluster/debug-service.md +++ b/content/en/docs/tasks/debug-application-cluster/debug-service.md @@ -8,57 +8,30 @@ title: Debug Services {{% capture overview %}} An issue that comes up rather frequently for new installations of Kubernetes is -that a `Service` is not working properly. You've run your `Deployment` and -created a `Service`, but you get no response when you try to access it. -This document will hopefully help you to figure out what's going wrong. +that a Service is not working properly. You've run your Pods through a +Deployment (or other workload controller) and created a Service, but you +get no response when you try to access it. This document will hopefully help +you to figure out what's going wrong. {{% /capture %}} {{% capture body %}} -## Conventions - -Throughout this doc you will see various commands that you can run. Some -commands need to be run within a `Pod`, others on a Kubernetes `Node`, and others -can run anywhere you have `kubectl` and credentials for the cluster. To make it -clear what is expected, this document will use the following conventions. - -If the command "COMMAND" is expected to run in a `Pod` and produce "OUTPUT": - -```shell -u@pod$ COMMAND -OUTPUT -``` - -If the command "COMMAND" is expected to run on a `Node` and produce "OUTPUT": - -```shell -u@node$ COMMAND -OUTPUT -``` - -If the command is "kubectl ARGS": - -```shell -kubectl ARGS -OUTPUT -``` - ## Running commands in a Pod -For many steps here you will want to see what a `Pod` running in the cluster -sees. The simplest way to do this is to run an interactive alpine `Pod`: +For many steps here you will want to see what a Pod running in the cluster +sees. The simplest way to do this is to run an interactive alpine Pod: ```none kubectl run -it --rm --restart=Never alpine --image=alpine sh -/ # ``` + {{< note >}} If you don't see a command prompt, try pressing enter. {{< /note >}} -If you already have a running `Pod` that you prefer to use, you can run a +If you already have a running Pod that you prefer to use, you can run a command in it using: ```shell @@ -67,21 +40,23 @@ kubectl exec -c -- ## Setup -For the purposes of this walk-through, let's run some `Pods`. Since you're -probably debugging your own `Service` you can substitute your own details, or you +For the purposes of this walk-through, let's run some Pods. Since you're +probably debugging your own Service you can substitute your own details, or you can follow along and get a second data point. ```shell kubectl run hostnames --image=k8s.gcr.io/serve_hostname \ - --labels=app=hostnames \ - --port=9376 \ - --replicas=3 + --replicas=3 +``` +```none deployment.apps/hostnames created ``` `kubectl` commands will print the type and name of the resource created or mutated, which can then be used in subsequent commands. + {{< note >}} -This is the same as if you started the `Deployment` with the following YAML: +This is the same as if you had started the Deployment with the following +YAML: ```yaml apiVersion: apps/v1 @@ -91,61 +66,111 @@ metadata: spec: selector: matchLabels: - app: hostnames + run: hostnames replicas: 3 template: metadata: labels: - app: hostnames + run: hostnames spec: containers: - name: hostnames image: k8s.gcr.io/serve_hostname - ports: - - containerPort: 9376 - protocol: TCP ``` + +The label "run" is automatically set by `kubectl run` to the name of the +Deployment. {{< /note >}} -Confirm your `Pods` are running: +You can confirm your Pods are running: ```shell -kubectl get pods -l app=hostnames +kubectl get pods -l run=hostnames +``` +```none NAME READY STATUS RESTARTS AGE hostnames-632524106-bbpiw 1/1 Running 0 2m hostnames-632524106-ly40y 1/1 Running 0 2m hostnames-632524106-tlaok 1/1 Running 0 2m ``` +You can also confirm that your Pods are serving. You can get the list of +Pod IP addresses and test them directly. + +```shell +kubectl get pods -l run=hostnames \ + -o go-template='{{range .items}}{{.status.podIP}}{{"\n"}}{{end}}' +``` +```none +10.244.0.5 +10.244.0.6 +10.244.0.7 +``` + +The example container used for this walk-through simply serves its own hostname +via HTTP on port 9376, but if you are debugging your own app, you'll want to +use whatever port number your Pods are listening on. + +From within a pod: + +```shell +for ep in 10.244.0.5:9376 10.244.0.6:9376 10.244.0.7:9376; do + wget -qO- $ep +done +``` + +This should produce something like: + +``` +hostnames-0uton +hostnames-bvc05 +hostnames-yp2kp +``` + +If you are not getting the responses you expect at this point, your Pods +might not be healthy or might not be listening on the port you think they are. +You might find `kubectl logs` to be useful for seeing what is happening, or +perhaps you need to `kubectl exec` directly into your Pods and debug from +there. + +Assuming everything has gone to plan so far, you can start to investigate why +your Service doesn't work. + ## Does the Service exist? -The astute reader will have noticed that we did not actually create a `Service` +The astute reader will have noticed that you did not actually create a Service yet - that is intentional. This is a step that sometimes gets forgotten, and is the first thing to check. -So what would happen if I tried to access a non-existent `Service`? Assuming you -have another `Pod` that consumes this `Service` by name you would get something -like: +What would happen if you tried to access a non-existent Service? If +you have another Pod that consumes this Service by name you would get +something like: ```shell -u@pod$ wget -O- hostnames +wget -O- hostnames +``` +```none Resolving hostnames (hostnames)... failed: Name or service not known. wget: unable to resolve host address 'hostnames' ``` -So the first thing to check is whether that `Service` actually exists: +The first thing to check is whether that Service actually exists: ```shell kubectl get svc hostnames +``` +```none No resources found. Error from server (NotFound): services "hostnames" not found ``` -So we have a culprit, let's create the `Service`. As before, this is for the -walk-through - you can use your own `Service`'s details here. +Let's create the Service. As before, this is for the walk-through - you can +use your own Service's details here. ```shell kubectl expose deployment hostnames --port=80 --target-port=9376 +``` +```none service/hostnames exposed ``` @@ -153,11 +178,16 @@ And read it back, just to be sure: ```shell kubectl get svc hostnames +``` +```none NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE hostnames ClusterIP 10.0.1.175 80/TCP 5s ``` -As before, this is the same as if you had started the `Service` with YAML: +Now you know that the Service exists. + +{{< note >}} +As before, this is the same as if you had started the Service with YAML: ```yaml apiVersion: v1 @@ -166,7 +196,7 @@ metadata: name: hostnames spec: selector: - app: hostnames + run: hostnames ports: - name: default protocol: TCP @@ -174,25 +204,35 @@ spec: targetPort: 9376 ``` -Now you can confirm that the `Service` exists. +In order to highlight the full range of configuration, the Service you created +here uses a different port number than the Pods. For many real-world +Services, these values might be the same. +{{< /note >}} -## Does the Service work by DNS? +## Does the Service work by DNS name? -From a `Pod` in the same `Namespace`: +One of the most common ways that clients consume a Service is through a DNS +name. + +From a Pod in the same Namespace: ```shell -u@pod$ nslookup hostnames +nslookup hostnames +``` +```none Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local Name: hostnames Address 1: 10.0.1.175 hostnames.default.svc.cluster.local ``` -If this fails, perhaps your `Pod` and `Service` are in different -`Namespaces`, try a namespace-qualified name: +If this fails, perhaps your Pod and Service are in different +Namespaces, try a namespace-qualified name (again, from within a Pod): ```shell -u@pod$ nslookup hostnames.default +nslookup hostnames.default +``` +```none Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local Name: hostnames.default @@ -200,11 +240,13 @@ Address 1: 10.0.1.175 hostnames.default.svc.cluster.local ``` If this works, you'll need to adjust your app to use a cross-namespace name, or -run your app and `Service` in the same `Namespace`. If this still fails, try a +run your app and Service in the same Namespace. If this still fails, try a fully-qualified name: ```shell -u@pod$ nslookup hostnames.default.svc.cluster.local +nslookup hostnames.default.svc.cluster.local +``` +```none Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local Name: hostnames.default.svc.cluster.local @@ -212,18 +254,20 @@ Address 1: 10.0.1.175 hostnames.default.svc.cluster.local ``` Note the suffix here: "default.svc.cluster.local". The "default" is the -`Namespace` we're operating in. The "svc" denotes that this is a `Service`. +Namespace you're operating in. The "svc" denotes that this is a Service. The "cluster.local" is your cluster domain, which COULD be different in your own cluster. -You can also try this from a `Node` in the cluster: +You can also try this from a Node in the cluster: {{< note >}} -10.0.0.10 is my DNS `Service`, yours might be different. +10.0.0.10 is the cluster's DNS Service IP, yours might be different. {{< /note >}} ```shell -u@node$ nslookup hostnames.default.svc.cluster.local 10.0.0.10 +nslookup hostnames.default.svc.cluster.local 10.0.0.10 +``` +```none Server: 10.0.0.10 Address: 10.0.0.10#53 @@ -232,39 +276,49 @@ Address: 10.0.1.175 ``` If you are able to do a fully-qualified name lookup but not a relative one, you -need to check that your `/etc/resolv.conf` file is correct. +need to check that your `/etc/resolv.conf` file in your Pod is correct. From +within a Pod: ```shell -u@pod$ cat /etc/resolv.conf +cat /etc/resolv.conf +``` + +You should see something like: + +``` nameserver 10.0.0.10 search default.svc.cluster.local svc.cluster.local cluster.local example.com options ndots:5 ``` -The `nameserver` line must indicate your cluster's DNS `Service`. This is +The `nameserver` line must indicate your cluster's DNS Service. This is passed into `kubelet` with the `--cluster-dns` flag. The `search` line must include an appropriate suffix for you to find the -`Service` name. In this case it is looking for `Services` in the local -`Namespace` (`default.svc.cluster.local`), `Services` in all `Namespaces` -(`svc.cluster.local`), and the cluster (`cluster.local`). Depending on your own -install you might have additional records after that (up to 6 total). The -cluster suffix is passed into `kubelet` with the `--cluster-domain` flag. We -assume that is "cluster.local" in this document, but yours might be different, -in which case you should change that in all of the commands above. +Service name. In this case it is looking for Services in the local +Namespace ("default.svc.cluster.local"), Services in all Namespaces +("svc.cluster.local"), and lastly for names in the cluster ("cluster.local"). +Depending on your own install you might have additional records after that (up +to 6 total). The cluster suffix is passed into `kubelet` with the +`--cluster-domain` flag. Throughout this document, the cluster suffix is +assumed to be "cluster.local". Your own clusters might be configured +differently, in which case you should change that in all of the previous +commands. The `options` line must set `ndots` high enough that your DNS client library considers search paths at all. Kubernetes sets this to 5 by default, which is high enough to cover all of the DNS names it generates. -### Does any Service exist in DNS? +### Does any Service work by DNS name? {#does-any-service-exist-in-dns} -If the above still fails - DNS lookups are not working for your `Service` - we +If the above still fails, DNS lookups are not working for your Service. You can take a step back and see what else is not working. The Kubernetes master -`Service` should always work: +Service should always work. From within a Pod: ```shell -u@pod$ nslookup kubernetes.default +nslookup kubernetes.default +``` +```none Server: 10.0.0.10 Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local @@ -272,34 +326,37 @@ Name: kubernetes.default Address 1: 10.0.0.1 kubernetes.default.svc.cluster.local ``` -If this fails, you might need to go to the kube-proxy section of this doc, or -even go back to the top of this document and start over, but instead of -debugging your own `Service`, debug DNS. +If this fails, please see the [kube-proxy](#is-the-kube-proxy-working) section +of this document, or even go back to the top of this document and start over, +but instead of debugging your own Service, debug the DNS Service. ## Does the Service work by IP? -Assuming we can confirm that DNS works, the next thing to test is whether your -`Service` works at all. From a node in your cluster, access the `Service`'s -IP (from `kubectl get` above). +Assuming you have confirmed that DNS works, the next thing to test is whether your +Service works by its IP address. From a Pod in your cluster, access the +Service's IP (from `kubectl get` above). ```shell -u@node$ curl 10.0.1.175:80 -hostnames-0uton - -u@node$ curl 10.0.1.175:80 -hostnames-yp2kp - -u@node$ curl 10.0.1.175:80 -hostnames-bvc05 +for i in $(seq 1 3); do + wget -qO- 10.0.1.175:80 +done ``` -If your `Service` is working, you should get correct responses. If not, there +This should produce something like: + +``` +hostnames-0uton +hostnames-bvc05 +hostnames-yp2kp +``` + +If your Service is working, you should get correct responses. If not, there are a number of things that could be going wrong. Read on. -## Is the Service correct? +## Is the Service defined correctly? It might sound silly, but you should really double and triple check that your -`Service` is correct and matches your `Pod`'s port. Read back your `Service` +Service is correct and matches your Pod's port. Read back your Service and verify it: ```shell @@ -316,7 +373,7 @@ kubectl get service hostnames -o json "resourceVersion": "347189", "creationTimestamp": "2015-07-07T15:24:29Z", "labels": { - "app": "hostnames" + "run": "hostnames" } }, "spec": { @@ -330,7 +387,7 @@ kubectl get service hostnames -o json } ], "selector": { - "app": "hostnames" + "run": "hostnames" }, "clusterIP": "10.0.1.175", "type": "ClusterIP", @@ -342,110 +399,116 @@ kubectl get service hostnames -o json } ``` -* Is the port you are trying to access in `spec.ports[]`? -* Is the `targetPort` correct for your `Pods` (many `Pods` choose to use a different port than the `Service`)? -* If you meant it to be a numeric port, is it a number (9376) or a -string "9376"? -* If you meant it to be a named port, do your `Pods` expose a port -with the same name? -* Is the port's `protocol` the same as the `Pod`'s? +* Is the Service port you are trying to access listed in `spec.ports[]`? +* Is the `targetPort` correct for your Pods (some Pods use a different port than the Service)? +* If you meant to use a numeric port, is it a number (9376) or a string "9376"? +* If you meant to use a named port, do your Pods expose a port with the same name? +* Is the port's `protocol` correct for your Pods? ## Does the Service have any Endpoints? -If you got this far, we assume that you have confirmed that your `Service` -exists and is resolved by DNS. Now let's check that the `Pods` you ran are -actually being selected by the `Service`. +If you got this far, you have confirmed that your Service is correctly +defined and is resolved by DNS. Now let's check that the Pods you ran are +actually being selected by the Service. -Earlier we saw that the `Pods` were running. We can re-check that: +Earlier you saw that the Pods were running. You can re-check that: ```shell -kubectl get pods -l app=hostnames +kubectl get pods -l run=hostnames +``` +```none NAME READY STATUS RESTARTS AGE hostnames-0uton 1/1 Running 0 1h hostnames-bvc05 1/1 Running 0 1h hostnames-yp2kp 1/1 Running 0 1h ``` -The "AGE" column says that these `Pods` are about an hour old, which implies that +The `-l run=hostnames` argument is a label selector - just like our Service +has. + +The "AGE" column says that these Pods are about an hour old, which implies that they are running fine and not crashing. -The `-l app=hostnames` argument is a label selector - just like our `Service` -has. Inside the Kubernetes system is a control loop which evaluates the -selector of every `Service` and saves the results into an `Endpoints` object. +The "RESTARTS" column says that these pods are not crashing frequently or being +restarted. Frequent restarts could lead to intermittent connectivity issues. +If the restart count is high, read more about how to [debug pods](/docs/tasks/debug-application-cluster/debug-pod-replication-controller/#debugging-pods). + +Inside the Kubernetes system is a control loop which evaluates the selector of +every Service and saves the results into a corresponding Endpoints object. ```shell kubectl get endpoints hostnames + NAME ENDPOINTS hostnames 10.244.0.5:9376,10.244.0.6:9376,10.244.0.7:9376 ``` -This confirms that the endpoints controller has found the correct `Pods` for -your `Service`. If the `hostnames` row is blank, you should check that the -`spec.selector` field of your `Service` actually selects for `metadata.labels` -values on your `Pods`. A common mistake is to have a typo or other error, such -as the `Service` selecting for `run=hostnames`, but the `Deployment` specifying -`app=hostnames`. +This confirms that the endpoints controller has found the correct Pods for +your Service. If the `ENDPOINTS` column is ``, you should check that +the `spec.selector` field of your Service actually selects for +`metadata.labels` values on your Pods. A common mistake is to have a typo or +other error, such as the Service selecting for `app=hostnames`, but the +Deployment specifying `run=hostnames`. ## Are the Pods working? -At this point, we know that your `Service` exists and has selected your `Pods`. -Let's check that the `Pods` are actually working - we can bypass the `Service` -mechanism and go straight to the `Pods`. +At this point, you know that your Service exists and has selected your Pods. +At the beginning of this walk-through, you verified the Pods themselves. +Let's check again that the Pods are actually working - you can bypass the +Service mechanism and go straight to the Pods, as listed by the Endpoints +above. {{< note >}} -These commands use the `Pod` port (9376), rather than the `Service` port (80). +These commands use the Pod port (9376), rather than the Service port (80). {{< /note >}} +From within a Pod: + ```shell -u@pod$ wget -qO- 10.244.0.5:9376 +for ep in 10.244.0.5:9376 10.244.0.6:9376 10.244.0.7:9376; do + wget -qO- $ep +done +``` + +This should produce something like: + +``` hostnames-0uton - -pod $ wget -qO- 10.244.0.6:9376 hostnames-bvc05 - -u@pod$ wget -qO- 10.244.0.7:9376 hostnames-yp2kp ``` -We expect each `Pod` in the `Endpoints` list to return its own hostname. If +You expect each Pod in the Endpoints list to return its own hostname. If this is not what happens (or whatever the correct behavior is for your own -`Pods`), you should investigate what's happening there. You might find -`kubectl logs` to be useful or `kubectl exec` directly to your `Pods` and check -service from there. - -Another thing to check is that your `Pods` are not crashing or being restarted. -Frequent restarts could lead to intermittent connectivity issues. - -```shell -kubectl get pods -l app=hostnames -NAME READY STATUS RESTARTS AGE -hostnames-632524106-bbpiw 1/1 Running 0 2m -hostnames-632524106-ly40y 1/1 Running 0 2m -hostnames-632524106-tlaok 1/1 Running 0 2m -``` - -If the restart count is high, read more about how to [debug -pods](/docs/tasks/debug-application-cluster/debug-pod-replication-controller/#debugging-pods). +Pods), you should investigate what's happening there. ## Is the kube-proxy working? -If you get here, your `Service` is running, has `Endpoints`, and your `Pods` -are actually serving. At this point, the whole `Service` proxy mechanism is +If you get here, your Service is running, has Endpoints, and your Pods +are actually serving. At this point, the whole Service proxy mechanism is suspect. Let's confirm it, piece by piece. +The default implementation of Services, and the one used on most clusters, is +kube-proxy. This is a program that runs on every node and configures one of a +small set of mechanisms for providing the Service abstraction. If your +cluster does not use kube-proxy, the following sections will not apply, and you +will have to investigate whatever implementation of Services you are using. + ### Is kube-proxy running? -Confirm that `kube-proxy` is running on your `Nodes`. You should get something -like the below: +Confirm that `kube-proxy` is running on your Nodes. Running directly on a +Node, you should get something like the below: ```shell -u@node$ ps auxw | grep kube-proxy +ps auxw | grep kube-proxy +``` +```none root 4194 0.4 0.1 101864 17696 ? Sl Jul04 25:43 /usr/local/bin/kube-proxy --master=https://kubernetes-master --kubeconfig=/var/lib/kube-proxy/kubeconfig --v=2 ``` Next, confirm that it is not failing something obvious, like contacting the master. To do this, you'll have to look at the logs. Accessing the logs -depends on your `Node` OS. On some OSes it is a file, such as +depends on your Node OS. On some OSes it is a file, such as /var/log/kube-proxy.log, while other OSes use `journalctl` to access logs. You should see something like: @@ -463,7 +526,7 @@ I1027 22:14:54.040223 5063 proxier.go:294] Adding new service "kube-system/ku ``` If you see error messages about not being able to contact the master, you -should double-check your `Node` configuration and installation steps. +should double-check your Node configuration and installation steps. One of the possible reasons that `kube-proxy` cannot run correctly is that the required `conntrack` binary cannot be found. This may happen on some Linux @@ -472,36 +535,19 @@ installing Kubernetes from scratch. If this is the case, you need to manually install the `conntrack` package (e.g. `sudo apt install conntrack` on Ubuntu) and then retry. -### Is kube-proxy writing iptables rules? +Kube-proxy can run in one of a few modes. In the log listed above, the +line `Using iptables Proxier` indicates that kube-proxy is running in +"iptables" mode. The most common other mode is "ipvs". The older "userspace" +mode has largely been replaced by these. -One of the main responsibilities of `kube-proxy` is to write the `iptables` -rules which implement `Services`. Let's check that those rules are getting -written. +#### Iptables mode -The kube-proxy can run in "userspace" mode, "iptables" mode or "ipvs" mode. -Hopefully you are using the "iptables" mode or "ipvs" mode. You -should see one of the following cases. - -#### Userspace +In "iptables" mode, you should see something like the following on a Node: ```shell -u@node$ iptables-save | grep hostnames --A KUBE-PORTALS-CONTAINER -d 10.0.1.175/32 -p tcp -m comment --comment "default/hostnames:default" -m tcp --dport 80 -j REDIRECT --to-ports 48577 --A KUBE-PORTALS-HOST -d 10.0.1.175/32 -p tcp -m comment --comment "default/hostnames:default" -m tcp --dport 80 -j DNAT --to-destination 10.240.115.247:48577 +iptables-save | grep hostnames ``` - -There should be 2 rules for each port on your `Service` (just one in this -example) - a "KUBE-PORTALS-CONTAINER" and a "KUBE-PORTALS-HOST". If you do -not see these, try restarting `kube-proxy` with the `-v` flag set to 4, and -then look at the logs again. - -Almost nobody should be using the "userspace" mode any more, so we won't spend -more time on it here. - -#### Iptables - -```shell -u@node$ iptables-save | grep hostnames +```none -A KUBE-SEP-57KPRZ3JQVENLNBR -s 10.244.3.6/32 -m comment --comment "default/hostnames:" -j MARK --set-xmark 0x00004000/0x00004000 -A KUBE-SEP-57KPRZ3JQVENLNBR -p tcp -m comment --comment "default/hostnames:" -m tcp -j DNAT --to-destination 10.244.3.6:9376 -A KUBE-SEP-WNBA2IHDGP2BOBGZ -s 10.244.1.7/32 -m comment --comment "default/hostnames:" -j MARK --set-xmark 0x00004000/0x00004000 @@ -514,15 +560,20 @@ u@node$ iptables-save | grep hostnames -A KUBE-SVC-NWV5X2332I4OT4T3 -m comment --comment "default/hostnames:" -j KUBE-SEP-57KPRZ3JQVENLNBR ``` -There should be 1 rule in `KUBE-SERVICES`, 1 or 2 rules per endpoint in -`KUBE-SVC-(hash)` (depending on `SessionAffinity`), one `KUBE-SEP-(hash)` chain -per endpoint, and a few rules in each `KUBE-SEP-(hash)` chain. The exact rules -will vary based on your exact config (including node-ports and load-balancers). +For each port of each Service, there should be 1 rule in `KUBE-SERVICES` and +one `KUBE-SVC-` chain. For each Pod endpoint, there should be a small +number of rules in that `KUBE-SVC-` and one `KUBE-SEP-` chain with +a small number of rules in it. The exact rules will vary based on your exact +config (including node-ports and load-balancers). -#### IPVS +#### IPVS mode + +In "ipvs" mode, you should see something like the following on a Node: ```shell -u@node$ ipvsadm -ln +ipvsadm -ln +``` +```none Prot LocalAddress:Port Scheduler Flags -> RemoteAddress:Port Forward Weight ActiveConn InActConn ... @@ -533,14 +584,39 @@ TCP 10.0.1.175:80 rr ... ``` -IPVS proxy will create a virtual server for each service address(e.g. Cluster IP, External IP, NodePort IP, Load Balancer IP etc.) and some corresponding real servers for endpoints of the service, if any. In this example, service hostnames(`10.0.1.175:80`) has 3 endpoints(`10.244.0.5:9376`, `10.244.0.6:9376`, `10.244.0.7:9376`) and you'll get results similar to above. +For each port of each Service, plus any NodePorts, external IPs, and +load-balancer IPs, kube-proxy will create a virtual server. For each Pod +endpoint, it will create corresponding real servers. In this example, service +hostnames(`10.0.1.175:80`) has 3 endpoints(`10.244.0.5:9376`, +`10.244.0.6:9376`, `10.244.0.7:9376`). + +#### Userspace mode + +In rare cases, you may be using "userspace" mode. From your Node: + +```shell +iptables-save | grep hostnames +``` +```none +-A KUBE-PORTALS-CONTAINER -d 10.0.1.175/32 -p tcp -m comment --comment "default/hostnames:default" -m tcp --dport 80 -j REDIRECT --to-ports 48577 +-A KUBE-PORTALS-HOST -d 10.0.1.175/32 -p tcp -m comment --comment "default/hostnames:default" -m tcp --dport 80 -j DNAT --to-destination 10.240.115.247:48577 +``` + +There should be 2 rules for each port of your Service (just one in this +example) - a "KUBE-PORTALS-CONTAINER" and a "KUBE-PORTALS-HOST". + +Almost nobody should be using the "userspace" mode any more, so you won't spend +more time on it here. ### Is kube-proxy proxying? -Assuming you do see the above rules, try again to access your `Service` by IP: +Assuming you do see one the above cases, try again to access your Service by +IP from one of your Nodes: ```shell -u@node$ curl 10.0.1.175:80 +curl 10.0.1.175:80 +``` +```none hostnames-0uton ``` @@ -548,31 +624,36 @@ If this fails and you are using the userspace proxy, you can try accessing the proxy directly. If you are using the iptables proxy, skip this section. Look back at the `iptables-save` output above, and extract the -port number that `kube-proxy` is using for your `Service`. In the above +port number that `kube-proxy` is using for your Service. In the above examples it is "48577". Now connect to that: ```shell -u@node$ curl localhost:48577 +curl localhost:48577 +``` +```none hostnames-yp2kp ``` If this still fails, look at the `kube-proxy` logs for specific lines like: -```shell +```none Setting endpoints for default/hostnames:default to [10.244.0.5:9376 10.244.0.6:9376 10.244.0.7:9376] ``` If you don't see those, try restarting `kube-proxy` with the `-v` flag set to 4, and then look at the logs again. -### A Pod cannot reach itself via Service IP +### Edge case: A Pod fails to reach itself via the Service IP {#a-pod-fails-to-reach-itself-via-the-service-ip} + +This might sound unlikely, but it does happen and it is supposed to work. This can happen when the network is not properly configured for "hairpin" traffic, usually when `kube-proxy` is running in `iptables` mode and Pods are connected with bridge network. The `Kubelet` exposes a `hairpin-mode` -[flag](/docs/admin/kubelet/) that allows endpoints of a Service to loadbalance back to themselves -if they try to access their own Service VIP. The `hairpin-mode` flag must either be -set to `hairpin-veth` or `promiscuous-bridge`. +[flag](/docs/admin/kubelet/) that allows endpoints of a Service to loadbalance +back to themselves if they try to access their own Service VIP. The +`hairpin-mode` flag must either be set to `hairpin-veth` or +`promiscuous-bridge`. The common steps to trouble shoot this are as follows: @@ -581,9 +662,10 @@ You should see something like the below. `hairpin-mode` is set to `promiscuous-bridge` in the following example. ```shell -u@node$ ps auxw|grep kubelet +ps auxw | grep kubelet +``` +```none root 3392 1.1 0.8 186804 65208 ? Sl 00:51 11:11 /usr/local/bin/kubelet --enable-debugging-handlers=true --config=/etc/kubernetes/manifests --allow-privileged=True --v=4 --cluster-dns=10.0.0.10 --cluster-domain=cluster.local --configure-cbr0=true --cgroup-root=/ --system-cgroups=/system --hairpin-mode=promiscuous-bridge --runtime-cgroups=/docker-daemon --kubelet-cgroups=/kubelet --babysit-daemons=true --max-pods=110 --serialize-image-pulls=false --outofdisk-transition-frequency=0 - ``` * Confirm the effective `hairpin-mode`. To do this, you'll have to look at @@ -594,7 +676,7 @@ match `--hairpin-mode` flag due to compatibility. Check if there is any log lines with key word `hairpin` in kubelet.log. There should be log lines indicating the effective hairpin mode, like something below. -```shell +```none I0629 00:51:43.648698 3252 kubelet.go:380] Hairpin mode set to "promiscuous-bridge" ``` @@ -604,6 +686,8 @@ you should see something like: ```shell for intf in /sys/devices/virtual/net/cbr0/brif/*; do cat $intf/hairpin_mode; done +``` +```none 1 1 1 @@ -615,20 +699,21 @@ has the permission to manipulate linux bridge on node. If `cbr0` bridge is used and configured properly, you should see: ```shell -u@node$ ifconfig cbr0 |grep PROMISC +ifconfig cbr0 |grep PROMISC +``` +```none UP BROADCAST RUNNING PROMISC MULTICAST MTU:1460 Metric:1 - ``` * Seek help if none of above works out. ## Seek help -If you get this far, something very strange is happening. Your `Service` is -running, has `Endpoints`, and your `Pods` are actually serving. You have DNS -working, `iptables` rules installed, and `kube-proxy` does not seem to be -misbehaving. And yet your `Service` is not working. You should probably let -us know, so we can help investigate! +If you get this far, something very strange is happening. Your Service is +running, has Endpoints, and your Pods are actually serving. You have DNS +working, and `kube-proxy` does not seem to be misbehaving. And yet your +Service is not working. Please let us know what is going on, so we can help +investigate! Contact us on [Slack](/docs/troubleshooting/#slack) or diff --git a/content/en/docs/tasks/debug-application-cluster/logging-stackdriver.md b/content/en/docs/tasks/debug-application-cluster/logging-stackdriver.md index d075944516..a60ceeedfb 100644 --- a/content/en/docs/tasks/debug-application-cluster/logging-stackdriver.md +++ b/content/en/docs/tasks/debug-application-cluster/logging-stackdriver.md @@ -362,7 +362,7 @@ you want to add Kafka sink for messages from a particular container for addition You can re-use the default [container image sources](https://git.k8s.io/contrib/fluentd/fluentd-gcp-image) with minor changes: -* Change Makefile to point to your container repository, e.g. `PREFIX=gcr.io/`. +* Change Makefile to point to your container repository, for example `PREFIX=gcr.io/`. * Add your dependency to the Gemfile, for example `gem 'fluent-plugin-kafka'`. Then run `make build push` from this directory. After updating `DaemonSet` to pick up the diff --git a/content/en/docs/tasks/inject-data-application/podpreset.md b/content/en/docs/tasks/inject-data-application/podpreset.md index beb57754c3..de41c0f73a 100644 --- a/content/en/docs/tasks/inject-data-application/podpreset.md +++ b/content/en/docs/tasks/inject-data-application/podpreset.md @@ -2,23 +2,19 @@ reviewers: - jessfraz title: Inject Information into Pods Using a PodPreset +min-kubernetes-server-version: v1.10 content_template: templates/task weight: 60 --- {{% capture overview %}} -You can use a `PodPreset` object to inject information like secrets, volume -mounts, and environment variables etc into pods at creation time. -This task shows some examples on using the `PodPreset` resource. +This page shows how to use PodPreset objects to inject information like {{< glossary_tooltip text="Secrets" term_id="secret" >}}, volume mounts, and {{< glossary_tooltip text="environment variables" term_id="container-env-variables" >}} into Pods at creation time. {{% /capture %}} {{% capture prerequisites %}} -Get an overview of PodPresets at -[Understanding Pod Presets](/docs/concepts/workloads/pods/podpreset/). - {{< include "task-tutorial-prereqs.md" >}} {{< version-check >}} {{% /capture %}} @@ -26,157 +22,298 @@ Get an overview of PodPresets at {{% capture steps %}} -## Simple Pod Spec Example +## Use Pod presets to inject environment variables and volumes -This is a simple example to show how a Pod spec is modified by the Pod -Preset. +In this step, you create a preset that has a volume mount and one environment variable. +Here is the manifest for the PodPreset: {{< codenew file="podpreset/preset.yaml" >}} +The name of a PodPreset object must be a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). + +In the manifest, you can see that the preset has an environment variable definition called `DB_PORT` +and a volume mount definition called `cache-volume` which is mounted under `/cache`. The {{< glossary_tooltip text="selector" term_id="selector" >}} specifies that +the preset will act upon any Pod that is labeled `role:frontend`. + Create the PodPreset: ```shell kubectl apply -f https://k8s.io/examples/podpreset/preset.yaml ``` -Examine the created PodPreset: +Verify that the PodPreset has been created: ```shell kubectl get podpreset ``` ``` -NAME AGE -allow-database 1m +NAME CREATED AT +allow-database 2020-01-24T08:54:29Z ``` -The new PodPreset will act upon any pod that has label `role: frontend`. +This manifest defines a Pod labelled `role: frontend` (matching the PodPreset's selector): {{< codenew file="podpreset/pod.yaml" >}} -Create a pod: +Create the Pod: ```shell kubectl create -f https://k8s.io/examples/podpreset/pod.yaml ``` -List the running Pods: +Verify that the Pod is running: ```shell kubectl get pods ``` + +The output shows that the Pod is running: + ``` NAME READY STATUS RESTARTS AGE website 1/1 Running 0 4m ``` -**Pod spec after admission controller:** - -{{< codenew file="podpreset/merged.yaml" >}} - -To see above output, run the following command: +View the Pod spec altered by the admission controller in order to see the effects of the preset +having been applied: ```shell kubectl get pod website -o yaml ``` -## Pod Spec with ConfigMap Example +{{< codenew file="podpreset/merged.yaml" >}} -This is an example to show how a Pod spec is modified by the Pod Preset -that defines a `ConfigMap` for Environment Variables. +The `DB_PORT` environment variable, the `volumeMount` and the `podpreset.admission.kubernetes.io` annotation +of the Pod verify that the preset has been applied. -**User submitted pod spec:** +## Pod spec with ConfigMap example -{{< codenew file="podpreset/pod.yaml" >}} +This is an example to show how a Pod spec is modified by a Pod preset +that references a ConfigMap containing environment variables. -**User submitted `ConfigMap`:** +Here is the manifest containing the definition of the ConfigMap: {{< codenew file="podpreset/configmap.yaml" >}} -**Example Pod Preset:** +Create the ConfigMap: + +```shell +kubectl create -f https://k8s.io/examples/podpreset/configmap.yaml +``` + +Here is a PodPreset manifest referencing that ConfigMap: {{< codenew file="podpreset/allow-db.yaml" >}} -**Pod spec after admission controller:** +Create the preset that references the ConfigMap: -{{< codenew file="podpreset/allow-db-merged.yaml" >}} +```shell +kubectl create -f https://k8s.io/examples/podpreset/allow-db.yaml +``` -## ReplicaSet with Pod Spec Example - -The following example shows that only the pod spec is modified by the Pod -Preset. - -**User submitted ReplicaSet:** - -{{< codenew file="podpreset/replicaset.yaml" >}} - -**Example Pod Preset:** - -{{< codenew file="podpreset/preset.yaml" >}} - -**Pod spec after admission controller:** - -Note that the ReplicaSet spec was not changed, users have to check individual pods -to validate that the PodPreset has been applied. - -{{< codenew file="podpreset/replicaset-merged.yaml" >}} - -## Multiple PodPreset Example - -This is an example to show how a Pod spec is modified by multiple Pod -Injection Policies. - -**User submitted pod spec:** +The following manifest defines a Pod matching the PodPreset for this example: {{< codenew file="podpreset/pod.yaml" >}} -**Example Pod Preset:** +Create the Pod: + +```shell +kubectl create -f https://k8s.io/examples/podpreset/pod.yaml +``` + +View the Pod spec altered by the admission controller in order to see the effects of the preset +having been applied: + +```shell +kubectl get pod website -o yaml +``` + +{{< codenew file="podpreset/allow-db-merged.yaml" >}} + +The `DB_PORT` environment variable and the `podpreset.admission.kubernetes.io` annotation of the Pod +verify that the preset has been applied. + +## ReplicaSet with Pod spec example + +This is an example to show that only Pod specs are modified by Pod presets. Other workload types +like ReplicaSets or Deployments are unaffected. + +Here is the manifest for the PodPreset for this example: {{< codenew file="podpreset/preset.yaml" >}} -**Another Pod Preset:** +Create the preset: + +```shell +kubectl apply -f https://k8s.io/examples/podpreset/preset.yaml +``` + +This manifest defines a ReplicaSet that manages three application Pods: + +{{< codenew file="podpreset/replicaset.yaml" >}} + +Create the ReplicaSet: + +```shell +kubectl create -f https://k8s.io/examples/podpreset/replicaset.yaml +``` + +Verify that the Pods created by the ReplicaSet are running: + +```shell +kubectl get pods +``` + +The output shows that the Pods are running: + +``` +NAME READY STATUS RESTARTS AGE +frontend-2l94q 1/1 Running 0 2m18s +frontend-6vdgn 1/1 Running 0 2m18s +frontend-jzt4p 1/1 Running 0 2m18s +``` + +View the `spec` of the ReplicaSet: + +```shell +kubectl get replicasets frontend -o yaml +``` + +{{< note >}} +The ReplicaSet object's `spec` was not changed, nor does the ReplicaSet contain a +`podpreset.admission.kubernetes.io` annotation. This is because a PodPreset only +applies to Pod objects. + +To see the effects of the preset having been applied, you need to look at individual Pods. +{{< /note >}} + +The command to view the specs of the affected Pods is: + +```shell +kubectl get pod --selector=role=frontend -o yaml +``` + +{{< codenew file="podpreset/replicaset-merged.yaml" >}} + +Again the `podpreset.admission.kubernetes.io` annotation of the Pods +verifies that the preset has been applied. + +## Multiple Pod presets example + +This is an example to show how a Pod spec is modified by multiple Pod presets. + + +Here is the manifest for the first PodPreset: + +{{< codenew file="podpreset/preset.yaml" >}} + +Create the first PodPreset for this example: + +```shell +kubectl apply -f https://k8s.io/examples/podpreset/preset.yaml +``` + +Here is the manifest for the second PodPreset: {{< codenew file="podpreset/proxy.yaml" >}} -**Pod spec after admission controller:** +Create the second preset: + +```shell +kubectl apply -f https://k8s.io/examples/podpreset/proxy.yaml +``` + +Here's a manifest containing the definition of an applicable Pod (matched by two PodPresets): + +{{< codenew file="podpreset/pod.yaml" >}} + +Create the Pod: + +```shell +kubectl create -f https://k8s.io/examples/podpreset/pod.yaml +``` + +View the Pod spec altered by the admission controller in order to see the effects of both presets +having been applied: + +```shell +kubectl get pod website -o yaml +``` {{< codenew file="podpreset/multi-merged.yaml" >}} -## Conflict Example +The `DB_PORT` environment variable, the `proxy-volume` VolumeMount and the two `podpreset.admission.kubernetes.io` +annotations of the Pod verify that both presets have been applied. -This is an example to show how a Pod spec is not modified by the Pod Preset -when there is a conflict. +## Conflict example -**User submitted pod spec:** +This is an example to show how a Pod spec is not modified by a Pod preset when there is a conflict. +The conflict in this example consists of a `VolumeMount` in the PodPreset conflicting with a Pod that defines the same `mountPath`. -{{< codenew file="podpreset/conflict-pod.yaml" >}} - -**Example Pod Preset:** +Here is the manifest for the PodPreset: {{< codenew file="podpreset/conflict-preset.yaml" >}} -**Pod spec after admission controller will not change because of the conflict:** +Note the `mountPath` value of `/cache`. + +Create the preset: + +```shell +kubectl apply -f https://k8s.io/examples/podpreset/conflict-preset.yaml +``` + +Here is the manifest for the Pod: {{< codenew file="podpreset/conflict-pod.yaml" >}} -**If we run `kubectl describe...` we can see the event:** +Note the volumeMount element with the same path as in the PodPreset. + +Create the Pod: ```shell -kubectl describe ... -``` -``` -.... -Events: - FirstSeen LastSeen Count From SubobjectPath Reason Message - Tue, 07 Feb 2017 16:56:12 -0700 Tue, 07 Feb 2017 16:56:12 -0700 1 {podpreset.admission.kubernetes.io/podpreset-allow-database } conflict Conflict on pod preset. Duplicate mountPath /cache. +kubectl create -f https://k8s.io/examples/podpreset/conflict-pod.yaml ``` -## Deleting a Pod Preset +View the Pod spec: -Once you don't need a pod preset anymore, you can delete it with `kubectl`: +```shell +kubectl get pod website -o yaml +``` + +{{< codenew file="podpreset/conflict-pod.yaml" >}} + +You can see there is no preset annotation (`podpreset.admission.kubernetes.io`). Seeing no annotation tells you that no preset has not been applied to the Pod. + +However, the +[PodPreset admission controller](https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#podpreset) +logs a warning containing details of the conflict. +You can view the warning using `kubectl`: + +```shell +kubectl -n kube-system logs -l=component=kube-apiserver +``` + +The output should look similar to: + +``` +W1214 13:00:12.987884 1 admission.go:147] conflict occurred while applying podpresets: allow-database on pod: err: merging volume mounts for allow-database has a conflict on mount path /cache: +v1.VolumeMount{Name:"other-volume", ReadOnly:false, MountPath:"/cache", SubPath:"", MountPropagation:(*v1.MountPropagationMode)(nil), SubPathExpr:""} +does not match +core.VolumeMount{Name:"cache-volume", ReadOnly:false, MountPath:"/cache", SubPath:"", MountPropagation:(*core.MountPropagationMode)(nil), SubPathExpr:""} + in container +``` + +Note the conflict message on the path for the VolumeMount. + +## Deleting a PodPreset + +Once you don't need a PodPreset anymore, you can delete it with `kubectl`: ```shell kubectl delete podpreset allow-database ``` +The output shows that the PodPreset was deleted: ``` podpreset "allow-database" deleted ``` diff --git a/content/en/docs/tasks/manage-daemon/update-daemon-set.md b/content/en/docs/tasks/manage-daemon/update-daemon-set.md index 0c1a5472b6..ab98f2ea4e 100644 --- a/content/en/docs/tasks/manage-daemon/update-daemon-set.md +++ b/content/en/docs/tasks/manage-daemon/update-daemon-set.md @@ -33,7 +33,7 @@ DaemonSet has two update strategy types: * RollingUpdate: This is the default update strategy. With `RollingUpdate` update strategy, after you update a DaemonSet template, old DaemonSet pods will be killed, and new DaemonSet pods - will be created automatically, in a controlled fashion. + will be created automatically, in a controlled fashion. At most one pod of the DaemonSet will be running on each node during the whole update process. ## Performing a Rolling Update diff --git a/content/en/docs/tasks/manage-kubernetes-objects/declarative-config.md b/content/en/docs/tasks/manage-kubernetes-objects/declarative-config.md index 0dee8eb60a..70b5af9df1 100644 --- a/content/en/docs/tasks/manage-kubernetes-objects/declarative-config.md +++ b/content/en/docs/tasks/manage-kubernetes-objects/declarative-config.md @@ -119,7 +119,7 @@ metadata: {"apiVersion":"apps/v1","kind":"Deployment", "metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"}, "spec":{"minReadySeconds":5,"selector":{"matchLabels":{"app":nginx}},"template":{"metadata":{"labels":{"app":"nginx"}}, - "spec":{"containers":[{"image":"nginx:1.7.9","name":"nginx", + "spec":{"containers":[{"image":"nginx:1.14.2","name":"nginx", "ports":[{"containerPort":80}]}]}}}} # ... spec: @@ -136,7 +136,7 @@ spec: app: nginx spec: containers: - - image: nginx:1.7.9 + - image: nginx:1.14.2 # ... name: nginx ports: @@ -199,7 +199,7 @@ metadata: {"apiVersion":"apps/v1","kind":"Deployment", "metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"}, "spec":{"minReadySeconds":5,"selector":{"matchLabels":{"app":nginx}},"template":{"metadata":{"labels":{"app":"nginx"}}, - "spec":{"containers":[{"image":"nginx:1.7.9","name":"nginx", + "spec":{"containers":[{"image":"nginx:1.14.2","name":"nginx", "ports":[{"containerPort":80}]}]}}}} # ... spec: @@ -216,7 +216,7 @@ spec: app: nginx spec: containers: - - image: nginx:1.7.9 + - image: nginx:1.14.2 # ... name: nginx ports: @@ -255,7 +255,7 @@ metadata: {"apiVersion":"apps/v1","kind":"Deployment", "metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"}, "spec":{"minReadySeconds":5,"selector":{"matchLabels":{"app":nginx}},"template":{"metadata":{"labels":{"app":"nginx"}}, - "spec":{"containers":[{"image":"nginx:1.7.9","name":"nginx", + "spec":{"containers":[{"image":"nginx:1.14.2","name":"nginx", "ports":[{"containerPort":80}]}]}}}} # ... spec: @@ -273,7 +273,7 @@ spec: app: nginx spec: containers: - - image: nginx:1.7.9 + - image: nginx:1.14.2 # ... name: nginx ports: @@ -282,7 +282,7 @@ spec: ``` Update the `simple_deployment.yaml` configuration file to change the image from -`nginx:1.7.9` to `nginx:1.11.9`, and delete the `minReadySeconds` field: +`nginx:1.14.2` to `nginx:1.16.1`, and delete the `minReadySeconds` field: {{< codenew file="application/update_deployment.yaml" >}} @@ -303,7 +303,7 @@ The output shows the following changes to the live configuration: * The `replicas` field retains the value of 2 set by `kubectl scale`. This is possible because it is omitted from the configuration file. -* The `image` field has been updated to `nginx:1.11.9` from `nginx:1.7.9`. +* The `image` field has been updated to `nginx:1.16.1` from `nginx:1.14.2`. * The `last-applied-configuration` annotation has been updated with the new image. * The `minReadySeconds` field has been cleared. * The `last-applied-configuration` annotation no longer contains the `minReadySeconds` field. @@ -320,7 +320,7 @@ metadata: {"apiVersion":"apps/v1","kind":"Deployment", "metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"}, "spec":{"selector":{"matchLabels":{"app":nginx}},"template":{"metadata":{"labels":{"app":"nginx"}}, - "spec":{"containers":[{"image":"nginx:1.11.9","name":"nginx", + "spec":{"containers":[{"image":"nginx:1.16.1","name":"nginx", "ports":[{"containerPort":80}]}]}}}} # ... spec: @@ -338,7 +338,7 @@ spec: app: nginx spec: containers: - - image: nginx:1.11.9 # Set by `kubectl apply` + - image: nginx:1.16.1 # Set by `kubectl apply` # ... name: nginx ports: @@ -460,7 +460,7 @@ metadata: {"apiVersion":"apps/v1","kind":"Deployment", "metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"}, "spec":{"minReadySeconds":5,"selector":{"matchLabels":{"app":nginx}},"template":{"metadata":{"labels":{"app":"nginx"}}, - "spec":{"containers":[{"image":"nginx:1.7.9","name":"nginx", + "spec":{"containers":[{"image":"nginx:1.14.2","name":"nginx", "ports":[{"containerPort":80}]}]}}}} # ... spec: @@ -478,7 +478,7 @@ spec: app: nginx spec: containers: - - image: nginx:1.7.9 + - image: nginx:1.14.2 # ... name: nginx ports: @@ -518,7 +518,7 @@ metadata: {"apiVersion":"apps/v1","kind":"Deployment", "metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"}, "spec":{"selector":{"matchLabels":{"app":nginx}},"template":{"metadata":{"labels":{"app":"nginx"}}, - "spec":{"containers":[{"image":"nginx:1.11.9","name":"nginx", + "spec":{"containers":[{"image":"nginx:1.16.1","name":"nginx", "ports":[{"containerPort":80}]}]}}}} # ... spec: @@ -536,7 +536,7 @@ spec: app: nginx spec: containers: - - image: nginx:1.11.9 # Set by `kubectl apply` + - image: nginx:1.16.1 # Set by `kubectl apply` # ... name: nginx ports: @@ -654,7 +654,7 @@ by `name`. # last-applied-configuration value containers: - name: nginx - image: nginx:1.10 + image: nginx:1.16 - name: nginx-helper-a # key: nginx-helper-a; will be deleted in result image: helper:1.3 - name: nginx-helper-b # key: nginx-helper-b; will be retained @@ -663,7 +663,7 @@ by `name`. # configuration file value containers: - name: nginx - image: nginx:1.10 + image: nginx:1.16 - name: nginx-helper-b image: helper:1.3 - name: nginx-helper-c # key: nginx-helper-c; will be added in result @@ -672,7 +672,7 @@ by `name`. # live configuration containers: - name: nginx - image: nginx:1.10 + image: nginx:1.16 - name: nginx-helper-a image: helper:1.3 - name: nginx-helper-b @@ -684,7 +684,7 @@ by `name`. # result after merge containers: - name: nginx - image: nginx:1.10 + image: nginx:1.16 # Element nginx-helper-a was deleted - name: nginx-helper-b image: helper:1.3 @@ -779,7 +779,7 @@ spec: app: nginx spec: containers: - - image: nginx:1.7.9 + - image: nginx:1.14.2 imagePullPolicy: IfNotPresent # defaulted by apiserver name: nginx ports: @@ -819,7 +819,7 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 @@ -834,7 +834,7 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 @@ -852,7 +852,7 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 @@ -870,7 +870,7 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 ``` diff --git a/content/en/docs/tasks/run-application/configure-pdb.md b/content/en/docs/tasks/run-application/configure-pdb.md index 673823feb7..d33dc24364 100644 --- a/content/en/docs/tasks/run-application/configure-pdb.md +++ b/content/en/docs/tasks/run-application/configure-pdb.md @@ -180,8 +180,8 @@ then you'll see something like this: kubectl get poddisruptionbudgets ``` ``` -NAME MIN-AVAILABLE ALLOWED-DISRUPTIONS AGE -zk-pdb 2 0 7s +NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE +zk-pdb 2 N/A 0 7s ``` If there are matching pods (say, 3), then you would see something like this: @@ -190,11 +190,11 @@ If there are matching pods (say, 3), then you would see something like this: kubectl get poddisruptionbudgets ``` ``` -NAME MIN-AVAILABLE ALLOWED-DISRUPTIONS AGE -zk-pdb 2 1 7s +NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE +zk-pdb 2 N/A 1 7s ``` -The non-zero value for `ALLOWED-DISRUPTIONS` means that the disruption controller has seen the pods, +The non-zero value for `ALLOWED DISRUPTIONS` means that the disruption controller has seen the pods, counted the matching pods, and updated the status of the PDB. You can get more information about the status of a PDB with this command: @@ -206,14 +206,15 @@ kubectl get poddisruptionbudgets zk-pdb -o yaml apiVersion: policy/v1beta1 kind: PodDisruptionBudget metadata: - creationTimestamp: 2017-08-28T02:38:26Z + annotations: +… + creationTimestamp: "2020-03-04T04:22:56Z" generation: 1 name: zk-pdb … status: currentHealthy: 3 - desiredHealthy: 3 - disruptedPods: null + desiredHealthy: 2 disruptionsAllowed: 1 expectedPods: 3 observedGeneration: 1 diff --git a/content/en/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough.md b/content/en/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough.md index 6a9fe4de32..800abfea69 100644 --- a/content/en/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough.md +++ b/content/en/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough.md @@ -369,8 +369,8 @@ label, you can specify the following metric block to scale only on GET requests: type: Object object: metric: - name: `http_requests` - selector: `verb=GET` + name: http_requests + selector: {matchLabels: {verb: GET}} ``` This selector uses the same syntax as the full Kubernetes label selectors. The monitoring pipeline diff --git a/content/en/docs/tasks/run-application/horizontal-pod-autoscale.md b/content/en/docs/tasks/run-application/horizontal-pod-autoscale.md index e515206308..3ed6fa0e41 100644 --- a/content/en/docs/tasks/run-application/horizontal-pod-autoscale.md +++ b/content/en/docs/tasks/run-application/horizontal-pod-autoscale.md @@ -178,6 +178,8 @@ The beta version, which includes support for scaling on memory and custom metric can be found in `autoscaling/v2beta2`. The new fields introduced in `autoscaling/v2beta2` are preserved as annotations when working with `autoscaling/v1`. +When you create a HorizontalPodAutoscaler API object, make sure the name specified is a valid +[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names). More details about the API object can be found at [HorizontalPodAutoscaler Object](https://git.k8s.io/community/contributors/design-proposals/autoscaling/horizontal-pod-autoscaler.md#horizontalpodautoscaler-object). diff --git a/content/en/docs/tasks/run-application/rolling-update-replication-controller.md b/content/en/docs/tasks/run-application/rolling-update-replication-controller.md index e70877a9d4..11df107b24 100644 --- a/content/en/docs/tasks/run-application/rolling-update-replication-controller.md +++ b/content/en/docs/tasks/run-application/rolling-update-replication-controller.md @@ -153,14 +153,14 @@ from the [`kubectl` reference](/docs/reference/generated/kubectl/kubectl-command ## Walkthrough -Let's say you were running version 1.7.9 of nginx: +Let's say you were running version 1.14.2 of nginx: -{{< codenew file="controllers/replication-nginx-1.7.9.yaml" >}} +{{< codenew file="controllers/replication-nginx-1.14.2.yaml" >}} -To update to version 1.9.1, you can use [`kubectl rolling-update --image`](https://git.k8s.io/community/contributors/design-proposals/cli/simple-rolling-update.md) to specify the new image: +To update to version 1.16.1, you can use [`kubectl rolling-update --image`](https://git.k8s.io/community/contributors/design-proposals/cli/simple-rolling-update.md) to specify the new image: ```shell -kubectl rolling-update my-nginx --image=nginx:1.9.1 +kubectl rolling-update my-nginx --image=nginx:1.16.1 ``` ``` Created my-nginx-ccba8fbd8cc8160970f63f9a2696fc46 @@ -213,7 +213,7 @@ This is one example where the immutability of containers is a huge asset. If you need to update more than just the image (e.g., command arguments, environment variables), you can create a new replication controller, with a new name and distinguishing label value, such as: -{{< codenew file="controllers/replication-nginx-1.9.2.yaml" >}} +{{< codenew file="controllers/replication-nginx-1.16.1.yaml" >}} and roll it out: diff --git a/content/en/docs/tasks/run-application/run-stateless-application-deployment.md b/content/en/docs/tasks/run-application/run-stateless-application-deployment.md index 5da19f0c25..c9e0aebd51 100644 --- a/content/en/docs/tasks/run-application/run-stateless-application-deployment.md +++ b/content/en/docs/tasks/run-application/run-stateless-application-deployment.md @@ -34,7 +34,7 @@ This page shows how to run an application using a Kubernetes Deployment object. You can run an application by creating a Kubernetes Deployment object, and you can describe a Deployment in a YAML file. For example, this YAML file describes -a Deployment that runs the nginx:1.7.9 Docker image: +a Deployment that runs the nginx:1.14.2 Docker image: {{< codenew file="application/deployment.yaml" >}} @@ -64,7 +64,7 @@ a Deployment that runs the nginx:1.7.9 Docker image: Labels: app=nginx Containers: nginx: - Image: nginx:1.7.9 + Image: nginx:1.14.2 Port: 80/TCP Environment: Mounts: diff --git a/content/en/docs/tasks/tools/install-kubectl.md b/content/en/docs/tasks/tools/install-kubectl.md index 4a799e5f01..83c9d1761b 100644 --- a/content/en/docs/tasks/tools/install-kubectl.md +++ b/content/en/docs/tasks/tools/install-kubectl.md @@ -385,6 +385,27 @@ However, the kubectl completion script depends on [**bash-completion**](https:// there are two versions of bash-completion, v1 and v2. V1 is for Bash 3.2 (which is the default on macOS), and v2 is for Bash 4.1+. The kubectl completion script **doesn't work** correctly with bash-completion v1 and Bash 3.2. It requires **bash-completion v2** and **Bash 4.1+**. Thus, to be able to correctly use kubectl completion on macOS, you have to install and use Bash 4.1+ ([*instructions*](https://itnext.io/upgrading-bash-on-macos-7138bd1066ba)). The following instructions assume that you use Bash 4.1+ (that is, any Bash version of 4.1 or newer). {{< /warning >}} +### Upgrade Bash + +The instructions here assume you use Bash 4.1+. You can check your Bash's version by running: + +```shell +echo $BASH_VERSION +``` + +If it is too old, you can install/upgrade it using Homebrew: + +```shell +brew install bash +``` + +Reload your shell and verify that the desired version is being used: + +```shell +echo $BASH_VERSION $SHELL +``` + +Homebrew usually installs it at `/usr/local/bin/bash`. ### Install bash-completion diff --git a/content/en/docs/tasks/tools/install-minikube.md b/content/en/docs/tasks/tools/install-minikube.md index 03c3b07cd5..b106c23ef6 100644 --- a/content/en/docs/tasks/tools/install-minikube.md +++ b/content/en/docs/tasks/tools/install-minikube.md @@ -86,6 +86,12 @@ The `none` VM driver can result in security and data loss issues. Before using `--vm-driver=none`, consult [this documentation](https://minikube.sigs.k8s.io/docs/reference/drivers/none/) for more information. {{< /caution >}} +Minikube also supports a `vm-driver=podman` similar to the Docker driver. Podman run as superuser privilege (root user) is the best way to ensure that your containers have full access to any feature available on your system. + +{{< caution >}} +The `podman` driver requires running the containers as root because regular user accounts don’t have full access to all operating system features that their containers might need to run. +{{< /caution >}} + ### Install Minikube using a package There are *experimental* packages for Minikube available; you can find Linux (AMD64) packages diff --git a/content/en/docs/tutorials/_index.md b/content/en/docs/tutorials/_index.md index 04013216c3..9f8de2129e 100644 --- a/content/en/docs/tutorials/_index.md +++ b/content/en/docs/tutorials/_index.md @@ -22,8 +22,6 @@ Before walking through each tutorial, you may want to bookmark the * [Kubernetes Basics](/docs/tutorials/kubernetes-basics/) is an in-depth interactive tutorial that helps you understand the Kubernetes system and try out some basic Kubernetes features. -* [Scalable Microservices with Kubernetes (Udacity)](https://www.udacity.com/course/scalable-microservices-with-kubernetes--ud615) - * [Introduction to Kubernetes (edX)](https://www.edx.org/course/introduction-kubernetes-linuxfoundationx-lfs158x#) * [Hello Minikube](/docs/tutorials/hello-minikube/) diff --git a/content/en/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro.html b/content/en/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro.html index 2a6af0af4c..13d3d99758 100644 --- a/content/en/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro.html +++ b/content/en/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro.html @@ -77,7 +77,7 @@ weight: 10
-

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

+

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

diff --git a/content/en/docs/tutorials/kubernetes-basics/deploy-app/deploy-interactive.html b/content/en/docs/tutorials/kubernetes-basics/deploy-app/deploy-interactive.html index 7636f8ea94..6d7e15a7c4 100644 --- a/content/en/docs/tutorials/kubernetes-basics/deploy-app/deploy-interactive.html +++ b/content/en/docs/tutorials/kubernetes-basics/deploy-app/deploy-interactive.html @@ -17,6 +17,14 @@ weight: 20
+
+
+

+ A Pod is the basic execution unit of a Kubernetes application. Each Pod represents a part of a workload that is running on your cluster. Learn more about Pods. +

+
+
+
diff --git a/content/en/docs/tutorials/kubernetes-basics/expose/expose-intro.html b/content/en/docs/tutorials/kubernetes-basics/expose/expose-intro.html index 8adf05965b..8a7d60dd87 100644 --- a/content/en/docs/tutorials/kubernetes-basics/expose/expose-intro.html +++ b/content/en/docs/tutorials/kubernetes-basics/expose/expose-intro.html @@ -79,13 +79,8 @@ weight: 10
  • Embed version tags
  • Classify an object using tags
  • - -
    -
    -
    -

    You can create a Service at the same time you create a Deployment by using
    --expose in kubectl.

    -
    +

    diff --git a/content/en/docs/tutorials/online-training/_index.md b/content/en/docs/tutorials/online-training/_index.md deleted file mode 100755 index 9b4b09f17f..0000000000 --- a/content/en/docs/tutorials/online-training/_index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: "Online Training Courses" -weight: 20 ---- - diff --git a/content/en/docs/tutorials/online-training/overview.md b/content/en/docs/tutorials/online-training/overview.md deleted file mode 100644 index e76b22481a..0000000000 --- a/content/en/docs/tutorials/online-training/overview.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Overview of Kubernetes Online Training -content_template: templates/concept ---- - -{{% capture overview %}} - -Here are some of the sites that offer online training for Kubernetes: - -{{% /capture %}} - -{{% capture body %}} - -* [AIOps Essentials (Autoscaling Kubernetes with Prometheus Metrics) with Hands-On Labs (Linux Academy)](https://linuxacademy.com/devops/training/course/name/using-machine-learning-to-scale-kubernetes-clusters) - -* [Amazon EKS Deep Dive with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/amazon-web-services/training/course/name/amazon-eks-deep-dive) - -* [Cloud Native Certified Kubernetes Administrator (CKA) with Hands-On Labs & Practice Exams (Linux Academy)](https://linuxacademy.com/linux/training/course/name/cloud-native-certified-kubernetes-administrator-cka) - -* [Certified Kubernetes Administrator (CKA) Preparation Course (CloudYuga)](https://cloudyuga.guru/courses/cka-online-self-paced) - -* [Certified Kubernetes Administrator Preparation Course with Practice Tests (KodeKloud)](https://kodekloud.com/p/certified-kubernetes-administrator-with-practice-tests) - -* [Certified Kubernetes Application Developer (CKAD) with Hands-On Labs & Practice Exams (Linux Academy)] (https://linuxacademy.com/containers/training/course/name/certified-kubernetes-application-developer-ckad/) - -* [Certified Kubernetes Application Developer (CKAD) Preparation Course (CloudYuga)](https://cloudyuga.guru/courses/ckad-online-self-paced) - -* [Certified Kubernetes Application Developer Preparation Course with Practice Tests (KodeKloud)](https://kodekloud.com/p/kubernetes-certification-course) - -* [Getting Started with Google Kubernetes Engine (Coursera)](https://www.coursera.org/learn/google-kubernetes-engine) - -* [Getting Started with Kubernetes (Pluralsight)](https://www.pluralsight.com/courses/getting-started-kubernetes) - -* [Getting Started with Kubernetes Clusters on OCI Oracle Kubernetes Engine (OKE) (Learning Library)](https://apexapps.oracle.com/pls/apex/f?p=44785:50:0:::50:P50_EVENT_ID,P50_COURSE_ID:5935,256) - -* [Google Kubernetes Engine Deep Dive (Linux Academy)] (https://linuxacademy.com/google-cloud-platform/training/course/name/google-kubernetes-engine-deep-dive) - -* [Helm Deep Dive with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/helm-deep-dive-part-1) - -* [Hands-on Introduction to Kubernetes (Instruqt)](https://play.instruqt.com/public/topics/getting-started-with-kubernetes) - -* [Introduction to Kubernetes (edX)](https://www.edx.org/course/introduction-kubernetes-linuxfoundationx-lfs158x) - -* [Kubernetes Essentials with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/kubernetes-essentials) - -* [Kubernetes for the Absolute Beginners with Hands-on Labs (KodeKloud)](https://kodekloud.com/p/kubernetes-for-the-absolute-beginners-hands-on) - -* [Kubernetes Fundamentals (LFS258) (The Linux Foundation)](https://training.linuxfoundation.org/training/kubernetes-fundamentals/) - -* [Kubernetes Quick Start with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/kubernetes-quick-start) - -* [Kubernetes the Hard Way with Hands-On Labs (Linux Academy)](https://linuxacademy.com/linux/training/course/name/kubernetes-the-hard-way) - -* [Kubernetes Security with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/kubernetes-security) - -* [Launch Your First OpenShift Operator with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/containers/training/course/name/red-hat-open-shift) - -* [Learn Kubernetes by Doing - 100% Hands-On Experience (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/learn-kubernetes-by-doing) - -* [Learn Kubernetes using Interactive Hands-on Scenarios (Katacoda)](https://www.katacoda.com/courses/kubernetes/) - -* [Microservice Applications in Kubernetes - 100% Hands-On Experience (Linux Academy)] (https://linuxacademy.com/devops/training/course/name/learn-microservices-by-doing) - -* [Monitoring Kubernetes With Prometheus with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/kubernetes-and-prometheus) - -* [Service Mesh with Istio with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/service-mesh-with-istio-part-1) - -* [Scalable Microservices with Kubernetes (Udacity)](https://www.udacity.com/course/scalable-microservices-with-kubernetes--ud615) - -* [Self-paced Kubernetes online course (Learnk8s Academy)](https://learnk8s.io/academy) -{{% /capture %}} diff --git a/content/en/docs/tutorials/services/source-ip.md b/content/en/docs/tutorials/services/source-ip.md index e1b4876a24..ca3a2bb409 100644 --- a/content/en/docs/tutorials/services/source-ip.md +++ b/content/en/docs/tutorials/services/source-ip.md @@ -1,6 +1,7 @@ --- title: Using Source IP content_template: templates/tutorial +min-kubernetes-server-version: v1.5 --- {{% capture overview %}} @@ -14,26 +15,38 @@ of Services, and how you can toggle this behavior according to your needs. {{% capture prerequisites %}} -{{< include "task-tutorial-prereqs.md" >}} {{< version-check >}} - -## Terminology +### Terminology This document makes use of the following terms: -* [NAT](https://en.wikipedia.org/wiki/Network_address_translation): network address translation -* [Source NAT](https://en.wikipedia.org/wiki/Network_address_translation#SNAT): replacing the source IP on a packet, usually with a node's IP -* [Destination NAT](https://en.wikipedia.org/wiki/Network_address_translation#DNAT): replacing the destination IP on a packet, usually with a pod IP -* [VIP](/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies): a virtual IP, such as the one assigned to every Kubernetes Service -* [Kube-proxy](/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies): a network daemon that orchestrates Service VIP management on every node +{{< comment >}} +If localizing this section, link to the equivalent Wikipedia pages for +the target localization. +{{< /comment >}} +[NAT](https://en.wikipedia.org/wiki/Network_address_translation) +: network address translation -## Prerequisites +[Source NAT](https://en.wikipedia.org/wiki/Network_address_translation#SNAT) +: replacing the source IP on a packet; in this page, that usually means replacing with the IP address of a node. -You must have a working Kubernetes 1.5 cluster to run the examples in this -document. The examples use a small nginx webserver that echoes back the source +[Destination NAT](https://en.wikipedia.org/wiki/Network_address_translation#DNAT) +: replacing the destination IP on a packet; in this page, that usually means replacing with the IP address of a {{< glossary_tooltip term_id="pod" >}} + +[VIP](/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies) +: a virtual IP address, such as the one assigned to every {{< glossary_tooltip text="Service" term_id="service" >}} in Kubernetes + +[kube-proxy](/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies) +: a network daemon that orchestrates Service VIP management on every node + +### Prerequisites + +{{< include "task-tutorial-prereqs.md" >}} + +The examples use a small nginx webserver that echoes back the source IP of requests it receives through an HTTP header. You can create it as follows: -```console +```shell kubectl create deployment source-ip-app --image=k8s.gcr.io/echoserver:1.4 ``` The output is: @@ -54,12 +67,13 @@ deployment.apps/source-ip-app created {{% capture lessoncontent %}} -## Source IP for Services with Type=ClusterIP +## Source IP for Services with `Type=ClusterIP` Packets sent to ClusterIP from within the cluster are never source NAT'd if -you're running kube-proxy in [iptables mode](/docs/concepts/services-networking/service/#proxy-mode-iptables), -which is the default since Kubernetes 1.2. Kube-proxy exposes its mode through -a `proxyMode` endpoint: +you're running kube-proxy in +[iptables mode](/docs/concepts/services-networking/service/#proxy-mode-iptables), +(the default). You can query the kube-proxy mode by fetching +`http://localhost:10249/proxyMode` on the node where kube-proxy is running. ```console kubectl get nodes @@ -71,9 +85,11 @@ kubernetes-node-6jst Ready 2h v1.13.0 kubernetes-node-cx31 Ready 2h v1.13.0 kubernetes-node-jj1t Ready 2h v1.13.0 ``` -Get the proxy mode on one of the node -```console -kubernetes-node-6jst $ curl localhost:10249/proxyMode + +Get the proxy mode on one of the nodes (kube-proxy listens on port 10249): +```shell +# Run this in a shell on the node you want to query. +curl http://localhost:10249/proxyMode ``` The output is: ``` @@ -82,14 +98,14 @@ iptables You can test source IP preservation by creating a Service over the source IP app: -```console +```shell kubectl expose deployment source-ip-app --name=clusterip --port=80 --target-port=8080 ``` The output is: ``` service/clusterip exposed ``` -```console +```shell kubectl get svc clusterip ``` The output is similar to: @@ -100,7 +116,7 @@ clusterip ClusterIP 10.0.170.92 80/TCP 51s And hitting the `ClusterIP` from a pod in the same cluster: -```console +```shell kubectl run busybox -it --image=busybox --restart=Never --rm ``` The output is similar to this: @@ -108,7 +124,14 @@ The output is similar to this: Waiting for pod default/busybox to be running, status is Pending, pod ready: false If you don't see a command prompt, try pressing enter. -# ip addr +``` +You can then run a command inside that Pod: + +```shell +# Run this inside the terminal from "kubectl run" +ip addr +``` +``` 1: lo: mtu 65536 qdisc noqueue link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo @@ -121,21 +144,28 @@ If you don't see a command prompt, try pressing enter. valid_lft forever preferred_lft forever inet6 fe80::188a:84ff:feb0:26a5/64 scope link valid_lft forever preferred_lft forever +``` -# wget -qO - 10.0.170.92 +…then use `wget` to query the local webserver +```shell +# Replace 10.0.170.92 with the Pod's IPv4 address +wget -qO - 10.0.170.92 +``` +``` CLIENT VALUES: client_address=10.244.3.8 command=GET ... ``` -The client_address is always the client pod's IP address, whether the client pod and server pod are in the same node or in different nodes. +The `client_address` is always the client pod's IP address, whether the client pod and server pod are in the same node or in different nodes. -## Source IP for Services with Type=NodePort +## Source IP for Services with `Type=NodePort` -As of Kubernetes 1.5, packets sent to Services with [Type=NodePort](/docs/concepts/services-networking/service/#nodeport) +Packets sent to Services with +[`Type=NodePort`](/docs/concepts/services-networking/service/#nodeport) are source NAT'd by default. You can test this by creating a `NodePort` Service: -```console +```shell kubectl expose deployment source-ip-app --name=nodeport --port=80 --target-port=8080 --type=NodePort ``` The output is: @@ -143,17 +173,17 @@ The output is: service/nodeport exposed ``` -```console +```shell NODEPORT=$(kubectl get -o jsonpath="{.spec.ports[0].nodePort}" services nodeport) NODES=$(kubectl get nodes -o jsonpath='{ $.items[*].status.addresses[?(@.type=="ExternalIP")].address }') ``` -If you're running on a cloudprovider, you may need to open up a firewall-rule +If you're running on a cloud provider, you may need to open up a firewall-rule for the `nodes:nodeport` reported above. Now you can try reaching the Service from outside the cluster through the node port allocated above. -```console +```shell for node in $NODES; do curl -s $node:$NODEPORT | grep -i client_address; done ``` The output is similar to: @@ -187,18 +217,19 @@ Visually: ``` -To avoid this, Kubernetes has a feature to preserve the client source IP -[(check here for feature availability)](/docs/tasks/access-application-cluster/create-external-load-balancer/#preserving-the-client-source-ip). -Setting `service.spec.externalTrafficPolicy` to the value `Local` will only -proxy requests to local endpoints, never forwarding traffic to other nodes -and thereby preserving the original source IP address. If there are no -local endpoints, packets sent to the node are dropped, so you can rely -on the correct source-ip in any packet processing rules you might apply a -packet that make it through to the endpoint. +To avoid this, Kubernetes has a feature to +[preserve the client source IP](/docs/tasks/access-application-cluster/create-external-load-balancer/#preserving-the-client-source-ip). +If you set `service.spec.externalTrafficPolicy` to the value `Local`, +kube-proxy only proxies proxy requests to local endpoints, and does not +forward traffic to other nodes. This approach preserves the original +source IP address. If there are no local endpoints, packets sent to the +node are dropped, so you can rely on the correct source-ip in any packet +processing rules you might apply a packet that make it through to the +endpoint. Set the `service.spec.externalTrafficPolicy` field as follows: -```console +```shell kubectl patch svc nodeport -p '{"spec":{"externalTrafficPolicy":"Local"}}' ``` The output is: @@ -208,12 +239,12 @@ service/nodeport patched Now, re-run the test: -```console +```shell for node in $NODES; do curl --connect-timeout 1 -s $node:$NODEPORT | grep -i client_address; done ``` -The output is: +The output is similar to: ``` -client_address=104.132.1.79 +client_address=198.51.100.79 ``` Note that you only got one reply, with the *right* client IP, from the one node on which the endpoint pod @@ -242,18 +273,19 @@ Visually: -## Source IP for Services with Type=LoadBalancer +## Source IP for Services with `Type=LoadBalancer` -As of Kubernetes 1.5, packets sent to Services with [Type=LoadBalancer](/docs/concepts/services-networking/service/#loadbalancer) are -source NAT'd by default, because all schedulable Kubernetes nodes in the -`Ready` state are eligible for loadbalanced traffic. So if packets arrive +Packets sent to Services with +[`Type=LoadBalancer`](/docs/concepts/services-networking/service/#loadbalancer) +are source NAT'd by default, because all schedulable Kubernetes nodes in the +`Ready` state are eligible for load-balanced traffic. So if packets arrive at a node without an endpoint, the system proxies it to a node *with* an endpoint, replacing the source IP on the packet with the IP of the node (as described in the previous section). -You can test this by exposing the source-ip-app through a loadbalancer +You can test this by exposing the source-ip-app through a load balancer: -```console +```shell kubectl expose deployment source-ip-app --name=loadbalancer --port=80 --target-port=8080 --type=LoadBalancer ``` The output is: @@ -261,18 +293,20 @@ The output is: service/loadbalancer exposed ``` -Print IPs of the Service: +Print out the IP addresses of the Service: ```console kubectl get svc loadbalancer ``` The output is similar to this: ``` NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE -loadbalancer LoadBalancer 10.0.65.118 104.198.149.140 80/TCP 5m +loadbalancer LoadBalancer 10.0.65.118 203.0.113.140 80/TCP 5m ``` -```console -curl 104.198.149.140 +Next, send a request to this Service's external-ip: + +```shell +curl 203.0.113.140 ``` The output is similar to this: ``` @@ -302,25 +336,25 @@ health check ---> node 1 node 2 <--- health check You can test this by setting the annotation: -```console +```shell kubectl patch svc loadbalancer -p '{"spec":{"externalTrafficPolicy":"Local"}}' ``` You should immediately see the `service.spec.healthCheckNodePort` field allocated by Kubernetes: -```console +```shell kubectl get svc loadbalancer -o yaml | grep -i healthCheckNodePort ``` The output is similar to this: -``` +```yaml healthCheckNodePort: 32122 ``` The `service.spec.healthCheckNodePort` field points to a port on every node serving the health check at `/healthz`. You can test this: -```console +```shell kubectl get pod -o wide -l run=source-ip-app ``` The output is similar to this: @@ -328,43 +362,48 @@ The output is similar to this: NAME READY STATUS RESTARTS AGE IP NODE source-ip-app-826191075-qehz4 1/1 Running 0 20h 10.180.1.136 kubernetes-node-6jst ``` -Curl the `/healthz` endpoint on different nodes. -```console -kubernetes-node-6jst $ curl localhost:32122/healthz + +Use `curl` to fetch the `/healthz` endpoint on various nodes: +```shell +# Run this locally on a node you choose +curl localhost:32122/healthz ``` -The output is similar to this: ``` 1 Service Endpoints found ``` -```console -kubernetes-node-jj1t $ curl localhost:32122/healthz + +On a different node you might get a different result: +```shell +# Run this locally on a node you choose +curl localhost:32122/healthz ``` -The output is similar to this: ``` No Service Endpoints Found ``` -A service controller running on the master is responsible for allocating the cloud -loadbalancer, and when it does so, it also allocates HTTP health checks -pointing to this port/path on each node. Wait about 10 seconds for the 2 nodes -without endpoints to fail health checks, then curl the lb ip: +A controller running on the +{{< glossary_tooltip text="control plane" term_id="control-plane" >}} is +responsible for allocating the cloud load balancer. The same controller also +allocates HTTP health checks pointing to this port/path on each node. Wait +about 10 seconds for the 2 nodes without endpoints to fail health checks, +then use `curl` to query the IPv4 address of the load balancer: -```console -curl 104.198.149.140 +```shell +curl 203.0.113.140 ``` The output is similar to this: ``` CLIENT VALUES: -client_address=104.132.1.79 +client_address=198.51.100.79 ... ``` -__Cross platform support__ +## Cross-platform support -As of Kubernetes 1.5, support for source IP preservation through Services -with Type=LoadBalancer is only implemented in a subset of cloudproviders -(GCP and Azure). The cloudprovider you're running on might fulfill the -request for a loadbalancer in a few different ways: +Only some cloud providers offer support for source IP preservation through +Services with `Type=LoadBalancer`. +The cloud provider you're running on might fulfill the request for a loadbalancer +in a few different ways: 1. With a proxy that terminates the client connection and opens a new connection to your nodes/endpoints. In such cases the source IP will always be that of the @@ -374,12 +413,14 @@ cloud LB, not that of the client. loadbalancer VIP end up at the node with the source IP of the client, not an intermediate proxy. -Loadbalancers in the first category must use an agreed upon +Load balancers in the first category must use an agreed upon protocol between the loadbalancer and backend to communicate the true client IP -such as the HTTP [X-FORWARDED-FOR](https://en.wikipedia.org/wiki/X-Forwarded-For) -header, or the [proxy protocol](http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt). -Loadbalancers in the second category can leverage the feature described above -by simply creating an HTTP health check pointing at the port stored in +such as the HTTP [Forwarded](https://tools.ietf.org/html/rfc7239#section-5.2) +or [X-FORWARDED-FOR](https://en.wikipedia.org/wiki/X-Forwarded-For) +headers, or the +[proxy protocol](http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt). +Load balancers in the second category can leverage the feature described above +by creating an HTTP health check pointing at the port stored in the `service.spec.healthCheckNodePort` field on the Service. {{% /capture %}} @@ -388,13 +429,13 @@ the `service.spec.healthCheckNodePort` field on the Service. Delete the Services: -```console +```shell kubectl delete svc -l run=source-ip-app ``` Delete the Deployment, ReplicaSet and Pod: -```console +```shell kubectl delete deployment source-ip-app ``` @@ -402,7 +443,6 @@ kubectl delete deployment source-ip-app {{% capture whatsnext %}} * Learn more about [connecting applications via services](/docs/concepts/services-networking/connect-applications-service/) -* Learn more about [loadbalancing](/docs/user-guide/load-balancer) +* Read how to [Create an External Load Balancer](https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/) {{% /capture %}} - diff --git a/content/en/docs/tutorials/stateless-application/guestbook-logs-metrics-with-elk.md b/content/en/docs/tutorials/stateless-application/guestbook-logs-metrics-with-elk.md index af24c72999..94008289ee 100644 --- a/content/en/docs/tutorials/stateless-application/guestbook-logs-metrics-with-elk.md +++ b/content/en/docs/tutorials/stateless-application/guestbook-logs-metrics-with-elk.md @@ -111,7 +111,7 @@ There are four files to edit to create a k8s secret when you are connecting to s 1. ELASTICSEARCH_USERNAME 1. KIBANA_HOST -Set these with the information for your Elasticsearch cluster and your Kibana host. Here are some examples +Set these with the information for your Elasticsearch cluster and your Kibana host. Here are some examples (also see [*this configuration*](https://stackoverflow.com/questions/59892896/how-to-connect-from-minikube-to-elasticsearch-installed-on-host-local-developme/59892897#59892897)) #### `ELASTICSEARCH_HOSTS` 1. A nodeGroup from the Elastic Elasticsearch Helm Chart: diff --git a/content/en/docs/tutorials/stateless-application/guestbook.md b/content/en/docs/tutorials/stateless-application/guestbook.md index 979a14198a..f1f93dd988 100644 --- a/content/en/docs/tutorials/stateless-application/guestbook.md +++ b/content/en/docs/tutorials/stateless-application/guestbook.md @@ -79,7 +79,7 @@ Replace POD-NAME with the name of your Pod. ### Creating the Redis Master Service -The guestbook applications needs to communicate to the Redis master to write its data. You need to apply a [Service](/docs/concepts/services-networking/service/) to proxy the traffic to the Redis master Pod. A Service defines a policy to access the Pods. +The guestbook application needs to communicate to the Redis master to write its data. You need to apply a [Service](/docs/concepts/services-networking/service/) to proxy the traffic to the Redis master Pod. A Service defines a policy to access the Pods. {{< codenew file="application/guestbook/redis-master-service.yaml" >}} diff --git a/content/en/examples/admin/snowflake-deployment.yaml b/content/en/examples/admin/snowflake-deployment.yaml new file mode 100644 index 0000000000..2f4f267916 --- /dev/null +++ b/content/en/examples/admin/snowflake-deployment.yaml @@ -0,0 +1,20 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app: snowflake + name: snowflake +spec: + replicas: 2 + selector: + matchLabels: + app: snowflake + template: + metadata: + labels: + app: snowflake + spec: + containers: + - image: k8s.gcr.io/serve_hostname + imagePullPolicy: Always + name: snowflake diff --git a/content/en/examples/application/deployment-scale.yaml b/content/en/examples/application/deployment-scale.yaml index 3bdc7b6f5b..68801c971d 100644 --- a/content/en/examples/application/deployment-scale.yaml +++ b/content/en/examples/application/deployment-scale.yaml @@ -14,6 +14,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.8 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/examples/application/deployment-update.yaml b/content/en/examples/application/deployment-update.yaml index 8c683d6dc7..18e8be65fb 100644 --- a/content/en/examples/application/deployment-update.yaml +++ b/content/en/examples/application/deployment-update.yaml @@ -14,6 +14,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.8 # Update the version of nginx from 1.7.9 to 1.8 + image: nginx:1.16.1 # Update the version of nginx from 1.14.2 to 1.16.1 ports: - containerPort: 80 diff --git a/content/en/examples/application/deployment.yaml b/content/en/examples/application/deployment.yaml index 0f526b16c0..2cd599218d 100644 --- a/content/en/examples/application/deployment.yaml +++ b/content/en/examples/application/deployment.yaml @@ -14,6 +14,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/examples/application/nginx-app.yaml b/content/en/examples/application/nginx-app.yaml index c3f926b74e..d00682e1fc 100644 --- a/content/en/examples/application/nginx-app.yaml +++ b/content/en/examples/application/nginx-app.yaml @@ -29,6 +29,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/examples/application/nginx/nginx-deployment.yaml b/content/en/examples/application/nginx/nginx-deployment.yaml index f05bfa3c5f..7f608bc47f 100644 --- a/content/en/examples/application/nginx/nginx-deployment.yaml +++ b/content/en/examples/application/nginx/nginx-deployment.yaml @@ -14,6 +14,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/examples/application/simple_deployment.yaml b/content/en/examples/application/simple_deployment.yaml index 10fa1ddf29..d9c74af8c5 100644 --- a/content/en/examples/application/simple_deployment.yaml +++ b/content/en/examples/application/simple_deployment.yaml @@ -14,6 +14,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/examples/application/update_deployment.yaml b/content/en/examples/application/update_deployment.yaml index d53aa3e6d2..2d7603acb9 100644 --- a/content/en/examples/application/update_deployment.yaml +++ b/content/en/examples/application/update_deployment.yaml @@ -13,6 +13,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.11.9 # update the image + image: nginx:1.16.1 # update the image ports: - containerPort: 80 diff --git a/content/en/examples/controllers/daemonset.yaml b/content/en/examples/controllers/daemonset.yaml index 1bfa082833..f291b750c1 100644 --- a/content/en/examples/controllers/daemonset.yaml +++ b/content/en/examples/controllers/daemonset.yaml @@ -15,6 +15,8 @@ spec: name: fluentd-elasticsearch spec: tolerations: + # this toleration is to have the daemonset runnable on master nodes + # remove it if your masters can't run pods - key: node-role.kubernetes.io/master effect: NoSchedule containers: diff --git a/content/en/examples/controllers/nginx-deployment.yaml b/content/en/examples/controllers/nginx-deployment.yaml index f7f95deebb..685c17aa68 100644 --- a/content/en/examples/controllers/nginx-deployment.yaml +++ b/content/en/examples/controllers/nginx-deployment.yaml @@ -16,6 +16,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/examples/controllers/replication-nginx-1.7.9.yaml b/content/en/examples/controllers/replication-nginx-1.14.2.yaml similarity index 89% rename from content/en/examples/controllers/replication-nginx-1.7.9.yaml rename to content/en/examples/controllers/replication-nginx-1.14.2.yaml index 768ab92ca7..b74bc81547 100644 --- a/content/en/examples/controllers/replication-nginx-1.7.9.yaml +++ b/content/en/examples/controllers/replication-nginx-1.14.2.yaml @@ -11,6 +11,6 @@ spec: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/examples/controllers/replication-nginx-1.9.2.yaml b/content/en/examples/controllers/replication-nginx-1.16.1.yaml similarity index 92% rename from content/en/examples/controllers/replication-nginx-1.9.2.yaml rename to content/en/examples/controllers/replication-nginx-1.16.1.yaml index f92f2657ed..0708cae4b5 100644 --- a/content/en/examples/controllers/replication-nginx-1.9.2.yaml +++ b/content/en/examples/controllers/replication-nginx-1.16.1.yaml @@ -15,7 +15,7 @@ spec: spec: containers: - name: nginx - image: nginx:1.9.2 + image: nginx:1.16.1 args: ["nginx", "-T"] ports: - containerPort: 80 diff --git a/content/en/examples/examples_test.go b/content/en/examples/examples_test.go index ee29c3a68b..7c9664b64c 100644 --- a/content/en/examples/examples_test.go +++ b/content/en/examples/examples_test.go @@ -34,8 +34,6 @@ import ( utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/kubernetes/pkg/api/legacyscheme" "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/admissionregistration" - ar_validation "k8s.io/kubernetes/pkg/apis/admissionregistration/validation" "k8s.io/kubernetes/pkg/apis/apps" apps_validation "k8s.io/kubernetes/pkg/apis/apps/validation" "k8s.io/kubernetes/pkg/apis/autoscaling" @@ -434,12 +432,6 @@ func TestExampleObjectSchemas(t *testing.T) { "node-problem-detector-configmap": {&apps.DaemonSet{}}, "termination": {&api.Pod{}}, }, - "federation": { - "policy-engine-deployment": {&apps.Deployment{}}, - "policy-engine-service": {&api.Service{}}, - "replicaset-example-policy": {&apps.ReplicaSet{}}, - "scheduling-policy-admission": {&api.ConfigMap{}}, - }, "podpreset": { "allow-db": {&settings.PodPreset{}}, "allow-db-merged": {&api.Pod{}}, @@ -525,9 +517,9 @@ func TestExampleObjectSchemas(t *testing.T) { "redis": {&api.Pod{}}, }, "policy": { - "privileged-psp": {&policy.PodSecurityPolicy{}}, - "restricted-psp": {&policy.PodSecurityPolicy{}}, - "example-psp": {&policy.PodSecurityPolicy{}}, + "privileged-psp": {&policy.PodSecurityPolicy{}}, + "restricted-psp": {&policy.PodSecurityPolicy{}}, + "example-psp": {&policy.PodSecurityPolicy{}}, "zookeeper-pod-disruption-budget-maxunavailable": {&policy.PodDisruptionBudget{}}, "zookeeper-pod-disruption-budget-minunavailable": {&policy.PodDisruptionBudget{}}, }, diff --git a/content/en/examples/federation/policy-engine-deployment.yaml b/content/en/examples/federation/policy-engine-deployment.yaml deleted file mode 100644 index 168af7ba4c..0000000000 --- a/content/en/examples/federation/policy-engine-deployment.yaml +++ /dev/null @@ -1,37 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - app: opa - name: opa - namespace: federation-system -spec: - replicas: 1 - selector: - matchLabels: - app: opa - template: - metadata: - labels: - app: opa - name: opa - spec: - containers: - - name: opa - image: openpolicyagent/opa:0.4.10 - args: - - "run" - - "--server" - - name: kube-mgmt - image: openpolicyagent/kube-mgmt:0.2 - args: - - "-kubeconfig=/srv/kubernetes/kubeconfig" - - "-cluster=federation/v1beta1/clusters" - volumeMounts: - - name: federation-kubeconfig - mountPath: /srv/kubernetes - readOnly: true - volumes: - - name: federation-kubeconfig - secret: - secretName: federation-controller-manager-kubeconfig diff --git a/content/en/examples/federation/policy-engine-service.yaml b/content/en/examples/federation/policy-engine-service.yaml deleted file mode 100644 index 982870b06b..0000000000 --- a/content/en/examples/federation/policy-engine-service.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: opa - namespace: federation-system -spec: - selector: - app: opa - ports: - - name: http - protocol: TCP - port: 8181 - targetPort: 8181 diff --git a/content/en/examples/federation/replicaset-example-policy.yaml b/content/en/examples/federation/replicaset-example-policy.yaml deleted file mode 100644 index 43dc83b18b..0000000000 --- a/content/en/examples/federation/replicaset-example-policy.yaml +++ /dev/null @@ -1,21 +0,0 @@ -apiVersion: apps/v1 -kind: ReplicaSet -metadata: - labels: - app: nginx-pci - name: nginx-pci - annotations: - requires-pci: "true" -spec: - replicas: 3 - selector: - matchLabels: - app: nginx-pci - template: - metadata: - labels: - app: nginx-pci - spec: - containers: - - image: nginx - name: nginx-pci diff --git a/content/en/examples/federation/scheduling-policy-admission.yaml b/content/en/examples/federation/scheduling-policy-admission.yaml deleted file mode 100644 index a164722425..0000000000 --- a/content/en/examples/federation/scheduling-policy-admission.yaml +++ /dev/null @@ -1,29 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: admission - namespace: federation-system -data: - config.yml: | - apiVersion: apiserver.k8s.io/v1alpha1 - kind: AdmissionConfiguration - plugins: - - name: SchedulingPolicy - path: /etc/kubernetes/admission/scheduling-policy-config.yml - scheduling-policy-config.yml: | - kubeconfig: /etc/kubernetes/admission/opa-kubeconfig - opa-kubeconfig: | - clusters: - - name: opa-api - cluster: - server: http://opa.federation-system.svc.cluster.local:8181/v0/data/kubernetes/placement - users: - - name: scheduling-policy - user: - token: deadbeefsecret - contexts: - - name: default - context: - cluster: opa-api - user: scheduling-policy - current-context: default diff --git a/content/en/examples/podpreset/allow-db-merged.yaml b/content/en/examples/podpreset/allow-db-merged.yaml index 8a0ad101d7..7f52cc1fa4 100644 --- a/content/en/examples/podpreset/allow-db-merged.yaml +++ b/content/en/examples/podpreset/allow-db-merged.yaml @@ -14,9 +14,6 @@ spec: volumeMounts: - mountPath: /cache name: cache-volume - - mountPath: /etc/app/config.json - readOnly: true - name: secret-volume ports: - containerPort: 80 env: @@ -32,6 +29,3 @@ spec: volumes: - name: cache-volume emptyDir: {} - - name: secret-volume - secret: - secretName: config-details diff --git a/content/en/examples/podpreset/allow-db.yaml b/content/en/examples/podpreset/allow-db.yaml index 0cca13bab2..2c511e650d 100644 --- a/content/en/examples/podpreset/allow-db.yaml +++ b/content/en/examples/podpreset/allow-db.yaml @@ -19,12 +19,6 @@ spec: volumeMounts: - mountPath: /cache name: cache-volume - - mountPath: /etc/app/config.json - readOnly: true - name: secret-volume volumes: - name: cache-volume emptyDir: {} - - name: secret-volume - secret: - secretName: config-details diff --git a/content/en/examples/pods/simple-pod.yaml b/content/en/examples/pods/simple-pod.yaml index 4208f4b365..0e79d8a3c6 100644 --- a/content/en/examples/pods/simple-pod.yaml +++ b/content/en/examples/pods/simple-pod.yaml @@ -5,6 +5,6 @@ metadata: spec: containers: - name: nginx - image: nginx:1.7.9 + image: nginx:1.14.2 ports: - containerPort: 80 diff --git a/content/en/includes/federated-task-tutorial-prereqs.md b/content/en/includes/federated-task-tutorial-prereqs.md deleted file mode 100644 index b254407a67..0000000000 --- a/content/en/includes/federated-task-tutorial-prereqs.md +++ /dev/null @@ -1,5 +0,0 @@ -This guide assumes that you have a running Kubernetes Cluster Federation installation. -If not, then head over to the [federation admin guide](/docs/tutorials/federation/set-up-cluster-federation-kubefed/) to learn how to -bring up a cluster federation (or have your cluster administrator do this for you). -Other tutorials, such as Kelsey Hightower's [Federated Kubernetes Tutorial](https://github.com/kelseyhightower/kubernetes-cluster-federation), -might also help you create a Federated Kubernetes cluster. diff --git a/content/en/training/_index.html b/content/en/training/_index.html new file mode 100644 index 0000000000..aad96f4912 --- /dev/null +++ b/content/en/training/_index.html @@ -0,0 +1,108 @@ +--- +title: Training +bigheader: Kubernetes Training and Certification +abstract: Training programs, certifications, and partners. +layout: basic +cid: training +class: training +--- + +
    +
    +
    +

    Build your cloud native career

    +

    Kubernetes is at the core of the cloud native movement. Training and certifications from the Linux Foundation and our training partners lets you invest in your career, learn Kubernetes, and make your cloud native projects successful.

    +
    +
    +
    + +
    +
    +
    +

    Take a free course on edX

    +
    +
    +
    +
    +
    + Introduction to Kubernetes
     
    +
    +

    Want to learn Kubernetes? Get an in-depth primer on this powerful system for managing containerized applications.

    +
    + Go to Course +
    +
    +
    +
    +
    + Introduction to Cloud Infrastructure Technologies +
    +

    Learn the fundamentals of building and managing cloud technologies directly from The Linux Foundation, the leader in open source.

    +
    + Go to Course +
    +
    +
    +
    +
    + Introduction to Linux +
    +

    Never learned Linux? Want a refresh? Develop a good working knowledge of Linux using both the graphical interface and command line across the major Linux distribution families.

    +
    + Go to Course +
    +
    +
    +
    + +
    +
    +
    +

    Learn with the Linux Foundation

    +

    The Linux Foundation offers instructor-led and self-paced courses for all aspects of the Kubernetes application development and operations lifecycle.

    +

    + See Courses +
    +
    +
    + +
    +
    +
    +

    Get Kubernetes Certified

    +
    +
    +
    +
    + Certified Kubernetes Application Developer (CKAD) +
    +

    The Certified Kubernetes Application Developer exam certifies that users can design, build, configure, and expose cloud native applications for Kubernetes.

    +
    + Go to Certification +
    +
    +
    +
    +
    + Certified Kubernetes Administrator (CKA) +
    +

    The Certified Kubernetes Administrator (CKA) program provides assurance that CKAs have the skills, knowledge, and competency to perform the responsibilities of Kubernetes administrators.

    +
    + Go to Certification +
    +
    +
    +
    + +
    +
    +
    +

    Kubernetes Training Partners

    +

    Our network of Kubernetes Training Partners provide training services for Kubernetes and cloud native projects.

    +
    +
    +
    + + +
    +
    diff --git a/content/es/docs/concepts/configuration/organize-cluster-access-kubeconfig.md b/content/es/docs/concepts/configuration/organize-cluster-access-kubeconfig.md new file mode 100644 index 0000000000..dc9f9e14a5 --- /dev/null +++ b/content/es/docs/concepts/configuration/organize-cluster-access-kubeconfig.md @@ -0,0 +1,153 @@ +--- +title: Organizar el acceso a los clústeres utilizando archivos kubeconfig +content_template: templates/concept +weight: 60 +--- + +{{% capture overview %}} + +Utilice los archivos kubeconfig para organizar la información acerca de los clústeres, los +usuarios, los Namespaces y los mecanismos de autenticación. La herramienta de +línea de comandos `kubectl` utiliza los archivos kubeconfig para hallar la información que +necesita para escoger un clúster y comunicarse con el servidor API de un clúster. + +{{< note >}} +Un archivo utilizado para configurar el acceso a los clústeres se denomina +*archivo kubeconfig*. Esta es una forma genérica de referirse a los archivos de +configuración. Esto no significa que exista un archivo llamado `kubeconfig`. +{{< /note >}} + +Por defecto, `kubectl` busca un archivo llamado `config` en el directorio `$HOME/.kube`. +Puedes especificar otros archivos kubeconfig mediante la configuración de la variable +de entorno `KUBECONFIG` o mediante la configuracion del flag +[`--kubeconfig`](/docs/reference/generated/kubectl/kubectl/). + +Para obtener instrucciones paso a paso acerca de cómo crear y especificar los archivos kubeconfig, +consulte el recurso +[Configurar El Acceso A Múltiples Clústeres](/docs/tasks/access-application-cluster/configure-access-multiple-clusters). + +{{% /capture %}} + +{{% capture body %}} + +## Compatibilidad con múltiples clústeres, usuarios y mecanismos de autenticación + +Suponga que tiene diversos clústeres y que sus usuarios y componentes se autentican +de diversas maneras. Por ejemplo: + +- Un kubelet en ejecución se podría autenticar usando certificados. +- Un usuario se podría autenticar utilizando tokens. +- Los administradores podrían tener un conjunto de certificados que sean suministrados a los usuarios individualmente. + +Con los archivos kubeconfig puedes organizar tus clústeres, usuarios y Namespaces. +También puedes definir diferentes contextos para realizar de forma rápida y +fácil cambios entre clústeres y Namespaces. + +## Contexto + +Un elemento *context* en un archivo kubeconfig se utiliza para agrupar los parámetros de +acceso bajo un nombre apropiado. Cada contexto tiene tres parámetros: clúster, Namespace +y usuario. +Por defecto, la herramienta de línea de comandos `kubectl` utiliza los parámetros del +*contexto actual* para comunicarse con el clúster. + +Para seleccionar el contexto actual: + +```shell +kubectl config use-context +``` + +## Variable de entorno KUBECONFIG + +La variable de entorno `KUBECONFIG` contiene una lista de archivos kubeconfig. +En el caso de Linux y Mac, la lista está delimitada por dos puntos. Si se trata +de Windows, la lista está delimitada por punto y coma. La variable de entorno +`KUBECONFIG` no es indispensable. Si la variable de entorno `KUBECONFIG` no existe, +`kubectl` utiliza el archivo kubeconfig por defecto `$HOME/.kube/config`. + +Si la variable de entorno `KUBECONFIG` existe, `kubectl` utiliza una +configuración eficiente que es el resultado de la fusión de los archivos +listados en la variable de entorno `KUBECONFIG`. + +## Fusionando archivos kubeconfig + +Para poder ver su configuración, escriba el siguiente comando: + +```shell +kubectl config view +``` + +Como se ha descrito anteriormente, la respuesta de este comando podría resultar a partir de un solo +archivo kubeconfig, o podría ser el resultado de la fusión de varios archivos kubeconfig. + +A continuación se muestran las reglas que usa `kubectl` cuando fusiona archivos kubeconfig: + +1. Si el flag `--kubeconfig` está activado, usa solamente el archivo especificado. Sin fusionar. + Sólo se permite una instancia con este flag. + + En caso contrario, si la variable de entorno `KUBECONFIG` está activada, sera usada + como un listado de los archivos a ser fusionados. + Fusionar los archivos listados en la variable de entorno `KUBECONFIG` de acuerdo + con estas reglas: + + * Ignorar nombres de archivo vacíos. + * Producir errores para archivos con contenido que no pueden ser deserializados. + * El primer archivo que establezca un valor particular o una clave se impone. + * Nunca cambie el valor o la clave. + Ejemplo: Conserva el contexto del primer archivo para configurar el `contexto actual`. + Ejemplo: Si dos archivos especifican un `red-user`, utilice sólo los valores del primer archivo. + Incluso desechar el segundo archivo aunque tenga registros que no tengan conflictos. + + Para obtener un ejemplo de configuración de la variable de entorno `KUBECONFIG`, consulte la sección + [Configuración de la variable de entorno KUBECONFIG](/docs/tasks/access-application-cluster/configure-access-multiple-clusters/#set-the-kubeconfig-environment-variable). + + En caso contrario, utilice el archivo kubeconfig predeterminado `$HOME/.kube/config`, sin fusionar. + +2. Determinar el contexto a utilizar con base en el primer acierto en esta secuencia: + + 1. Si es que existe, utilice el flag `---contexto` de la línea de comandos. + 2. Utilice el `contexto actual` procedente de los archivos kubeconfig fusionados. + + En este punto se permite un contexto vacío. + +3. Determinar el clúster y el usuario. En este caso, puede o no haber un contexto. + Determine el clúster y el usuario con base en el primer acierto que se ejecute dos veces en + esta secuencia: una para el usuario y otra para el clúster: + + 1. Si es que existen, utilice el flag `--user` o `--cluster` de la línea de comandos. + 2. Si el contexto no está vacío, tome el usuario o clúster del contexto. + + En este caso el usuario y el clúster pueden estar vacíos. + +4. Determinar la información del clúster a utilizar. En este caso, puede o no haber información del clúster. + Se construye cada pieza de la información del clúster con base en esta secuencia, el primer acierto se impone: + + 1. Si es que existen, use el flag `--server`, `--certificate-authority`, `--insecure-skip-tls-verify` en la línea de comandos. + 2. Si existen atributos de información de clúster procedentes de los archivos kubeconfig fusionados, utilícelos. + 3. Falla si no existe la ubicación del servidor. + +5. Determinar la información del usuario a utilizar. Cree información de usuario utilizando las mismas reglas que + la información de clúster, con la excepción de permitir sólo un mecanismo de autenticación por usuario: + + 1. Si es que existen, utilice el flag `--client-certificate`, `--client-key`, `--username`, `--password`, `--token` de la línea de comandos. + 2. Utilice los campos `user` de los archivos kubeconfig fusionados. + 3. Falla si hay dos mecanismos de autenticación contradictorios. + +6. Si todavía falta información, utilice los valores predeterminados y solicite + información de autenticación. + +## Referencias de archivos + +Las referencias, así también como, las rutas de un archivo kubeconfig son relativas a la ubicación del archivo kubeconfig. +Las referencias de un archivo en la línea de comandos son relativas al directorio actual de trabajo. +Dentro de `$HOME/.kube/config`, las rutas relativas se almacenan de manera relativa a la ubicación del archivo kubeconfig , al igual que las rutas absolutas +se almacenan absolutamente. + +{{% /capture %}} + +{{% capture whatsnext %}} + +* [Configurar el acceso a multiples Clústeres](/docs/tasks/access-application-cluster/configure-access-multiple-clusters/) +* [`kubectl config`](/docs/reference/generated/kubectl/kubectl-commands#config) + +{{% /capture %}} diff --git a/content/fr/_index.html b/content/fr/_index.html index 026a0f910f..16bfc5c82f 100644 --- a/content/fr/_index.html +++ b/content/fr/_index.html @@ -3,12 +3,12 @@ title: "Solution professionnelle d’orchestration de conteneurs" abstract: "Déploiement, mise à l'échelle et gestion automatisée des conteneurs" cid: home --- +{{< announcement >}} {{< deprecationwarning >}} {{< blocks/section id="oceanNodes" >}} {{% blocks/feature image="flower" %}} - ### [Kubernetes (K8s)]({{< relref "/docs/concepts/overview/what-is-kubernetes" >}}) est un système open-source permettant d'automatiser le déploiement, la mise à l'échelle et la gestion des applications conteneurisées. Les conteneurs qui composent une application sont regroupés dans des unités logiques pour en faciliter la gestion et la découverte. Kubernetes s’appuie sur [15 années d’expérience dans la gestion de charges de travail de production (workloads) chez Google](http://queue.acm.org/detail.cfm?id=2898444), associé aux meilleures idées et pratiques de la communauté. @@ -18,6 +18,7 @@ Les conteneurs qui composent une application sont regroupés dans des unités lo #### Quel que soit le nombre Conçu selon les mêmes principes qui permettent à Google de gérer des milliards de conteneurs par semaine, Kubernetes peut évoluer sans augmenter votre équipe d'opérations. + {{% /blocks/feature %}} {{% blocks/feature image="blocks" %}} @@ -28,18 +29,15 @@ Qu'il s'agisse de tester localement ou d'une implémentation globale, Kubernetes {{% /blocks/feature %}} {{% blocks/feature image="suitcase" %}} - #### Quel que soit l'endroit -Kubernetes est une solution open-source qui vous permet de tirer parti de vos infrastructures qu'elles soient sur site (on-premises), hybride ou en Cloud publique. -Vous pourrez ainsi répartir sans effort vos workloads là où vous le souhaitez. +Kubernetes est une solution open-source qui vous permet de tirer parti de vos infrastructures qu'elles soient sur site (on-premises), hybride ou en Cloud publique. Vous pourrez ainsi répartir sans effort vos workloads là où vous le souhaitez. {{% /blocks/feature %}} {{< /blocks/section >}} {{< blocks/section id="video" background-image="kub_video_banner_homepage" >}} -

    Les défis de la migration de plus de 150 microservices vers Kubernetes

    Par Sarah Wells, directrice technique des opérations et de la fiabilité, Financial Times

    @@ -47,12 +45,12 @@ Vous pourrez ainsi répartir sans effort vos workloads là où vous le souhaitez


    - Venez au KubeCon San Diego du 18 au 21 Nov 2019 + Venez au KubeCon Amsterdam en Juillet/Aout (à définir)



    - Venez au KubeCon Amsterdam du 30 Mars au 2 Avril 2020 + Venez au KubeCon Boston du 17 au 20 Novembre 2020
    diff --git a/content/fr/docs/concepts/architecture/cloud-controller.md b/content/fr/docs/concepts/architecture/cloud-controller.md index e8a513e42d..ca0542a2c3 100644 --- a/content/fr/docs/concepts/architecture/cloud-controller.md +++ b/content/fr/docs/concepts/architecture/cloud-controller.md @@ -253,6 +253,7 @@ Les fournisseurs de cloud suivants ont implémenté leur CCM: * [AWS](https://github.com/kubernetes/cloud-provider-aws) * [BaiduCloud](https://github.com/baidu/cloud-provider-baiducloud) * [Linode](https://github.com/linode/linode-cloud-controller-manager) +* [Scaleway](https://github.com/scaleway/scaleway-cloud-controller-manager) ## Administration de cluster diff --git a/content/fr/docs/concepts/workloads/pods/init-containers.md b/content/fr/docs/concepts/workloads/pods/init-containers.md index 905b9275db..c2ac521df4 100644 --- a/content/fr/docs/concepts/workloads/pods/init-containers.md +++ b/content/fr/docs/concepts/workloads/pods/init-containers.md @@ -111,10 +111,10 @@ spec: initContainers: - name: init-myservice image: busybox:1.28 - command: ['sh', '-c', 'until nslookup myservice; do echo "En attente de myservice"; sleep 2; done;'] + command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo en attente de myservice; sleep 2; done"] - name: init-mydb image: busybox:1.28 - command: ['sh', '-c', 'until nslookup mydb; do echo "En attente de mydb"; sleep 2; done;'] + command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo en attente de mydb; sleep 2; done"] ``` Les fichiers YAML suivants résument les services `mydb` et `myservice` : diff --git a/content/fr/docs/contribute/start.md b/content/fr/docs/contribute/start.md index 59cb54cfc2..39eee2a39d 100644 --- a/content/fr/docs/contribute/start.md +++ b/content/fr/docs/contribute/start.md @@ -70,7 +70,7 @@ Pour plus d'informations sur la contribution à la documentation dans plusieurs Si vous souhaitez démarrer une nouvelle traduction, voir ["Traduction"](/docs/contribute/localization/). -## Créer des demander recevables +## Créer des demandes recevables Toute personne possédant un compte GitHub peut soumettre un problème (rapport de bogue) à la documentation de Kubernetes. Si vous voyez quelque chose qui ne va pas, même si vous ne savez pas comment le réparer, [ouvrez un ticket](#how-to-file-an-issue). diff --git a/content/fr/docs/reference/kubectl/overview.md b/content/fr/docs/reference/kubectl/overview.md index 634bd83a4e..7ed5b714b1 100644 --- a/content/fr/docs/reference/kubectl/overview.md +++ b/content/fr/docs/reference/kubectl/overview.md @@ -69,31 +69,31 @@ Le tableau suivant inclut une courte description et la syntaxe générale pour c Opération | Syntaxe | Description -------------------- | -------------------- | -------------------- -`annotate` | `kubectl annotate (-f FICHIER \| TYPE NOM \| TYPE/NOM) CLE_1=VAL_1 ... CLE_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]` | Ajoute ou modifie les annotations d'une ou plusieurs ressources. +`annotate` | kubectl annotate (-f FICHIER | TYPE NOM | TYPE/NOM) CLE_1=VAL_1 ... CLE_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags] | Ajoute ou modifie les annotations d'une ou plusieurs ressources. `api-versions` | `kubectl api-versions [flags]` | Liste les versions d'API disponibles. `apply` | `kubectl apply -f FICHIER [flags]` | Applique un changement de configuration à une ressource depuis un fichier ou stdin. `attach` | `kubectl attach POD -c CONTENEUR [-i] [-t] [flags]` | Attache à un conteneur en cours d'exécution soit pour voir la sortie standard soit pour interagir avec le conteneur (stdin). -`autoscale` | `kubectl autoscale (-f FICHIER \| TYPE NOM \| TYPE/NOM) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]` | Scale automatiquement l'ensemble des pods gérés par un replication controller. +`autoscale` | kubectl autoscale (-f FICHIER | TYPE NOM | TYPE/NOM) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags] | Scale automatiquement l'ensemble des pods gérés par un replication controller. `cluster-info` | `kubectl cluster-info [flags]` | Affiche les informations des endpoints du master et des services du cluster. `config` | `kubectl config SOUS-COMMANDE [flags]` | Modifie les fichiers kubeconfig. Voir les sous-commandes individuelles pour plus de détails. `create` | `kubectl create -f FICHIER [flags]` | Crée une ou plusieurs ressources depuis un fichier ou stdin. -`delete` | `kubectl delete (-f FICHIER \| TYPE [NOM \| /NOM \| -l label \| --all]) [flags]` | Supprime des ressources soit depuis un fichier ou stdin, ou en indiquant des sélecteurs de label, des noms, des sélecteurs de ressources ou des ressources. -`describe` | `kubectl describe (-f FICHIER \| TYPE [PREFIXE_NOM \| /NOM \| -l label]) [flags]` | Affiche l'état détaillé d'une ou plusieurs ressources. +`delete` | kubectl delete (-f FICHIER | TYPE [NOM | /NOM | -l label | --all]) [flags] | Supprime des ressources soit depuis un fichier ou stdin, ou en indiquant des sélecteurs de label, des noms, des sélecteurs de ressources ou des ressources. +`describe` | kubectl describe (-f FICHIER | TYPE [PREFIXE_NOM | /NOM | -l label]) [flags] | Affiche l'état détaillé d'une ou plusieurs ressources. `diff` | `kubectl diff -f FICHIER [flags]` | Diff un fichier ou stdin par rapport à la configuration en cours (**BETA**) -`edit` | `kubectl edit (-f FICHIER \| TYPE NOM \| TYPE/NOM) [flags]` | Édite et met à jour la définition d'une ou plusieurs ressources sur le serveur en utilisant l'éditeur par défaut. +`edit` | kubectl edit (-f FICHIER | TYPE NOM | TYPE/NOM) [flags] | Édite et met à jour la définition d'une ou plusieurs ressources sur le serveur en utilisant l'éditeur par défaut. `exec` | `kubectl exec POD [-c CONTENEUR] [-i] [-t] [flags] [-- COMMANDE [args...]]` | Exécute une commande à l'intérieur d'un conteneur dans un pod. `explain` | `kubectl explain [--recursive=false] [flags]` | Obtient des informations sur différentes ressources. Par exemple pods, nœuds, services, etc. -`expose` | `kubectl expose (-f FICHIER \| TYPE NOM \| TYPE/NOM) [--port=port] [--protocol=TCP\|UDP] [--target-port=nombre-ou-nom] [--name=nom] [--external-ip=ip-externe-ou-service] [--type=type] [flags]` | Expose un replication controller, service ou pod comme un nouveau service Kubernetes. -`get` | `kubectl get (-f FICHIER \| TYPE [NOM \| /NOM \| -l label]) [--watch] [--sort-by=CHAMP] [[-o \| --output]=FORMAT_AFFICHAGE] [flags]` | Liste une ou plusieurs ressources. -`label` | `kubectl label (-f FICHIER \| TYPE NOM \| TYPE/NOM) CLE_1=VAL_1 ... CLE_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]` | Ajoute ou met à jour les labels d'une ou plusieurs ressources. +`expose` | kubectl expose (-f FICHIER | TYPE NOM | TYPE/NOM) [--port=port] [--protocol=TCP|UDP] [--target-port=nombre-ou-nom] [--name=nom] [--external-ip=ip-externe-ou-service] [--type=type] [flags] | Expose un replication controller, service ou pod comme un nouveau service Kubernetes. +`get` | kubectl get (-f FICHIER | TYPE [NOM | /NOM | -l label]) [--watch] [--sort-by=CHAMP] [[-o | --output]=FORMAT_AFFICHAGE] [flags] | Liste une ou plusieurs ressources. +`label` | kubectl label (-f FICHIER | TYPE NOM | TYPE/NOM) CLE_1=VAL_1 ... CLE_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags] | Ajoute ou met à jour les labels d'une ou plusieurs ressources. `logs` | `kubectl logs POD [-c CONTENEUR] [--follow] [flags]` | Affiche les logs d'un conteneur dans un pod. -`patch` | `kubectl patch (-f FICHIER \| TYPE NOM \| TYPE/NOM) --patch PATCH [flags]` | Met à jour un ou plusieurs champs d'une resource en utilisant le processus de merge patch stratégique. +`patch` | kubectl patch (-f FICHIER | TYPE NOM | TYPE/NOM) --patch PATCH [flags] | Met à jour un ou plusieurs champs d'une resource en utilisant le processus de merge patch stratégique. `port-forward` | `kubectl port-forward POD [PORT_LOCAL:]PORT_DISTANT [...[PORT_LOCAL_N:]PORT_DISTANT_N] [flags]` | Transfère un ou plusieurs ports locaux vers un pod. `proxy` | `kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]` | Exécute un proxy vers un API server Kubernetes. `replace` | `kubectl replace -f FICHIER` | Remplace une ressource depuis un fichier ou stdin. -`rolling-update`| `kubectl rolling-update ANCIEN_NOM_CONTROLEUR ([NOUVEAU_NOM_CONTROLEUR] --image=NOUVELLE_IMAGE_CONTENEUR \| -f NOUVELLE_SPEC_CONTROLEUR) [flags]` | Exécute un rolling update en remplaçant graduellement le replication controller indiqué et ses pods. +`rolling-update`| kubectl rolling-update ANCIEN_NOM_CONTROLEUR ([NOUVEAU_NOM_CONTROLEUR] --image=NOUVELLE_IMAGE_CONTENEUR | -f NOUVELLE_SPEC_CONTROLEUR) [flags] | Exécute un rolling update en remplaçant graduellement le replication controller indiqué et ses pods. `run` | `kubectl run NOM --image=image [--env="cle=valeur"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [flags]` | Exécute dans le cluster l'image indiquée. -`scale` | `kubectl scale (-f FICHIER \| TYPE NOM \| TYPE/NOM) --replicas=QUANTITE [--resource-version=version] [--current-replicas=quantité] [flags]` | Met à jour la taille du replication controller indiqué. +`scale` | kubectl scale (-f FICHIER | TYPE NOM | TYPE/NOM) --replicas=QUANTITE [--resource-version=version] [--current-replicas=quantité] [flags] | Met à jour la taille du replication controller indiqué. `version` | `kubectl version [--client] [flags]` | Affiche la version de Kubernetes du serveur et du client. Rappelez-vous : Pour tout savoir sur les opérations, voir la documentation de référence de [kubectl](/docs/user-guide/kubectl/). diff --git a/content/fr/docs/tasks/administer-cluster/running-cloud-controller.md b/content/fr/docs/tasks/administer-cluster/running-cloud-controller.md index a6b6a5b820..631eda2baf 100644 --- a/content/fr/docs/tasks/administer-cluster/running-cloud-controller.md +++ b/content/fr/docs/tasks/administer-cluster/running-cloud-controller.md @@ -69,6 +69,7 @@ Pour les cloud-controller-manager ne faisant pas partie de Kubernetes, vous pouv * [keepalived](https://github.com/munnerz/keepalived-cloud-provider) * [Oracle Cloud Infrastructure](https://github.com/oracle/oci-cloud-controller-manager) * [Rancher](https://github.com/rancher/rancher-cloud-controller-manager) +* [Scaleway](https://github.com/scaleway/scaleway-cloud-controller-manager) Pour les fournisseurs qui se trouvent déjà dans Kubernetes, vous pouvez exécuter le cloud-controller-manager dans l'arborescence en tant que Daemonset dans votre cluster. Utilisez ce qui suit comme guide: diff --git a/content/fr/docs/tasks/tools/install-kubectl.md b/content/fr/docs/tasks/tools/install-kubectl.md index 091cb63c30..2d1f50fccd 100644 --- a/content/fr/docs/tasks/tools/install-kubectl.md +++ b/content/fr/docs/tasks/tools/install-kubectl.md @@ -54,7 +54,7 @@ Vous devez utiliser une version de kubectl qui différe seulement d'une version 4. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` ### Installation à l'aide des gestionnaires des paquets natifs @@ -80,28 +80,33 @@ yum install -y kubectl {{< /tab >}} {{< /tabs >}} +### Installation avec des gestionnaires de paquets alternatifs -### Installer avec snap - +{{< tabs name="other_kubectl_install" >}} +{{% tab name="Snap" %}} Si vous êtes sur Ubuntu ou une autre distribution Linux qui supporte le gestionnaire de paquets [snap](https://snapcraft.io/docs/core/install), kubectl est disponible comme application [snap](https://snapcraft.io/). -1. Passez à l'utilisateur snap et exécutez la commande d'installation : +```shell +snap install kubectl --classic - ``` - sudo snap install kubectl --classic - ``` +kubectl version --client +``` +{{% /tab %}} +{{% tab name="Homebrew" %}} +Si vous êtes sur Linux et que vous utiliser [Homebrew](https://docs.brew.sh/Homebrew-on-Linux) comme gestionnaire de paquets, kubectl est disponible. [installation](https://docs.brew.sh/Homebrew-on-Linux#install) +```shell +brew install kubectl -2. Testez pour vous assurer que la version que vous avez installée est à jour : - - ``` - kubectl version - ``` +kubectl version --client +``` +{{% /tab %}} +{{< /tabs >}} ## Installer kubectl sur macOS ### Installer le binaire kubectl avec curl sur macOS -1. Téléchargez la dernière release: +1. Téléchargez la dernière version: ``` curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/darwin/amd64/kubectl @@ -129,7 +134,7 @@ Si vous êtes sur Ubuntu ou une autre distribution Linux qui supporte le gestion 4. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` ### Installer avec Homebrew sur macOS @@ -138,6 +143,11 @@ Si vous êtes sur MacOS et que vous utilisez le gestionnaire de paquets [Homebre 1. Exécutez la commande d'installation: + ``` + brew install kubectl + ``` + ou + ``` brew install kubernetes-cli ``` @@ -145,7 +155,7 @@ Si vous êtes sur MacOS et que vous utilisez le gestionnaire de paquets [Homebre 2. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` ### Installer avec Macports sur macOS @@ -162,14 +172,14 @@ Si vous êtes sur MacOS et que vous utilisez le gestionnaire de paquets [Macport 2. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` ## Installer kubectl sur Windows ### Installer le binaire kubectl avec curl sur Windows -1. Téléchargez la dernière release {{< param "fullversion" >}} depuis [ce lien](https://storage.googleapis.com/kubernetes-release/release/{{< param "fullversion" >}}/bin/windows/amd64/kubectl.exe). +1. Téléchargez la dernière version {{< param "fullversion" >}} depuis [ce lien](https://storage.googleapis.com/kubernetes-release/release/{{< param "fullversion" >}}/bin/windows/amd64/kubectl.exe). Ou si vous avez `curl` installé, utilisez cette commande: @@ -183,8 +193,12 @@ Si vous êtes sur MacOS et que vous utilisez le gestionnaire de paquets [Macport 3. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` +{{< note >}} +[Docker Desktop pour Windows](https://docs.docker.com/docker-for-windows/#kubernetes) ajoute sa propre version de `kubectl` au $PATH. +Si vous avez déjà installé Docker Desktop, vous devrez peut-être placer votre entrée PATH avant celle ajoutée par le programme d'installation de Docker Desktop ou supprimer le `kubectl` de Docker Desktop. +{{< /note >}} ### Installer avec Powershell de PSGallery @@ -204,7 +218,7 @@ Si vous êtes sous Windows et que vous utilisez le gestionnaire de paquets [Powe 2. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` {{< note >}}La mise à jour de l'installation s'effectue en réexécutant les deux commandes listées à l'étape 1.{{< /note >}} @@ -227,7 +241,7 @@ Pour installer kubectl sur Windows, vous pouvez utiliser le gestionnaire de paqu 2. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` 3. Accédez à votre répertoire personnel: @@ -269,7 +283,7 @@ Vous pouvez installer kubectl en tant qu'élément du SDK Google Cloud. 3. Testez pour vous assurer que la version que vous avez installée est à jour: ``` - kubectl version + kubectl version --client ``` ## Vérification de la configuration de kubectl @@ -307,7 +321,7 @@ Vous trouverez ci-dessous les étapes à suivre pour configurer l'auto-compléti {{< tabs name="kubectl_autocompletion" >}} -{{% tab name="Bash on Linux" %}} +{{% tab name="Bash sur Linux" %}} ### Introduction @@ -344,6 +358,12 @@ Vous devez maintenant vérifier que le script de completion de kubectl est bien ```shell kubectl completion bash >/etc/bash_completion.d/kubectl ``` +- Si vous avez un alias pour kubectl, vous pouvez étendre la completion de votre shell pour fonctionner avec cet alias: + + ```shell + echo 'alias k=kubectl' >>~/.bashrc + echo 'complete -F __start_kubectl k' >>~/.bashrc + ``` {{< note >}} bash-completion source tous les scripts de completion dans `/etc/bash_completion.d`. @@ -354,49 +374,69 @@ Les deux approches sont équivalentes. Après avoir rechargé votre shell, l'aut {{% /tab %}} -{{% tab name="Bash on macOS" %}} +{{% tab name="Bash sur macOS" %}} -{{< warning>}} -macOS inclut Bash 3.2 par défaut. Le script de complétion kubectl nécessite Bash 4.1+ et ne fonctionne pas avec Bash 3.2. Une des solutions possibles est d'installer une version plus récente de Bash sous macOS (voir instructions [ici](https://itnext.io/upgrading-bash-on-macos-7138bd1066ba)). Les instructions ci-dessous ne fonctionnent que si vous utilisez Bash 4.1+. -{{< /warning >}} ### Introduction Le script de complétion kubectl pour Bash peut être généré avec la commande `kubectl completion bash`. Sourcer le script de completion dans votre shell permet l'auto-complétion de kubectl. -En revanche, le script de complétion dépend de [**bash-completion**](https://github.com/scop/bash-completion), ce qui implique que vous devez d'abord installer ce logiciel (vous pouvez tester si vous avez déjà installé bash-completion en utilisant `type _init_completion`). +En revanche, le script de complétion dépend de [**bash-completion**](https://github.com/scop/bash-completion), ce qui implique que vous devez d'abord installer ce logiciel. + +{{< warning>}} +macOS inclut Bash 3.2 par défaut. Le script de complétion kubectl nécessite Bash 4.1+ et ne fonctionne pas avec Bash 3.2. Une des solutions possibles est d'installer une version plus récente de Bash sous macOS (voir instructions [ici](https://itnext.io/upgrading-bash-on-macos-7138bd1066ba)). Les instructions ci-dessous ne fonctionnent que si vous utilisez Bash 4.1+. +{{< /warning >}} + ### Installer bash-completion -Vous pouvez installer bash-completion avec Homebrew: +{{< note >}} +Comme mentionné, ces instructions supposent que vous utilisez Bash 4.1+, ce qui signifie que vous installerez bash-completion v2 (contrairement à Bash 3.2 et bash-completion v1, auquel cas la complétion pour kubectl ne fonctionnera pas). +{{< /note >}} + +Vous pouvez tester si vous avez déjà installé bash-completion en utilisant `type _init_completion`. Si il n'est pas installé, vous pouvez installer bash-completion avec Homebrew: ```shell -brew install bash-completion +brew install bash-completion@2 ``` Comme indiqué dans la sortie de `brew install` (section "Caveats"), ajoutez les lignes suivantes à votre fichier `~/.bashrc` ou `~/.bash_profile` : ```shell -[ -f /usr/local/etc/bash_completion ] && . /usr/local/etc/bash_completion +export BASH_COMPLETION_COMPAT_DIR="/usr/local/etc/bash_completion.d" +[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh" ``` -Rechargez votre shell. +Rechargez votre shell et vérifiez que bash-completion v2 est correctement installé avec `type _init_completion`. ### Activer l'auto-complétion de kubectl -Si vous avez installé kubectl avec Homebrew (comme expliqué [ici](#installer-avec-homebrew-sur-macos)), alors le script de complétion a été automatiquement installé dans `/usr/local/etc/bash_completion.d/kubectl`. Dans ce cas, vous n'avez rien à faire. - Si vous n'avez pas installé via Homebrew, vous devez maintenant vous assurer que le script de complétion kubectl est bien sourcé dans toutes vos sessions shell comme suit: +- Sourcer le script de completion dans votre fichier `~/.bashrc`: + + ```shell + echo 'source <(kubectl completion bash)' >>~/.bashrc + + ``` + - Ajoutez le script de complétion dans le répertoire `/usr/local/etc/bash_completion.d`: ```shell kubectl completion bash >/usr/local/etc/bash_completion.d/kubectl ``` +- Si vous avez un alias pour kubectl, vous pouvez étendre la completion de votre shell pour fonctionner avec cet alias: + + ```shell + echo 'alias k=kubectl' >>~/.bashrc + echo 'complete -F __start_kubectl k' >>~/.bashrc + ``` + +Si vous avez installé kubectl avec Homebrew (comme expliqué [ici](#installer-avec-homebrew-sur-macos)), alors le script de complétion a été automatiquement installé dans `/usr/local/etc/bash_completion.d/kubectl`. Dans ce cas, vous n'avez rien à faire. {{< note >}} -bash-completion (en cas d'installation avec Homebrew) source tous les scripts de complétion dans le répertoire. +L'installation Homebrew de bash-complétion v2 source tous les fichiers du répertoire `BASH_COMPLETION_COMPAT_DIR`, c'est pourquoi les deux dernières méthodes fonctionnent. {{< /note >}} Après avoir rechargé votre shell, l'auto-complétion de kubectl devrait fonctionner. @@ -412,6 +452,13 @@ Pour faire ainsi dans toutes vos sessions shell, ajoutez ce qui suit à votre fi source <(kubectl completion zsh) ``` +Si vous avez un alias pour kubectl, vous pouvez étendre la completion de votre shell pour fonctionner avec cet alias: + +```shell +echo 'alias k=kubectl' >>~/.zshrc +echo 'complete -F __start_kubectl k' >>~/.zshrc +``` + Après avoir rechargé votre shell, l'auto-complétion de kubectl devrait fonctionner. Si vous rencontrez une erreur comme `complete:13: command not found: compdef`, alors ajoutez ce qui suit au début de votre fichier `~/.zshrc`: diff --git a/content/id/docs/concepts/workloads/pods/init-containers.md b/content/id/docs/concepts/workloads/pods/init-containers.md index f792e2b1df..60ce9d31ce 100644 --- a/content/id/docs/concepts/workloads/pods/init-containers.md +++ b/content/id/docs/concepts/workloads/pods/init-containers.md @@ -78,12 +78,12 @@ metadata: { "name": "init-myservice", "image": "busybox:1.28", - "command": ["sh", "-c", "until nslookup myservice; do echo waiting for myservice; sleep 2; done;"] + "command": ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"] }, { "name": "init-mydb", "image": "busybox:1.28", - "command": ["sh", "-c", "until nslookup mydb; do echo waiting for mydb; sleep 2; done;"] + "command": ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"] } ]' spec: diff --git a/content/ja/docs/concepts/workloads/pods/init-containers.md b/content/ja/docs/concepts/workloads/pods/init-containers.md index 9dde5bc7eb..8ba075b32c 100644 --- a/content/ja/docs/concepts/workloads/pods/init-containers.md +++ b/content/ja/docs/concepts/workloads/pods/init-containers.md @@ -76,12 +76,12 @@ metadata: { "name": "init-myservice", "image": "busybox:1.28", - "command": ["sh", "-c", "until nslookup myservice; do echo waiting for myservice; sleep 2; done;"] + "command": ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"] }, { "name": "init-mydb", "image": "busybox:1.28", - "command": ["sh", "-c", "until nslookup mydb; do echo waiting for mydb; sleep 2; done;"] + "command": ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"] } ]' spec: diff --git a/content/ko/docs/concepts/_index.md b/content/ko/docs/concepts/_index.md index 6d4e30b4ca..c6e7556312 100644 --- a/content/ko/docs/concepts/_index.md +++ b/content/ko/docs/concepts/_index.md @@ -32,7 +32,7 @@ weight: 40 * [파드](/ko/docs/concepts/workloads/pods/pod-overview/) * [서비스](/ko/docs/concepts/services-networking/service/) -* [볼륨](/docs/concepts/storage/volumes/) +* [볼륨](/ko/docs/concepts/storage/volumes/) * [네임스페이스](/ko/docs/concepts/overview/working-with-objects/namespaces/) 또한, 쿠버네티스에는 기초 오브젝트를 기반으로, 부가 기능 및 편의 기능을 제공하는 [컨트롤러](/ko/docs/concepts/architecture/controller/)에 의존하는 보다 높은 수준의 추상 개념도 포함되어 있다. 다음이 포함된다. diff --git a/content/ko/docs/concepts/architecture/cloud-controller.md b/content/ko/docs/concepts/architecture/cloud-controller.md index 5c872bf06a..734a2cd1a0 100644 --- a/content/ko/docs/concepts/architecture/cloud-controller.md +++ b/content/ko/docs/concepts/architecture/cloud-controller.md @@ -52,7 +52,7 @@ CCM은 쿠버네티스 컨트롤러 매니저(KCM)의 기능 일부를 독립시 볼륨 컨트롤러는 의도적으로 CCM의 일부가 되지 않도록 선택되었다. 연관된 복잡성 때문에 그리고 벤더 특유의 볼륨 로직 개념을 일반화 하기 위한 기존의 노력때문에, 볼륨 컨트롤러는 CCM으로 이전되지 않도록 결정되었다. {{< /note >}} -CCM을 이용하는 볼륨을 지원하기 위한 원래 계획은 플러그형 볼륨을 지원하기 위한 [Flex](/docs/concepts/storage/volumes/#flexVolume) 볼륨을 사용하기 위한 것이었다. 그러나, [CSI](/docs/concepts/storage/volumes/#csi)라 알려진 경쟁적인 노력이 Flex를 대체하도록 계획되고 있다. +CCM을 이용하는 볼륨을 지원하기 위한 원래 계획은 플러그형 볼륨을 지원하기 위한 [Flex](/ko/docs/concepts/storage/volumes/#flexVolume) 볼륨을 사용하기 위한 것이었다. 그러나, [CSI](/ko/docs/concepts/storage/volumes/#csi)라 알려진 경쟁적인 노력이 Flex를 대체하도록 계획되고 있다. 이러한 역동성을 고려하여, CSI가 준비될 때까지 차이점에 대한 측정은 도중에 중지하기로 결정하였다. diff --git a/content/ko/docs/concepts/architecture/nodes.md b/content/ko/docs/concepts/architecture/nodes.md index f9c28cee9c..a94a81a0cb 100644 --- a/content/ko/docs/concepts/architecture/nodes.md +++ b/content/ko/docs/concepts/architecture/nodes.md @@ -184,7 +184,7 @@ kubelet은 `NodeStatus` 와 리스 오브젝트를 생성하고 업데이트 할 #### 안정성 쿠버네티스 1.4에서, 대량의 노드들이 마스터 접근에 -문제를 지닐 경우 (예를 들어 마스터에 네트워크 문제가 발생했기 때문에) +문제를 지닐 경우 (예를 들어 마스터에 네트워크 문제들이 발생했기 때문에) 더 개선된 문제 해결을 하도록 노드 컨트롤러의 로직을 업데이트 했다. 1.4를 시작으로, 노드 컨트롤러는 파드 축출에 대한 결정을 내릴 경우 클러스터 내 모든 노드를 살핀다. @@ -210,7 +210,7 @@ kubelet은 `NodeStatus` 와 리스 오브젝트를 생성하고 업데이트 할 노드가 가용성 영역들에 걸쳐 퍼져 있는 주된 이유는 하나의 전체 영역이 장애가 발생할 경우 워크로드가 상태 양호한 영역으로 이전되어질 수 있도록 하기 위해서이다. 그러므로, 하나의 영역 내 모든 노드들이 상태가 불량하면 노드 컨트롤러는 -정상 비율 `--node-eviction-rate`로 축출한다. 코너 케이스란 모든 영역이 +`--node-eviction-rate` 의 정상 비율로 축출한다. 코너 케이스란 모든 영역이 완전히 상태불량 (즉 클러스터 내 양호한 노드가 없는 경우) 한 경우이다. 이러한 경우, 노드 컨트롤러는 마스터 연결에 문제가 있어 일부 연결이 복원될 때까지 모든 축출을 중지하는 것으로 여긴다. diff --git a/content/ko/docs/concepts/configuration/overview.md b/content/ko/docs/concepts/configuration/overview.md index 794f46d079..1bcb7362d6 100644 --- a/content/ko/docs/concepts/configuration/overview.md +++ b/content/ko/docs/concepts/configuration/overview.md @@ -28,7 +28,7 @@ weight: 10 - 더 나은 인트로스펙션(introspection)을 위해서, 어노테이션에 오브젝트의 설명을 넣는다. -## "단독(Naked)" 파드 vs 레플리카 셋, 디플로이먼트, 그리고 잡 +## "단독(Naked)" 파드 vs 레플리카 셋, 디플로이먼트, 그리고 잡 {#naked-pods-vs-replicasets-deployments-and-jobs} - 가능하다면 단독 파드(즉, [레플리카 셋](/ko/docs/concepts/workloads/controllers/replicaset/)이나 [디플로이먼트](/ko/docs/concepts/workloads/controllers/deployment/)에 연결되지 않은 파드)를 사용하지 않는다. 단독 파드는 노드 장애 이벤트가 발생해도 다시 스케줄링되지 않는다. @@ -85,7 +85,7 @@ DNS 서버는 새로운 `서비스`를 위한 쿠버네티스 API를 Watch하며 - `imagePullPolicy: Never`: 이미지가 로컬에 존재한다고 가정한다. 이미지를 풀(Pull) 하기 위해 시도하지 않는다. {{< note >}} -컨테이너가 항상 같은 버전의 이미지를 사용하도록 만들기 위해, `sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2`와 같은 이미지의 [다이제스트](https://docs.docker.com/engine/reference/commandline/pull/#pull-an-image-by-digest-immutable-identifier)를 명시할 수 있다. 다이제스트는 특정 버전의 이미지를 고유하게 식별하며, 다이제스트 값을 변경하지 않는 한 쿠버네티스에 의해 절대로 변경되지 않는다. +컨테이너가 항상 같은 버전의 이미지를 사용하도록 하기 위해, `<이미지 이름>:<태그>` 를 `<이미지 이름>@<다이제스트>` (예시 `image@sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2`)로 변경해서 이미지의 [다이제스트](https://docs.docker.com/engine/reference/commandline/pull/#pull-an-image-by-digest-immutable-identifier)를 명시할 수 있다. 다이제스트는 특정 버전의 이미지를 고유하게 식별하며, 다이제스트 값을 변경하지 않는 한 쿠버네티스에 의해 절대로 변경되지 않는다. {{< /note >}} {{< note >}} diff --git a/content/ko/docs/concepts/containers/container-environment-variables.md b/content/ko/docs/concepts/containers/container-environment-variables.md index 6100f4c28a..b5cfaccbfc 100644 --- a/content/ko/docs/concepts/containers/container-environment-variables.md +++ b/content/ko/docs/concepts/containers/container-environment-variables.md @@ -17,7 +17,7 @@ weight: 20 쿠버네티스 컨테이너 환경은 컨테이너에 몇 가지 중요한 리소스를 제공한다. -* 하나의 [이미지](/ko/docs/concepts/containers/images/)와 하나 이상의 [볼륨](/docs/concepts/storage/volumes/)이 결합된 파일 시스템. +* 하나의 [이미지](/ko/docs/concepts/containers/images/)와 하나 이상의 [볼륨](/ko/docs/concepts/storage/volumes/)이 결합된 파일 시스템. * 컨테이너 자신에 대한 정보. * 클러스터 내의 다른 오브젝트에 대한 정보. diff --git a/content/ko/docs/concepts/containers/images.md b/content/ko/docs/concepts/containers/images.md index 3bc71c53c8..615e84dc40 100644 --- a/content/ko/docs/concepts/containers/images.md +++ b/content/ko/docs/concepts/containers/images.md @@ -64,6 +64,7 @@ Docker *18.06 또는 그 이상* 을 사용하길 바란다. 더 낮은 버전 - IAM 역할과 정책을 사용하여 OCIR 저장소에 접근을 제어함 - Azure 컨테이너 레지스트리(ACR) 사용 - IBM 클라우드 컨테이너 레지스트리 사용 + - IAM 역할 및 정책을 사용하여 IBM 클라우드 컨테이너 레지스트리에 대한 접근 권한 부여 - 프라이빗 레지스트리에 대한 인증을 위한 노드 구성 - 모든 파드는 구성된 프라이빗 레지스트리를 읽을 수 있음 - 클러스터 관리자에 의한 노드 구성 필요 @@ -85,8 +86,9 @@ Docker *18.06 또는 그 이상* 을 사용하길 바란다. 더 낮은 버전 클러스터 내에서 모든 파드는 해당 레지스트리에 있는 이미지에 읽기 접근 권한을 가질 것이다. -Kubelet은 해당 인스턴스의 Google 서비스 계정을 이용하여 GCR을 인증할 것이다. -인스턴스의 서비스 계정은 `https://www.googleapis.com/auth/devstorage.read_only`라서, +Kubelet은 해당 인스턴스의 Google 서비스 계정을 이용하여 +GCR을 인증할 것이다. 인스턴스의 서비스 계정은 +`https://www.googleapis.com/auth/devstorage.read_only`라서, 프로젝트의 GCR로부터 풀은 할 수 있지만 푸시는 할 수 없다. ### Amazon Elastic Container Registry 사용 @@ -144,12 +146,11 @@ kubelet은 ECR 자격 증명을 가져오고 주기적으로 갱신할 것이다 [쿠버네티스 시크릿을 구성하고 그것을 파드 디플로이를 위해서 사용](/ko/docs/concepts/containers/images/#파드에-imagepullsecrets-명시)할 수 있다. ### IBM 클라우드 컨테이너 레지스트리 사용 -IBM 클라우드 컨테이너 레지스트리는 멀티-테넌트 프라이빗 이미지 레지스트리를 제공하여 사용자가 Docker 이미지를 안전하게 저장하고 공유할 수 있도록 한다. 기본적으로, -프라이빗 레지스트리의 이미지는 통합된 취약점 조언기(Vulnerability Advisor)를 통해 조사되어 보안 이슈와 잠재적 취약성을 검출한다. IBM 클라우드 계정의 모든 사용자가 이미지에 접근할 수 있도록 하거나, 레지스트리 네임스페이스에 접근을 승인하는 토큰을 생성할 수 있다. +IBM 클라우드 컨테이너 레지스트리는 멀티-테넌트 프라이빗 이미지 레지스트리를 제공하여 사용자가 이미지를 안전하게 저장하고 공유할 수 있도록 한다. 기본적으로, 프라이빗 레지스트리의 이미지는 통합된 취약점 조언기(Vulnerability Advisor)를 통해 조사되어 보안 이슈와 잠재적 취약성을 검출한다. IBM 클라우드 계정의 모든 사용자가 이미지에 접근할 수 있도록 하거나, IAM 역할과 정책으로 IBM 클라우드 컨테이너 레지스트리 네임스페이스의 접근 권한을 부여해서 사용할 수 있다. -IBM 클라우드 컨테이너 레지스트리 CLI 플러그인을 설치하고 사용자 이미지를 위한 네임스페이스를 생성하기 위해서는, [IBM 클라우드 컨테이너 레지스트리 시작하기](https://cloud.ibm.com/docs/services/Registry?topic=registry-getting-started)를 참고한다. +IBM 클라우드 컨테이너 레지스트리 CLI 플러그인을 설치하고 사용자 이미지를 위한 네임스페이스를 생성하기 위해서는, [IBM 클라우드 컨테이너 레지스트리 시작하기](https://cloud.ibm.com/docs/Registry?topic=registry-getting-started)를 참고한다. -[IBM 클라우드 퍼블릭 이미지](https://cloud.ibm.com/docs/services/Registry?topic=registry-public_images) 및 사용자의 프라이빗 이미지로부터 컨테이너를 사용자의 IBM 클라우드 쿠버네티스 서비스 클러스터의 `default` 네임스페이스에 디플로이하기 위해서 IBM 클라우드 컨테이너 레지스트리를 사용하면 된다. 컨테이너를 다른 네임스페이스에 디플로이하거나, 다른 IBM 클라우드 컨테이너 레지스트리 지역 또는 IBM 클라우드 계정을 사용하기 위해서는, 쿠버네티스 `imagePullSecret`를 생성한다. 더 자세한 정보는, [이미지로부터 컨테이너 빌드하기](https://cloud.ibm.com/docs/containers?topic=containers-images)를 참고한다. +다른 추가적인 구성이 없는 IBM 클라우드 쿠버네티스 서비스 클러스터의 IBM 클라우드 컨테이너 레지스트리 내 기본 네임스페이스에 저장되어 있는 배포된 이미지를 동일 계정과 동일 지역에서 사용하려면 [이미지로부터 컨테이너 빌드하기](https://cloud.ibm.com/docs/containers?topic=containers-images)를 본다. 다른 구성 옵션에 대한 것은 [레지스트리부터 클러스터에 이미지를 가져오도록 권한을 부여하는 방법 이해하기](https://cloud.ibm.com/docs/containers?topic=containers-registry#cluster_registry_auth)를 본다. ### 프라이빗 레지스트리에 대한 인증을 위한 노드 구성 @@ -239,6 +240,7 @@ kubectl describe pods/private-image-test-1 | grep 'Failed' Fri, 26 Jun 2015 15:36:13 -0700 Fri, 26 Jun 2015 15:39:13 -0700 19 {kubelet node-i2hq} spec.containers{uses-private-image} failed Failed to pull image "user/privaterepo:v1": Error: image user/privaterepo:v1 not found ``` + 클러스터의 모든 노드가 반드시 동일한 `.docker/config.json`를 가져야 한다. 그렇지 않으면, 파드가 일부 노드에서만 실행되고 다른 노드에서는 실패할 것이다. 예를 들어, 노드 오토스케일링을 사용한다면, 각 인스턴스 템플릿은 `.docker/config.json`을 포함하거나 그것을 포함한 드라이브를 마운트해야 한다. @@ -362,7 +364,6 @@ imagePullSecrets을 셋팅하여 자동화할 수 있다. - 테넌트는 해당 시크릿을 각 네임스페이스의 imagePullSecrets에 추가한다. - 다중 레지스트리에 접근해야 하는 경우, 각 레지스트리에 대해 하나의 시크릿을 생성할 수 있다. Kubelet은 모든`imagePullSecrets` 파일을 하나의 가상`.docker / config.json` 파일로 병합한다. diff --git a/content/ko/docs/concepts/overview/working-with-objects/names.md b/content/ko/docs/concepts/overview/working-with-objects/names.md index 0804c0d425..0ab2681a77 100644 --- a/content/ko/docs/concepts/overview/working-with-objects/names.md +++ b/content/ko/docs/concepts/overview/working-with-objects/names.md @@ -1,5 +1,5 @@ --- -title: 이름(Name) +title: 오브젝트 이름과 ID content_template: templates/concept weight: 20 --- @@ -22,7 +22,35 @@ weight: 20 {{< glossary_definition term_id="name" length="all" >}} -관례에 따라, 쿠버네티스 리소스의 이름은 최대 253자까지 허용되고 소문자 알파벳과 숫자(alphanumeric), `-`, 그리고 `.`로 구성되며 특정 리소스는 보다 구체적인 제약을 갖는다. +다음은 리소스에 일반적으로 사용되는 세가지 유형의 이름 제한 조건이다. + +### DNS 서브도메인 이름들 + +대부분의 리소스 유형에는 [RFC 1123](https://tools.ietf.org/html/rfc1123)에 정의된 대로 +DNS 서브도메인 이름으로 사용할 수 있는 이름이 필요하다. +이것은 이름이 다음을 충족해야 한다는 것을 의미한다. + +- 253자를 넘지 말아야 한다. +- 소문자와 영숫자 `-` 또는 `.` 만 포함한다. +- 영숫자로 시작한다. +- 영숫자로 끝난다. + +### DNS 레이블 이름 + +일부 리소스 유형은 [RFC 1123](https://tools.ietf.org/html/rfc1123)에 +정의된 대로 DNS 레이블 표준을 따라야 한다. +이것은 이름이 다음을 충족해야 한다는 것을 의미한다. + +- 최대 63자이다. +- 소문자와 영숫자 또는 `-` 만 포함한다. +- 영숫자로 시작한다. +- 영숫자로 끝난다. + +### 경로 세그먼트 이름 + +일부 리소스 유형에서는 이름을 경로 세그먼트로 안전하게 인코딩 할 수 +있어야 한다. 즉 이름이 "." 또는 ".."이 아닐 수 있으며 이름에는 +"/" 또는 "%"가 포함될 수 없다. 여기 파드의 이름이 `nginx-demo`라는 매니페스트 예시가 있다. @@ -39,6 +67,7 @@ spec: - containerPort: 80 ``` + {{< note >}} 일부 리소스 유형은 이름에 추가적인 제약이 있다. {{< /note >}} diff --git a/content/ko/docs/concepts/security/_index.md b/content/ko/docs/concepts/security/_index.md new file mode 100644 index 0000000000..079e3dd8f8 --- /dev/null +++ b/content/ko/docs/concepts/security/_index.md @@ -0,0 +1,4 @@ +--- +title: "보안" +weight: 81 +--- diff --git a/content/ko/docs/concepts/security/overview.md b/content/ko/docs/concepts/security/overview.md new file mode 100644 index 0000000000..a8f5f050a4 --- /dev/null +++ b/content/ko/docs/concepts/security/overview.md @@ -0,0 +1,161 @@ +--- +title: 클라우드 네이티브 보안 개요 +content_template: templates/concept +weight: 1 +--- + +{{< toc >}} + +{{% capture overview %}} +쿠버네티스 보안(일반적인 보안)은 관련된 많은 부분이 상호작용하는 +방대한 주제다. 오늘날에는 웹 애플리케이션의 실행을 돕는 +수많은 시스템에 오픈소스 소프트웨어가 통합되어 있으며, +전체적인 보안에 대하여 생각할 수 있는 방법에 대한 통찰력을 도울 수 있는 +몇 가지 중요한 개념이 있다. 이 가이드는 클라우드 네이티브 보안과 관련된 +몇 가지 일반적인 개념에 대한 멘탈 모델(mental model)을 정의한다. 멘탈 모델은 완전히 임의적이며 +소프트웨어 스택을 보호할 위치를 생각하는데 도움이되는 경우에만 사용해야 +한다. +{{% /capture %}} + +{{% capture body %}} + +## 클라우드 네이티브 보안의 4C +계층적인 보안에 대해서 어떻게 생각할 수 있는지 이해하는 데 도움이 될 수 있는 다이어그램부터 살펴보자. +{{< note >}} +이 계층화된 접근 방식은 보안에 대한 [심층 방어](https://en.wikipedia.org/wiki/Defense_in_depth_(computing)) +접근 방식을 강화하며, 소프트웨어 시스템의 보안을 위한 모범 사례로 +널리 알려져 있다. 4C는 클라우드(Cloud), 클러스터(Clusters), 컨테이너(Containers) 및 코드(Code)이다. +{{< /note >}} + +{{< figure src="/images/docs/4c.png" title="클라우드 네이티브 보안의 4C" >}} + + +위 그림에서 볼 수 있듯이, +4C는 각각의 사각형의 보안에 따라 다르다. 코드 +수준의 보안만 처리하여 클라우드, 컨테이너 및 코드의 열악한 보안 표준으로부터 +보호하는 것은 거의 불가능하다. 그러나 이런 영역들의 보안이 적절하게 +처리되고, 코드에 보안을 추가한다면 이미 강력한 기반이 더욱 +강화될 것이다. 이러한 관심 분야는 아래에서 더 자세히 설명한다. + +## 클라우드 + +여러 면에서 클라우드(또는 공동 위치 서버, 또는 기업의 데이터 센터)는 쿠버네티스 클러스터 구성을 위한 +[신뢰 컴퓨팅 기반(trusted computing base)](https://en.wikipedia.org/wiki/Trusted_computing_base) +이다. 이러한 구성 요소 자체가 취약하거나(또는 취약한 방법으로 구성된) +경우 이 기반 위에서 구축된 모든 구성 요소의 보안을 +실제로 보장할 방법이 없다. 각 클라우드 공급자는 그들의 환경에서 워크로드를 +안전하게 실행하는 방법에 대해 고객에게 광범위한 보안 권장 사항을 +제공한다. 모든 클라우드 공급자와 워크로드는 다르기 때문에 +클라우드 보안에 대한 권장 사항을 제공하는 것은 이 가이드의 범위를 벗어난다. 다음은 +알려진 클라우드 공급자의 보안 문서의 일부와 +쿠버네티스 클러스터를 구성하기 위한 인프라 +보안에 대한 일반적인 지침을 제공한다. + +### 클라우드 공급자 보안 표 + + + +IaaS 공급자 | 링크 | +-------------------- | ------------ | +Alibaba Cloud | https://www.alibabacloud.com/trust-center | +Amazon Web Services | https://aws.amazon.com/security/ | +Google Cloud Platform | https://cloud.google.com/security/ | +IBM Cloud | https://www.ibm.com/cloud/security | +Microsoft Azure | https://docs.microsoft.com/en-us/azure/security/azure-security | +VMWare VSphere | https://www.vmware.com/security/hardening-guides.html | + + +자체 하드웨어나 다른 클라우드 공급자를 사용하는 경우 보안에 대한 +모범 사례는 해당 문서를 참조한다. + +### 일반적인 인프라 지침 표 + +쿠버네티스 인프라에서 고려할 영역 | 추천 | +--------------------------------------------- | ------------ | +API 서버에 대한 네트워크 접근(마스터) | 이상적으로는 인터넷에서 쿠버네티스 마스터에 대한 모든 접근을 공개적으로 허용하지 않으며 클러스터를 관리하는데 필요한 IP 주소 집합으로 제한된 네트워크 접근 제어 목록(ACL)에 의해 제어되어야 한다. | +노드에 대한 네트워크 접근(워커 서버) | 노드는 마스터의 지정된 포트 연결_만_ 허용하고(네트워크 접근 제어 목록의 사용), NodePort와 LoadBalancer 유형의 쿠버네티스 서비스에 대한 연결을 허용하도록 구성해야 한다. 가능한 노드가 공용 인터넷에 완전히 노출되어서는 안된다. +클라우드 공급자 API에 대한 쿠버네티스 접근 | 각 클라우드 공급자는 쿠버네티스 마스터 및 노드에 서로 다른 권한을 부여해야 함으로써, 이런 권장 사항이 더 일반적이다. 관리해야 하는 리소스에 대한 [최소 권한의 원칙](https://en.wikipedia.org/wiki/Principle_of_least_privilege)을 따르는 클라우드 공급자의 접근 권한을 클러스터에 구성하는 것이 가장 좋다. AWS의 Kops에 대한 예제: https://github.com/kubernetes/kops/blob/master/docs/iam_roles.md#iam-roles +etcd에 대한 접근 | etcd (쿠버네티스의 데이터저장소)에 대한 접근은 마스터로만 제한되어야 한다. 구성에 따라 TLS를 통해 etcd를 사용해야 한다. 자세한 정보: https://github.com/etcd-io/etcd/tree/master/Documentation#security +etcd 암호화 | 가능한 모든 드라이브를 유휴 상태에서 암호화 하는 것이 좋은 방법이지만, etcd는 전체 클러스터(시크릿 포함)의 상태를 유지하고 있기에 디스크의 암호화는 유휴 상태에서 암호화 되어야 한다. + +## 클러스터 + +이 섹션에서는 쿠버네티스의 워크로드 +보안을 위한 링크를 제공한다. 쿠버네티스 +보안에 영향을 미치는 다음 두 가지 영역이 있다. + +* 클러스터를 구성하는 설정 가능한 컴포넌트의 보안 +* 클러스터에서 실행되는 컴포넌트의 보안 + +### 클러스터_의_ 컴포넌트 + +우발적이거나 악의적인 접근으로부터 클러스터를 보호하고, +모범 사례에 대한 정보를 채택하기 위해서는 +[클러스터 보안](/docs/tasks/administer-cluster/securing-a-cluster/)에 대한 조언을 읽고 따른다. + +### 클러스터 _내_ 컴포넌트(애플리케이션) +애플리케이션의 공격 영역에 따라, 보안의 특정 측면에 +중점을 둘 수 있다. 예를 들어, 다른 리소스 체인에 중요한 서비스(서비스 A)와 +리소스 소진 공격에 취약한 별도의 작업 부하(서비스 B)를 실행하는 경우, +리소스 제한을 설정하지 않은 서비스 B에 의해 +서비스 A 또한 손상시킬 위험이 있다. 다음은 쿠버네티스에서 +실행 중인 워크로드를 보호할 때 고려해야 할 사항에 대한 링크 표이다. + +워크로드 보안에서 고려할 영역 | 추천 | +------------------------------ | ------------ | +RBAC 인증(쿠버네티스 API에 대한 접근) | https://kubernetes.io/docs/reference/access-authn-authz/rbac/ +인증 | https://kubernetes.io/docs/reference/access-authn-authz/controlling-access/ +애플리케이션 시크릿 관리(및 유휴 상태에서의 etcd 암호화 등) | https://kubernetes.io/docs/concepts/configuration/secret/
    https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/ +파드 보안 정책 | https://kubernetes.io/docs/concepts/policy/pod-security-policy/ +서비스 품질(및 클러스터 리소스 관리) | https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/ +네트워크 정책 | https://kubernetes.io/ko/docs/concepts/services-networking/network-policies/ +쿠버네티스 인그레스를 위한 TLS | https://kubernetes.io/ko/docs/concepts/services-networking/ingress/#tls + + + +## 컨테이너 + +쿠버네티스에서 소프트웨어를 실행하려면, 소프트웨어는 컨테이너에 있어야 한다. 이로 인해, +쿠버네티스의 원시적인 워크로드 보안으로부터 이점을 얻기 위해서 +반드시 고려해야 할 보안 사항이 있다. 컨테이너 보안 +또한 이 가이드의 범위를 벗어나지만, 해당 주제에 대한 추가적인 설명을 위하여 +일반 권장사항 및 링크 표를 아래에 제공한다. + +컨테이너에서 고려할 영역 | 추천 | +------------------------------ | ------------ | +컨테이너 취약점 스캔 및 OS에 종속적인 보안 | 이미지 빌드 단계의 일부 또는 정기적으로 [CoreOS의 Clair](https://github.com/coreos/clair/)와 같은 도구를 사용해서 컨테이너에 알려진 취약점이 있는지 검사한다. +이미지 서명 및 시행 | 두 개의 다른 CNCF 프로젝트(TUF 와 Notary)는 컨테이너 이미지에 서명하고 컨테이너 내용에 대한 신뢰 시스템을 유지하는데 유용한 도구이다. 도커를 사용하는 경우 도커 엔진에 [도커 컨텐츠 신뢰](https://docs.docker.com/engine/security/trust/content_trust/)가 내장되어 있다. 시행 부분에서의 [IBM의 Portieris](https://github.com/IBM/portieris) 프로젝트는 쿠버네티스 다이나믹 어드미션 컨트롤러로 실행되는 도구로, 클러스터에서 허가하기 전에 Notary를 통해 이미지가 적절하게 서명되었는지 확인한다. +권한있는 사용자의 비허용 | 컨테이너를 구성할 때 컨테이너의 목적을 수행하는데 필요한 최소 권한을 가진 사용자를 컨테이너 내에 만드는 방법에 대해서는 설명서를 참조한다. + +## 코드 + +마지막으로 애플리케이션의 코드 수준으로 내려가면, 가장 많은 제어를 할 수 있는 +주요 공격 영역 중 하나이다. 이런 코드 수준은 쿠버네티스의 범위 +밖이지만 몇가지 권장사항이 있다. + +### 일반적인 코드 보안 지침표 + +코드에서 고려할 영역 | 추천 | +--------------------------------------------- | ------------ | +TLS를 통한 접근 | 코드가 TCP를 통해 통신해야 한다면, 클라이언트와 먼저 TLS 핸드 셰이크를 수행하는 것이 이상적이다. 몇 가지 경우를 제외하고, 기본 동작은 전송 중인 모든 것을 암호화하는 것이다. 한걸음 더 나아가, VPC의 "방화벽 뒤"에서도 서비스 간 네트워크 트래픽을 암호화하는 것이 좋다. 이것은 인증서를 가지고 있는 두 서비스의 양방향 검증을 [mTLS](https://en.wikipedia.org/wiki/Mutual_authentication)를 통해 수행할 수 있다. 이것을 수행하기 위해 쿠버네티스에는 [Linkerd](https://linkerd.io/) 및 [Istio](https://istio.io/)와 같은 수많은 도구가 있다. | +통신 포트 범위 제한 | 이 권장사항은 당연할 수도 있지만, 가능하면 통신이나 메트릭 수집에 꼭 필요한 서비스의 포트만 노출시켜야 한다. | +타사 종속성 보안 | 애플리케이션은 자체 코드베이스의 외부에 종속적인 경향이 있기 때문에, 코드의 종속성을 정기적으로 스캔하여 현재 알려진 취약점이 없는지 확인하는 것이 좋다. 각 언어에는 이런 검사를 자동으로 수행하는 도구를 가지고 있다. | +정적 코드 분석 | 대부분 언어에는 잠재적으로 안전하지 않은 코딩 방법에 대해 코드 스니펫을 분석할 수 있는 방법을 제공한다. 가능한 언제든지 일반적인 보안 오류에 대해 코드베이스를 스캔할 수 있는 자동화된 도구를 사용하여 검사를 한다. 도구는 다음에서 찾을 수 있다: https://www.owasp.org/index.php/Source_Code_Analysis_Tools | +동적 탐지 공격 | 일반적으로 서비스에서 발생할 수 있는 잘 알려진 공격 중 일부를 서비스에 테스트할 수 있는 자동화된 몇 가지 도구가 있다. 이런 잘 알려진 공격에는 SQL 인젝션, CSRF 및 XSS가 포함된다. 가장 널리 사용되는 동적 분석 도구는 OWASP Zed Attack 프록시다. https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project | + + +## 강력한(robust) 자동화 + +위에서 언급한 대부분의 제안사항은 실제로 일련의 보안 검사의 일부로 코드를 +전달하는 파이프라인에 의해 자동화 될 수 있다. 소프트웨어 전달을 위한 +"지속적인 해킹(Continuous Hacking)"에 대한 접근 방식에 대해 알아 보려면, 자세한 설명을 제공하는 [이 기사](https://thenewstack.io/beyond-ci-cd-how-continuous-hacking-of-docker-containers-and-pipeline-driven-security-keeps-ygrene-secure/)를 참고한다. + +{{% /capture %}} +{{% capture whatsnext %}} +* [파드에 대한 네트워크 정책](/docs/concepts/services-networking/network-policies/) 알아보기 +* [클러스터 보안](/docs/tasks/administer-cluster/securing-a-cluster/)에 대해 알아보기 +* [API 접근 통제](/docs/reference/access-authn-authz/controlling-access/)에 대해 알아보기 +* 컨트롤 플레인에 대한 [전송 데이터 암호화](/docs/tasks/tls/managing-tls-in-a-cluster/) 알아보기 +* [Rest에서 데이터 암호화](/docs/tasks/administer-cluster/encrypt-data/) 알아보기 +* [쿠버네티스 시크릿](/docs/concepts/configuration/secret/)에 대해 알아보기 +{{% /capture %}} diff --git a/content/ko/docs/concepts/services-networking/dual-stack.md b/content/ko/docs/concepts/services-networking/dual-stack.md index 9d58bccbd6..0c52346820 100644 --- a/content/ko/docs/concepts/services-networking/dual-stack.md +++ b/content/ko/docs/concepts/services-networking/dual-stack.md @@ -51,7 +51,7 @@ IPv4/IPv6 이중 스택을 활성화 하려면, 클러스터의 관련 구성요 * `--feature-gates="IPv6DualStack=true"` * kube-proxy: * `--proxy-mode=ipvs` - * `--cluster-cidrs=,` + * `--cluster-cidr=,` * `--feature-gates="IPv6DualStack=true"` {{< caution >}} diff --git a/content/ko/docs/concepts/services-networking/ingress.md b/content/ko/docs/concepts/services-networking/ingress.md index 793a1520e3..64d610a499 100644 --- a/content/ko/docs/concepts/services-networking/ingress.md +++ b/content/ko/docs/concepts/services-networking/ingress.md @@ -334,7 +334,7 @@ spec: {{< note >}} TLS 기능을 제공하는 다양한 인그레스 컨트롤러간의 기능 차이가 있다. 사용자 환경에서의 TLS의 작동 방식을 이해하려면 -[nginx](https://git.k8s.io/ingress-nginx/README.md#https), +[nginx](https://kubernetes.github.io/ingress-nginx/user-guide/tls/), [GCE](https://git.k8s.io/ingress-gce/README.md#frontend-https) 또는 기타 플랫폼의 특정 인그레스 컨트롤러에 대한 설명서를 참조한다. {{< /note >}} diff --git a/content/ko/docs/concepts/services-networking/service.md b/content/ko/docs/concepts/services-networking/service.md index 1c33fb3008..6d47a2c2aa 100644 --- a/content/ko/docs/concepts/services-networking/service.md +++ b/content/ko/docs/concepts/services-networking/service.md @@ -1189,7 +1189,7 @@ kube-proxy는 유저스페이스 모드에 있을 때 SCTP 연결 관리를 지 {{% capture whatsnext %}} -* [서비스와 애플리케이션 연결](/docs/concepts/services-networking/connect-applications-service/) 알아보기 +* [서비스와 애플리케이션 연결](/ko/docs/concepts/services-networking/connect-applications-service/) 알아보기 * [인그레스](/ko/docs/concepts/services-networking/ingress/)에 대해 알아보기 * [엔드포인트슬라이스](/ko/docs/concepts/services-networking/endpoint-slices/)에 대해 알아보기 diff --git a/content/ko/docs/concepts/storage/volume-pvc-datasource.md b/content/ko/docs/concepts/storage/volume-pvc-datasource.md new file mode 100644 index 0000000000..ab9f1db2ca --- /dev/null +++ b/content/ko/docs/concepts/storage/volume-pvc-datasource.md @@ -0,0 +1,65 @@ +--- +title: CSI 볼륨 복제하기 +content_template: templates/concept +weight: 30 +--- + +{{% capture overview %}} + +{{< feature-state for_k8s_version="v1.16" state="beta" >}} +이 문서에서는 쿠버네티스의 기존 CSI 볼륨 복제의 개념을 설명한다. [볼륨] +(/ko/docs/concepts/storage/volumes)을 숙지하는 것을 추천한다. + +{{% /capture %}} + + +{{% capture body %}} + +## 소개 + +{{< glossary_tooltip text="CSI" term_id="csi" >}} 볼륨 복제 기능은 `dataSource` 필드에 기존 {{< glossary_tooltip text="PVC" term_id="persistent-volume-claim" >}}를 지정하는 지원을 추가해서 사용자가 {{< glossary_tooltip term_id="volume" >}}을 복제하려는 것을 나타낸다. + +복제는 표준 볼륨처럼 소비할 수 있는 쿠버네티스 볼륨의 복제본으로 정의된다. 유일한 차이점은 프로비저닝할 때 "새" 빈 볼륨을 생성하는 대신에 백엔드 장치가 지정된 볼륨의 정확한 복제본을 생성한다는 것이다. + +쿠버네티스 API의 관점에서 복제를 구현하면 새로운 PVC 생성 중에 기존 PVC를 데이터 소스로 지정할 수 있는 기능이 추가된다. 소스 PVC는 바인딩되어있고, 사용가능해야 한다(사용 중이 아니어야함). + +사용자는 이 기능을 사용할 때 다음 사항을 알고 있어야 한다. + +* 복제 지원(`VolumePVCDataSource`)은 CSI 드라이버에서만 사용할 수 있다. +* 복제 지원은 동적 프로비저너만 사용할 수 있다. +* CSI 드라이버는 볼륨 복제 기능을 구현했거나 구현하지 않았을 수 있다. +* PVC는 대상 PVC와 동일한 네임스페이스에 있는 경우에만 복제할 수 있다(소스와 대상은 동일한 네임스페이스에 있어야 함). +* 복제는 동일한 스토리지 클래스 내에서만 지원된다. + - 대상 볼륨은 소스와 동일한 스토리지 클래스여야 한다. + - 기본 스토리지 클래스를 사용할 수 있으며, 사양에 storageClassName을 생략할 수 있다. + + +## 프로비저닝 + +동일한 네임스페이스에서 기존 PVC를 참조하는 dataSource를 추가하는 것을 제외하고는 다른 PVC와 마찬가지로 복제가 프로비전된다. + +```yaml +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: clone-of-pvc-1 + namespace: myns +spec: + accessModes: + - ReadWriteOnce + storageClassName: cloning + resources: + requests: + storage: 5Gi + dataSource: + kind: PersistentVolumeClaim + name: pvc-1 +``` + +그 결과로 지정된 소스 `pvc-1` 과 동일한 내용을 가진 `clone-of-pvc-1` 이라는 이름을 가지는 새로운 PVC가 생겨난다. + +## 사용 + +새 PVC를 사용할 수 있게 되면, 복제된 PVC는 다른 PVC와 동일하게 소비된다. 또한, 이 시점에서 새롭게 생성된 PVC는 독립된 오브젝트이다. 원본 dataSource PVC와는 무관하게 독립적으로 소비하고, 복제하고, 스냅샷의 생성 또는 삭제를 할 수 있다. 이는 소스가 새롭게 생성된 복제본에 어떤 방식으로든 연결되어 있지 않으며, 새롭게 생성된 복제본에 영향 없이 수정하거나, 삭제할 수도 있는 것을 의미한다. + +{{% /capture %}} diff --git a/content/ko/docs/concepts/storage/volume-snapshot-classes.md b/content/ko/docs/concepts/storage/volume-snapshot-classes.md new file mode 100644 index 0000000000..f4d2991238 --- /dev/null +++ b/content/ko/docs/concepts/storage/volume-snapshot-classes.md @@ -0,0 +1,65 @@ +--- +title: 볼륨 스냅샷 클래스 +content_template: templates/concept +weight: 30 +--- + +{{% capture overview %}} + +이 문서는 쿠버네티스의 `VolumeSnapshotClass` 개요를 설명한다. +[볼륨 스냅샷](/docs/concepts/storage/volume-snapshots/)과 +[스토리지 클래스](/docs/concepts/storage/storage-classes)의 숙지를 추천한다. + +{{% /capture %}} + + +{{% capture body %}} + +## 소개 + +`StorageClass` 는 관리자가 볼륨을 프로비저닝할 때 제공하는 스토리지의 "클래스"를 +설명하는 방법을 제공하는 것처럼, `VolumeSnapshotClass` 는 볼륨 스냅샷을 +프로비저닝할 때 스토리지의 "클래스"를 설명하는 방법을 제공한다. + +## VolumeSnapshotClass 리소스 + +각 `VolumeSnapshotClass` 에는 클래스에 속하는 `VolumeSnapshot` 을 +동적으로 프로비전 할 때 사용되는 `driver`, `deletionPolicy` 그리고 `parameters` +필드를 포함한다. + +`VolumeSnapshotClass` 오브젝트의 이름은 중요하며, 사용자가 특정 +클래스를 요청할 수 있는 방법이다. 관리자는 `VolumeSnapshotClass` 오브젝트를 +처음 생성할 때 클래스의 이름과 기타 파라미터를 설정하고, 오브젝트가 +생성된 이후에는 업데이트할 수 없다. + +관리자는 특정 클래스의 바인딩을 요청하지 않는 VolumeSnapshots에만 +기본 `VolumeSnapshotClass` 를 지정할 수 있다. + +```yaml +apiVersion: snapshot.storage.k8s.io/v1beta1 +kind: VolumeSnapshotClass +metadata: + name: csi-hostpath-snapclass +driver: hostpath.csi.k8s.io +deletionPolicy: Delete +parameters: +``` + +### 드라이버 + +볼륨 스냅샷 클래스에는 VolumeSnapshots의 프로비저닝에 사용되는 CSI 볼륨 플러그인을 +결정하는 드라이버를 가지고 있다. 이 필드는 반드시 지정해야한다. + +### 삭제정책(DeletionPolicy) + +볼륨 스냅샷 클래스는 삭제정책을 가지고 있다. 바인딩 된 `VolumeSnapshot` 오브젝트를 삭제할 때 `VolumeSnapshotContent` 의 상황을 구성할 수 있다. 볼륨 스냅삿의 삭제정책은 `Retain` 또는 `Delete` 일 수 있다. 이 필드는 반드시 지정해야 한다. + +삭제정책이 `Delete` 인 경우 기본 스토리지 스냅샷이 `VolumeSnapshotContent` 오브젝트와 함께 삭제된다. 삭제정책이 `Retain` 인 경우 기본 스냅샷과 `VolumeSnapshotContent` 모두 유지된다. + +## 파라미터 + +볼륨 스냅샷 클래스에는 볼륨 스냅샷 클래스에 속하는 볼륨 스냅샷을 +설명하는 파라미터를 가지고 있다. `driver` 에 따라 다른 파라미터를 사용할 +수 있다. + +{{% /capture %}} diff --git a/content/ko/docs/concepts/workloads/controllers/cron-jobs.md b/content/ko/docs/concepts/workloads/controllers/cron-jobs.md index ff76d12f86..4e912069ec 100644 --- a/content/ko/docs/concepts/workloads/controllers/cron-jobs.md +++ b/content/ko/docs/concepts/workloads/controllers/cron-jobs.md @@ -13,9 +13,14 @@ _크론 잡은_ 시간 기반의 일정에 따라 [잡](/docs/concepts/workloads 하나의 크론잡 객체는 _크론탭_ (크론 테이블) 파일의 한 줄과 같다. 크론잡은 잡을 [크론](https://en.wikipedia.org/wiki/Cron)형식으로 쓰여진 주어진 일정에 따라 주기적으로 동작시킨다. -{{< note >}} -모든 **크론잡** `일정:` 시간은 잡이 처음 시작된 마스터의 시간대를 기반으로 한다. -{{< /note >}} +{{< caution >}} +모든 **크론잡** `일정:` 시간은 {{< glossary_tooltip term_id="kube-controller-manager" text="kube-controller-manager" >}} +의 시간대를 기준으로 한다. + +컨트롤 플레인이 파드 또는 베어 컨테이너에서 kube-controller-manager를 +실행하는 경우 kube-controller-manager 컨테이너의 설정된 시간대는 크론 잡 컨트롤러가 +사용하는 시간대로 설정한다. +{{< /caution >}} 크론잡 리소스에 대한 매니페스트를 생성할때에는 제공하는 이름이 52자 이하인지 확인해야 한다. 이는 크론잡 컨트롤러는 제공된 잡 이름에 diff --git a/content/ko/docs/concepts/workloads/controllers/jobs-run-to-completion.md b/content/ko/docs/concepts/workloads/controllers/jobs-run-to-completion.md new file mode 100644 index 0000000000..939b6e8293 --- /dev/null +++ b/content/ko/docs/concepts/workloads/controllers/jobs-run-to-completion.md @@ -0,0 +1,477 @@ +--- +title: 잡 - 실행부터 완료까지 +content_template: templates/concept +feature: + title: 배치 실행 + description: > + 쿠버네티스는 서비스 외에도 배치와 CI 워크로드를 관리할 수 있으며, 원하는 경우 실패한 컨테이너를 교체할 수 있다. +weight: 70 +--- + +{{% capture overview %}} + +잡에서 하나 이상의 파드를 생성하고 지정된 수의 파드가 성공적으로 종료되도록 한다. +파드가 성공적으로 완료되면, 성공적으로 완료된 잡을 추적한다. 지정된 수의 +성공 완료에 도달하면, 작업(즉, 잡)이 완료된다. 잡을 삭제하면 잡이 생성한 +파드가 정리된다. + +간단한 사례는 잡 오브젝트를 하나 생성해서 파드 하나를 안정적으로 실행하고 완료하는 것이다. +첫 번째 파드가 실패 또는 삭제된 경우(예로는 노드 하드웨어의 실패 또는 +노드 재부팅) 잡 오브젝트는 새로운 파드를 기동시킨다. + +잡을 사용하면 여러 파드를 병렬로 실행할 수도 있다. + +{{% /capture %}} + + +{{% capture body %}} + +## 예시 잡 실행하기 + +다음은 잡 설정 예시이다. 예시는 파이(π)의 2000 자리까지 계산해서 출력한다. +이를 완료하는 데 약 10초가 소요된다. + +{{< codenew file="controllers/job.yaml" >}} + +이 명령으로 예시를 실행할 수 있다. + +```shell +kubectl apply -f https://k8s.io/examples/controllers/job.yaml +``` +``` +job.batch/pi created +``` + +`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 +``` + +`kubectl get pods` 를 사용해서 잡의 완료된 파드를 본다. + +잡에 속하는 모든 파드를 기계적으로 읽을 수 있는 양식으로 나열하려면, 다음과 같은 명령을 사용할 수 있다. + +```shell +pods=$(kubectl get pods --selector=job-name=pi --output=jsonpath='{.items[*].metadata.name}') +echo $pods +``` +``` +pi-5rwd7 +``` + +여기서 셀렉터는 잡의 셀렉터와 동일하다. `--output=jsonpath` 옵션은 반환된 목록의 +각각의 파드에서 이름을 가져와서 표현하는 방식을 지정한다. + +파드 중 하나를 표준 출력으로 본다. + +```shell +kubectl logs $pods +``` +다음과 유사하게 출력된다. +```shell +3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632788659361533818279682303019520353018529689957736225994138912497217752834791315155748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035637076601047101819429555961989467678374494482553797747268471040475346462080466842590694912933136770289891521047521620569660240580381501935112533824300355876402474964732639141992726042699227967823547816360093417216412199245863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818347977535663698074265425278625518184175746728909777727938000816470600161452491921732172147723501414419735685481613611573525521334757418494684385233239073941433345477624168625189835694855620992192221842725502542568876717904946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886269456042419652850222106611863067442786220391949450471237137869609563643719172874677646575739624138908658326459958133904780275901 +``` + +## 잡 사양 작성하기 + +다른 쿠버네티스의 설정과 마찬가지로 잡에는 `apiVersion`, `kind` 그리고 `metadata` 필드가 필요하다. + +잡에는 [`.spec` 섹션](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status)도 필요하다. + +### 파드 템플릿 + +`.spec.template` 은 `.spec` 의 유일한 필수 필드이다. + +`.spec.template` 은 [파드 템플릿](/ko/docs/concepts/workloads/pods/pod-overview/#파드-템플릿)이다. 이것은 `apiVersion` 또는 `kind` 가 없다는 것을 제외한다면 [파드](/ko/docs/concepts/workloads/pods/pod/)와 정확하게 같은 스키마를 가지고 있다. + +추가로 파드의 필수 필드 외에도 잡의 파드 템플릿은 적절한 +레이블([파드 셀렉터](#파드-셀렉터)를 본다)과 적절한 재시작 정책을 명시해야 한다. + +`Never` 또는 `OnFailure` 와 같은 [`RestartPolicy`](/ko/docs/concepts/workloads/pods/pod-lifecycle/#재시작-정책)만 허용된다. + +### 파드 셀렉터 + +`.spec.selector` 필드는 선택 사항이다. 대부분의 케이스에서 지정해서는 안된다. +[자신의 파드 셀렉터를 지정하기](#자신의-파드-셀렉터를-지정하기) 섹션을 참고한다. + + +### 병렬 잡 + +잡으로 실행하기에 적합한 작업 유형은 크게 세 가지가 있다. + +1. 비-병렬(Non-parallel) 잡: + - 일반적으로, 파드가 실패하지 않은 한, 하나의 파드만 시작된다. + - 파드가 성공적으로 종료하자마자 즉시 잡이 완료된다. +1. *고정적(fixed)인 완료 횟수* 를 가진 병렬 잡: + - `.spec.completions` 에 0이 아닌 양수 값을 지정한다. + - 잡은 전체 작업을 나타내며 1에서 `.spec.completions` 까지의 범위의 각 값에 대해 한 개씩 성공한 파드가 있으면 완료된다. + - **아직 구현되지 않음:** 각 파드에게는 1부터 `.spec.completions` 까지의 범위 내의 서로 다른 인덱스가 전달된다. +1. *작업 큐(queue)* 가 있는 병렬 잡: + - `.spec.completions` 를 지정하지 않고, `.spec.parallelism` 를 기본으로 한다. + - 파드는 각자 또는 외부 서비스 간에 조정을 통해 각각의 작업을 결정해야 한다. 예를 들어 파드는 작업 큐에서 최대 N 개의 항목을 일괄로 가져올(fetch) 수 있다. + - 각 파드는 모든 피어들의 작업이 완료되었는지 여부를 독립적으로 판단할 수 있으며, 결과적으로 전체 잡이 완료되게 한다. + - 잡의 _모든_ 파드가 성공적으로 종료되면, 새로운 파드는 생성되지 않는다. + - 하나 이상의 파드가 성공적으로 종료되고, 모든 파드가 종료되면 잡은 성공적으로 완료된다. + - 성공적으로 종료된 파드가 하나라도 생긴 경우, 다른 파드들은 해당 작업을 지속하지 않아야 하며 어떠한 출력도 작성하면 안 된다. 파드들은 모두 종료되는 과정에 있어야 한다. + +_비-병렬_ 잡은 `.spec.completions` 와 `.spec.parallelism` 모두를 설정하지 않은 채로 둘 수 있다. 이때 둘 다 +설정하지 않은 경우 1이 기본으로 설정된다. + +_고정적인 완료 횟수_ 잡은 `.spec.completions` 을 필요한 완료 횟수로 설정해야 한다. +`.spec.parallelism` 을 설정할 수 있고, 설정하지 않으면 1이 기본으로 설정된다. + +_작업 큐_ 잡은 `.spec.completions` 를 설정하지 않은 상태로 두고, `.spec.parallelism` 을 +음수가 아닌 정수로 설정해야 한다. + +다른 유형의 잡을 사용하는 방법에 대한 더 자세한 정보는 [잡 패턴](#잡-패턴) 섹션을 본다. + + +#### 병렬 처리 제어하기 + +요청된 병렬 처리(`.spec.parallelism`)는 음수가 아닌 값으로 설정할 수 있다. +만약 지정되지 않은 경우에는 1이 기본이 된다. +만약 0으로 지정되면 병렬 처리가 증가할 때까지 사실상 일시 중지된다. + +실제 병렬 처리(모든 인스턴스에서 실행되는 파드의 수)는 여러가지 이유로 요청된 +병렬 처리보다 많거나 적을 수 있다. + +- _고정적인 완료 횟수(fixed completion count)_ 잡의 경우, 병렬로 실행 중인 파드의 수는 남은 완료 수를 + 초과하지 않는다. `.spec.parallelism` 의 더 큰 값은 사실상 무시된다. +- _작업 큐_ 잡은 파드가 성공한 이후에 새로운 파드가 시작되지 않는다. 그러나 나머지 파드는 완료될 수 있다. +- 만약 잡 {{< glossary_tooltip term_id="controller" >}} 가 반응할 시간이 없는 경우 +- 만약 잡 컨트롤러가 어떤 이유(`리소스 쿼터` 의 부족, 권한 부족 등)로든 파드 생성에 실패한 경우, + 요청한 것보다 적은 수의 파드가 있을 수 있다. +- 잡 컨트롤러는 동일한 잡에서 과도하게 실패한 이전 파드들로 인해 새로운 파드의 생성을 조절할 수 있다. +- 파드가 정상적으로(gracefully) 종료되면, 중지하는데 시간이 소요된다. + +## 파드와 컨테이너 장애 처리하기 + +파드내 컨테이너의 프로세스가 0이 아닌 종료 코드로 종료되었거나 컨테이너 메모리 제한을 +초과해서 죽는 등의 여러가지 이유로 실패할 수 있다. 만약 이런 일이 +발생하고 `.spec.template.spec.restartPolicy = "OnFailure"` 라면 파드는 +노드에 그대로 유지되지만, 컨테이너는 다시 실행된다. 따라서 프로그램은 로컬에서 재시작될 때의 +케이스를 다루거나 `.spec.template.spec.restartPolicy = "Never"` 로 지정해야 한다. +더 자세한 정보는 [파드 라이프사이클](/ko/docs/concepts/workloads/pods/pod-lifecycle/#상태-예제)의 `restartPolicy` 를 본다. + +파드가 노드에서 내보내지는 경우(노드 업그레이드, 재부팅, 삭제 등) 또는 파드의 컨테이너가 실패 +되고 `.spec.template.spec.restartPolicy = "Never"` 로 설정됨과 같은 여러 이유로 +전체 파드가 실패할 수 있다. 파드가 실패하면 잡 컨트롤러는 +새 파드를 시작한다. 이 의미는 애플리케이션이 새 파드에서 재시작될 때 이 케이스를 처리해야 +한다는 점이다. 특히, 이전 실행으로 인한 임시파일, 잠금, 불완전한 출력 그리고 이와 유사한 +것들을 처리해야 한다. + +`.spec.parallelism = 1`, `.spec.completions = 1` 그리고 +`.spec.template.spec.restartPolicy = "Never"` 를 지정하더라도 같은 프로그램을 +두 번 시작하는 경우가 있다는 점을 참고한다. + +`.spec.parallelism` 그리고 `.spec.completions` 를 모두 1보다 크게 지정한다면 한번에 +여러개의 파드가 실행될 수 있다. 따라서 파드는 동시성에 대해서도 관대(tolerant)해야 한다. + +### 파드 백오프(backoff) 실패 정책 + +구성 등의 논리적 오류로 인해 약간의 재시도 이후에 +잡을 실패하게 만들려는 경우가 있다. +이렇게 하려면 `.spec.backoffLimit` 에 잡을 실패로 간주하기 이전에 +재시도할 횟수를 설정한다. 백오프 제한은 기본적으로 6으로 설정되어 있다. 잡과 +관련한 실패한 파드는 최대 6분안에서 기하급수적으로 증가하는 백-오프 지연 (10초, 20초, 40초 ...) +한도가 되어 잡 컨트롤러에 의해 재생성 된다. 잡의 다음 상태 +확인 이전에 새로 실패한 파드가 표시되지 않으면 백 오프 +카운트가 재설정 된다. + +{{< note >}} +1.12 이전 버전의 쿠버네티스 버전에 대해 여전히 [#54870](https://github.com/kubernetes/kubernetes/issues/54870) 이슈가 있다. +{{< /note >}} +{{< note >}} +만약 잡에 `restartPolicy = "OnFailure"` 가 있는 경우 잡 백오프 한계에 +도달하면 잡을 실행 중인 컨테이너가 종료된다. 이로 인해 잡 실행 파일의 디버깅이 +더 어려워질 수 있다. 디버깅하거나 로깅 시스템을 사용해서 실패한 작업의 결과를 실수로 손실되지 않도록 +하려면 `restartPolicy = "Never"` 로 설정하는 것을 권장한다. +{{< /note >}} + +## 잡의 종료와 정리 + +잡이 완료되면 파드가 더 이상 생성되지도 않지만, 삭제되지도 않는다. 이를 유지하면 +완료된 파드의 로그를 계속 보며 에러, 경고 또는 다른 기타 진단 출력을 확인할 수 있다. +잡 오브젝트는 완료된 후에도 상태를 볼 수 있도록 남아 있다. 상태를 확인한 후 이전 잡을 삭제하는 것은 사용자의 몫이다. +`kubectl` 로 잡을 삭제할 수 있다 (예: `kubectl delete jobs/pi` 또는 `kubectl delete -f ./job.yaml`). `kubectl` 을 사용해서 잡을 삭제하면 생성된 모든 파드도 함께 삭제된다. + +기본적으로 파드의 실패(`restartPolicy=Never`) 또는 컨테이너가 오류(`restartPolicy=OnFailure`)로 종료되지 않는 한, 잡은 중단되지 않고 실행되고 +이때 위에서 설명했던 `.spec.backoffLimit` 까지 연기된다. `.spec.backoffLimit` 에 도달하면 잡은 실패로 표기되고 실행 중인 모든 파드는 종료된다. + +잡을 종료하는 또 다른 방법은 유효 데드라인을 설정하는 것이다. +잡의 `.spec.activeDeadlineSeconds` 필드를 초 단위로 설정하면 된다. +`activeDeadlineSeconds` 는 생성된 파드의 수에 관계 없이 잡의 기간에 적용된다. +잡이 `activeDeadlineSeconds` 에 도달하면, 실행 중인 모든 파드가 종료되고 잡의 상태는 `reason: DeadlineExceeded` 와 함께 `type: Failed` 가 된다. + +잡의 `.spec.activeDeadlineSeconds` 는 `.spec.backoffLimit` 보다 우선한다는 점을 참고한다. 따라서 하나 이상 실패한 파드를 재시도하는 잡은 `backoffLimit` 에 도달하지 않은 경우에도 `activeDeadlineSeconds` 에 지정된 시간 제한에 도달하면 추가 파드를 배포하지 않는다. + +예시: + +```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 +``` + +잡의 사양과 잡의 [파드 템플릿 사양](/ko/docs/concepts/workloads/pods/init-containers/#자세한-동작)에는 모두 `activeDeadlineSeconds` 필드가 있다는 점을 참고한다. 이 필드를 적절한 레벨로 설정해야 한다. + +`restartPolicy` 는 잡 자체에 적용되는 것이 아니라 파드에 적용된다는 점을 유념한다. 잡의 상태가 `type: Failed` 이 되면, 잡의 자동 재시작은 없다. +즉, `.spec.activeDeadlineSeconds` 와 `.spec.backoffLimit` 로 활성화된 잡의 종료 메커니즘은 영구적인 잡의 실패를 유발하며 이를 해결하기 위해 수동 개입이 필요하다. + +## 완료된 잡을 자동으로 정리 + +완료된 잡은 일반적으로 시스템에서 더 이상 필요로 하지 않는다. 시스템 내에 +이를 유지한다면 API 서버에 부담이 된다. +만약 [크론잡](/ko/docs/concepts/workloads/controllers/cron-jobs/)과 +같은 상위 레벨 컨트롤러가 잡을 직접 관리하는 경우, +지정된 용량 기반 정리 정책에 따라 크론잡이 잡을 정리할 수 있다. + +### 완료된 잡을 위한 TTL 메커니즘 + +{{< feature-state for_k8s_version="v1.12" state="alpha" >}} + +완료된 잡 (`Complete` 또는 `Failed`)을 자동으로 정리하는 또 다른 방법은 +잡의 `.spec.ttlSecondsAfterFinished` 필드를 지정해서 완료된 리소스에 대해 +[TTL 컨트롤러](/ko/docs/concepts/workloads/controllers/ttlafterfinished/)에서 +제공하는 TTL 메커니즘을 사용하는 +것이다. + +TTL 컨트롤러는 잡을 정리하면 잡을 계단식으로 삭제한다. +즉, 잡과 함께 파드와 같은 종속 오브젝트를 삭제한다. 잡을 +삭제하면 finalizer와 같은 라이프사이클 보증이 보장되는 것을 +참고한다. + +예시: + +```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 +``` + +`pi-with-ttl` 잡은 완료 후 `100` 초 이후에 +자동으로 삭제될 수 있다. + +만약 필드를 `0` 으로 설정하면, 잡이 완료된 직후에 자동으로 +삭제되도록 할 수 있다. 만약 필드를 설정하지 않으면, 이 잡이 완료된 +후에 TTL 컨트롤러에 의해 정리되지 않는다. + +이 TTL 메커니즘은 기능 게이트 `TTLAfterFinished`와 함께 알파 단계이다. 더 +자세한 정보는 완료된 리소스를 위한 +[TTL 컨트롤러](/ko/docs/concepts/workloads/controllers/ttlafterfinished/) +문서를 본다. + +## 잡 패턴 + +잡 오브젝트를 사용해서 신뢰할 수 있는 파드의 병렬 실행을 지원할 수 있다. 잡 오브젝트는 과학 +컴퓨팅(scientific computing)에서 일반적으로 사용되는 밀접하게 통신하는 병렬 프로세스를 지원하도록 +설계되지 않았다. 잡 오브젝트는 독립적이지만 관련된 *작업 항목* 집합의 병렬 처리를 지원한다. +여기에는 전송할 이메일들, 렌더링할 프레임, 코드 변환이 필요한 파일, NoSQL 데이터베이스에서의 +키 범위 스캔 등이 있다. + +복잡한 시스템에는 여러개의 다른 작업 항목 집합이 있을 수 있다. 여기서는 사용자와 +함께 관리하려는 하나의 작업 항목 집합 — *배치 잡* 을 고려하고 있다. + +병렬 계산에는 몇몇 다른 패턴이 있으며 각각의 장단점이 있다. +트레이드오프는 다음과 같다. + +- 각 작업 항목에 대한 하나의 잡 오브젝트 vs 모든 작업 항목에 대한 단일 잡 오브젝트. 후자는 + 작업 항목 수가 많은 경우 더 적합하다. 전자는 사용자와 시스템이 많은 수의 잡 오브젝트를 + 관리해야 하는 약간의 오버헤드를 만든다. +- 작업 항목과 동일한 개수의 파드 생성 vs 각 파드에서 다수의 작업 항목을 처리 + 전자는 일반적으로 기존 코드와 컨테이너를 거의 수정할 필요가 없다. 후자는 + 이전 글 머리표(-)와 비슷한 이유로 많은 수의 작업 항목에 적합하다. +- 여러 접근 방식이 작업 큐를 사용한다. 이를 위해서는 큐 서비스를 실행하고, + 작업 큐를 사용하도록 기존 프로그램이나 컨테이너를 수정해야 한다. + 다른 접근 방식들은 기존에 컨테이너화된 애플리케이션에 보다 쉽게 적용할 수 있다. + + +여기에 트레이드오프가 요약되어있고, 2열에서 4열까지가 위의 트레이드오프에 해당한다. +패턴 이름은 예시와 더 자세한 설명을 위한 링크이다. + +| 패턴 | 단일 잡 오브젝트 | 작업 항목보다 파드가 적은가? | 수정하지 않은 앱을 사용하는가? | Kube 1.1에서 작동하는가? | +| -------------------------------------------------------------------- |:-----------------:|:---------------------------:|:-------------------:|:-------------------:| +| [잡 템플릿 확장](/docs/tasks/job/parallel-processing-expansion/) | | | ✓ | ✓ | +| [작업 항목 당 파드가 있는 큐](/docs/tasks/job/coarse-parallel-processing-work-queue/) | ✓ | | 때때로 | ✓ | +| [가변 파드 수를 가진 큐](/docs/tasks/job/fine-parallel-processing-work-queue/) | ✓ | ✓ | | ✓ | +| 정적 작업이 할당된 단일 잡 | ✓ | | ✓ | | + +`.spec.completions` 로 완료를 지정할 때, 잡 컨트롤러에 의해 생성된 각 파드는 +동일한 [`사양`](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status)을 갖는다. 이 의미는 +작업의 모든 파드는 동일한 명령 줄과 동일한 이미지, +동일한 볼륨, (거의) 동일한 환경 변수를 가진다는 점이다. 이 패턴은 +파드가 다른 작업을 수행하도록 배열하는 다른 방법이다. + +이 표는 각 패턴에 필요한 `.spec.parallelism` 그리고 `.spec.completions` 설정을 보여준다. +여기서 `W` 는 작업 항목의 수이다. + +| 패턴 | `.spec.completions` | `.spec.parallelism` | +| -------------------------------------------------------------------- |:-------------------:|:--------------------:| +| [잡 템플릿 확장](/docs/tasks/job/parallel-processing-expansion/) | 1 | 1이어야 함 | +| [작업 항목 당 파드가 있는 큐](/docs/tasks/job/coarse-parallel-processing-work-queue/) | W | any | +| [가변 파드 수를 가진 큐](/docs/tasks/job/fine-parallel-processing-work-queue/) | 1 | any | +| 정적 작업이 할당된 단일 잡 | W | any | + + +## 고급 사용법 + +### 자신의 파드 셀렉터를 지정하기 + +일반적으로 잡 오브젝트를 생성할 때 `.spec.selector` 를 지정하지 않는다. +시스템의 기본적인 로직은 잡이 생성될 때 이 필드를 추가한다. +이것은 다른 잡과 겹치지 않는 셀렉터 값을 선택한다. + +그러나, 일부 케이스에서는 이 자동화된 설정 셀렉터를 재정의해야 할 수도 있다. +이를 위해 잡의 `.spec.selector` 를 설정할 수 있다. + +이 것을 할 때는 매우 주의해야 한다. 만약 해당 잡의 파드에 고유하지 +않고 연관이 없는 파드와 일치하는 레이블 셀렉터를 지정하면, 연관이 없는 잡의 파드가 삭제되거나, +해당 잡이 다른 파드가 완료한 것으로 수를 세거나, 하나 또는 +양쪽 잡 모두 파드 생성이나 실행 완료를 거부할 수도 있다. 만약 고유하지 않은 셀렉터가 +선택된 경우, 다른 컨트롤러(예: 레플리케이션 컨트롤러)와 해당 파드는 +예측할 수 없는 방식으로 작동할 수 있다. 쿠버네티스는 당신이 `.spec.selector` 를 지정할 때 +발생하는 실수를 막을 수 없을 것이다. + +다음은 이 기능을 사용하려는 경우의 예시이다. + +잡 `old` 가 이미 실행 중이다. 기존 파드가 계속 +실행되기를 원하지만, 잡이 생성한 나머지 파드에는 다른 +파드 템플릿을 사용하고 잡으로 하여금 새 이름을 부여하기를 원한다. +그러나 관련된 필드들은 업데이트가 불가능하기 때문에 잡을 업데이트할 수 없다. +따라서 `kubectl delete jobs/old --cascade=false` 를 사용해서 +잡 `old` 를 삭제하지만, _파드를 실행 상태로 둔다_. +삭제하기 전에 어떤 셀렉터를 사용하는지 기록한다. + +``` +kubectl get job old -o yaml +``` +``` +kind: Job +metadata: + name: old + ... +spec: + selector: + matchLabels: + controller-uid: a8f3d00d-c6d2-11e5-9f87-42010af00002 + ... +``` + +그런 이후에 이름이 `new` 인 새 잡을 생성하고, 동일한 셀렉터를 명시적으로 지정한다. +기존 파드에는 `controller-uid=a8f3d00d-c6d2-11e5-9f87-42010af00002` +레이블이 있기에 잡 `new` 에 의해서도 제어된다. + +시스템이 일반적으로 자동 생성하는 셀렉터를 사용하지 않도록 하기 위해 +새 잡에서 `manualSelector: true` 를 지정해야 한다. + +``` +kind: Job +metadata: + name: new + ... +spec: + manualSelector: true + selector: + matchLabels: + controller-uid: a8f3d00d-c6d2-11e5-9f87-42010af00002 + ... +``` + +새 잡 자체는 `a8f3d00d-c6d2-11e5-9f87-42010af00002` 와 다른 uid 를 가지게 될 것이다. +`manualSelector: true` 를 설정하면 시스템에게 사용자가 무엇을 하는지 알고 있음을 알리고, 이런 +불일치를 허용한다. + +## 대안 + +### 베어(Bare) 파드 + +파드가 실행 중인 노드가 재부팅되거나 실패하면 파드가 종료되고 +다시 시작되지 않는다. 그러나 잡은 종료된 항목을 대체하기 위해 새 파드를 생성한다. +따라서, 애플리케이션에 단일 파드만 필요한 경우에도 베어 파드 대신 +잡을 사용하는 것을 권장한다. + +### 레플리케이션 컨트롤러 + +잡은 [레플리케이션 컨트롤러](/ko/docs/concepts/workloads/controllers/replicationcontroller/)를 보완한다. +레플리케이션 컨트롤러는 종료하지 않을 파드(예: 웹 서버)를 관리하고, 잡은 종료될 것으로 +예상되는 파드(예: 배치 작업)를 관리한다. + +[파드 라이프사이클](/ko/docs/concepts/workloads/pods/pod-lifecycle/)에서 설명한 것처럼, `잡` 은 *오직* +`OnFailure` 또는 `Never` 와 같은 `RestartPolicy` 를 사용하는 파드에만 적절하다. +(참고: `RestartPolicy` 가 설정되지 않은 경우에는 기본값은 `Always` 이다.) + +### 단일 잡으로 컨트롤러 파드 시작 + +또 다른 패턴은 단일 잡이 파드를 생성한 후 다른 파드들을 생성해서 해당 파드들에 +일종의 사용자 정의 컨트롤러 역할을 하는 것이다. 이를 통해 최대한의 유연성을 얻을 수 있지만, +시작하기에는 다소 복잡할 수 있으며 쿠버네티스와의 통합성이 낮아진다. + +이 패턴의 한 예시는 파드를 시작하는 잡이다. 파드는 스크립트를 실행해서 +스파크(Spark) 마스터 컨트롤러 ([스파크 예시](https://github.com/kubernetes/examples/tree/{{< param "githubbranch" >}}/staging/spark/README.md)를 본다)를 시작하고, +스파크 드라이버를 실행한 다음, 정리한다. + +이 접근 방식의 장점은 전체 프로세스가 잡 오브젝트의 완료를 보장하면서도, +파드 생성과 작업 할당 방법을 완전히 제어할 수 있다는 점이다. + +## 크론 잡 {#cron-jobs} + +[`크론잡`](/ko/docs/concepts/workloads/controllers/cron-jobs/)을 사용해서 Unix 도구인 `cron`과 유사하게 지정된 시간/일자에 실행되는 잡을 생성할 수 있다. + +{{% /capture %}} diff --git a/content/ko/docs/concepts/workloads/controllers/replicaset.md b/content/ko/docs/concepts/workloads/controllers/replicaset.md index f5d199c746..47b74587aa 100644 --- a/content/ko/docs/concepts/workloads/controllers/replicaset.md +++ b/content/ko/docs/concepts/workloads/controllers/replicaset.md @@ -71,53 +71,50 @@ kubectl describe rs/frontend 출력은 다음과 유사할 것이다. ```shell -Name: frontend -Namespace: default -Selector: tier=frontend -Labels: app=guestbook - tier=frontend -Annotations: -Replicas: 3 current / 3 desired -Pods Status: 3 Running / 0 Waiting / 0 Succeeded / 0 Failed +Name: frontend +Namespace: default +Selector: tier=frontend +Labels: app=guestbook + tier=frontend +Annotations: kubectl.kubernetes.io/last-applied-configuration: + {"apiVersion":"apps/v1","kind":"ReplicaSet","metadata":{"annotations":{},"labels":{"app":"guestbook","tier":"frontend"},"name":"frontend",... +Replicas: 3 current / 3 desired +Pods Status: 3 Running / 0 Waiting / 0 Succeeded / 0 Failed Pod Template: - Labels: app=guestbook - tier=frontend + Labels: tier=frontend Containers: php-redis: - Image: gcr.io/google_samples/gb-frontend:v3 - Port: 80/TCP - Requests: - cpu: 100m - memory: 100Mi - Environment: - GET_HOSTS_FROM: dns - Mounts: - Volumes: + Image: gcr.io/google_samples/gb-frontend:v3 + Port: + Host Port: + Environment: + Mounts: + Volumes: Events: - FirstSeen LastSeen Count From SubobjectPath Type Reason Message - --------- -------- ----- ---- ------------- -------- ------ ------- - 1m 1m 1 {replicaset-controller } Normal SuccessfulCreate Created pod: frontend-qhloh - 1m 1m 1 {replicaset-controller } Normal SuccessfulCreate Created pod: frontend-dnjpy - 1m 1m 1 {replicaset-controller } Normal SuccessfulCreate Created pod: frontend-9si5l + Type Reason Age From Message + ---- ------ ---- ---- ------- + Normal SuccessfulCreate 117s replicaset-controller Created pod: frontend-wtsmm + Normal SuccessfulCreate 116s replicaset-controller Created pod: frontend-b2zdv + Normal SuccessfulCreate 116s replicaset-controller Created pod: frontend-vcmts ``` 마지막으로 파드가 올라왔는지 확인할 수 있다. ```shell -kubectl get Pods +kubectl get pods ``` 다음과 유사한 파드 정보를 볼 수 있다. ```shell -NAME READY STATUS RESTARTS AGE -frontend-9si5l 1/1 Running 0 1m -frontend-dnjpy 1/1 Running 0 1m -frontend-qhloh 1/1 Running 0 1m +NAME READY STATUS RESTARTS AGE +frontend-b2zdv 1/1 Running 0 6m36s +frontend-vcmts 1/1 Running 0 6m36s +frontend-wtsmm 1/1 Running 0 6m36s ``` 또한 파드들의 소유자 참조 정보가 해당 프런트엔드 레플리카셋으로 설정되어 있는지 확인할 수 있다. 확인을 위해서는 실행 중인 파드 중 하나의 yaml을 확인한다. ```shell -kubectl get pods frontend-9si5l -o yaml +kubectl get pods frontend-b2zdv -o yaml ``` 메타데이터의 ownerReferences 필드에 설정되어있는 프런트엔드 레플리카셋의 정보가 다음과 유사하게 나오는 것을 볼 수 있다. @@ -125,11 +122,11 @@ kubectl get pods frontend-9si5l -o yaml apiVersion: v1 kind: Pod metadata: - creationTimestamp: 2019-01-31T17:20:41Z + creationTimestamp: "2020-02-12T07:06:16Z" generateName: frontend- labels: tier: frontend - name: frontend-9si5l + name: frontend-b2zdv namespace: default ownerReferences: - apiVersion: apps/v1 @@ -137,7 +134,7 @@ metadata: controller: true kind: ReplicaSet name: frontend - uid: 892a2330-257c-11e9-aecd-025000000001 + uid: f391f6db-bb9b-4c09-ae74-6a1f77f3d5cf ... ``` @@ -166,16 +163,17 @@ kubectl apply -f https://kubernetes.io/examples/pods/pod-rs.yaml 파드를 가져온다. ```shell -kubectl get Pods +kubectl get pods ``` 결과에는 새로운 파드가 이미 종료되었거나 종료가 진행 중인 것을 보여준다. ```shell NAME READY STATUS RESTARTS AGE -frontend-9si5l 1/1 Running 0 1m -frontend-dnjpy 1/1 Running 0 1m -frontend-qhloh 1/1 Running 0 1m -pod2 0/1 Terminating 0 4s +frontend-b2zdv 1/1 Running 0 10m +frontend-vcmts 1/1 Running 0 10m +frontend-wtsmm 1/1 Running 0 10m +pod1 0/1 Terminating 0 1s +pod2 0/1 Terminating 0 1s ``` 파드를 먼저 생성한다. @@ -191,15 +189,15 @@ kubectl apply -f https://kubernetes.io/examples/controllers/frontend.yaml 레플리카셋이 해당 파드를 소유한 것을 볼 수 있으며 새 파드 및 기존 파드의 수가 레플리카셋이 필요로 하는 수와 일치할 때까지 사양에 따라 신규 파드만 생성한다. 파드를 가져온다. ```shell -kubectl get Pods +kubectl get pods ``` 다음 출력에서 볼 수 있다. ```shell NAME READY STATUS RESTARTS AGE -frontend-pxj4r 1/1 Running 0 5s -pod1 1/1 Running 0 13s -pod2 1/1 Running 0 13s +frontend-hmmj2 1/1 Running 0 9s +pod1 1/1 Running 0 36s +pod2 1/1 Running 0 36s ``` 이러한 방식으로 레플리카셋은 템플릿을 사용하지 않는 파드를 소유하게 된다. diff --git a/content/ko/docs/concepts/workloads/controllers/ttlafterfinished.md b/content/ko/docs/concepts/workloads/controllers/ttlafterfinished.md index ff6cc0284f..48a8bdb303 100644 --- a/content/ko/docs/concepts/workloads/controllers/ttlafterfinished.md +++ b/content/ko/docs/concepts/workloads/controllers/ttlafterfinished.md @@ -33,8 +33,8 @@ TTL 컨트롤러는 실행이 완료된 리소스 오브젝트의 수명을 완료된 잡(`완료` 또는 `실패`)을 자동으로 정리하기 위해 이 기능을 사용할 수 있다. 리소스의 작업이 완료된 TTL 초(sec) 후 (다른 말로는, TTL이 만료되었을 때), TTL 컨트롤러는 해당 리소스가 정리될 수 있다고 가정한다. -TTL 컨트롤러가 리소스를 정리할때 리소스를 연속적으로 삭제한다. 즉, -의존하는 오브젝트와 함께 삭제한다. 리소스가 삭제되면 완료자(finalizers)와 +TTL 컨트롤러가 리소스를 정리할때 리소스를 연속적으로 삭제한다. 이는 +의존하는 오브젝트도 해당 리소스와 함께 삭제되는 것을 의미한다. 리소스가 삭제되면 완료자(finalizers)와 같은 라이프 사이클 보증이 적용 된다. TTL 초(sec)는 언제든지 설정이 가능하다. 여기에 잡 필드 중 diff --git a/content/ko/docs/concepts/workloads/pods/init-containers.md b/content/ko/docs/concepts/workloads/pods/init-containers.md index 19dabdd03c..9e90cb0d77 100644 --- a/content/ko/docs/concepts/workloads/pods/init-containers.md +++ b/content/ko/docs/concepts/workloads/pods/init-containers.md @@ -120,10 +120,10 @@ spec: initContainers: - name: init-myservice image: busybox:1.28 - command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;'] + command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"] - name: init-mydb image: busybox:1.28 - command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;'] + command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"] ``` 다음 커맨드들을 이용하여 파드를 시작하거나 디버깅할 수 있다. diff --git a/content/ko/docs/concepts/workloads/pods/pod-overview.md b/content/ko/docs/concepts/workloads/pods/pod-overview.md index 55126172fe..1902594c33 100644 --- a/content/ko/docs/concepts/workloads/pods/pod-overview.md +++ b/content/ko/docs/concepts/workloads/pods/pod-overview.md @@ -51,7 +51,7 @@ card: #### 저장소 -파드는 공유 저장소 집합인 {{< glossary_tooltip text="Volumes" term_id="volume" >}} 을 명시할 수 있다. 파드 내부의 모든 컨테이너는 공유 볼륨에 접근할 수 있고, 그 컨테이너끼리 데이터를 공유하는 것을 허용한다. 또한 볼륨은 컨테이너가 재시작되어야 하는 상황에도 파드 안의 데이터가 영구적으로 유지될 수 있게 한다. 쿠버네티스가 어떻게 파드 안의 공유 저장소를 사용하는지 보려면 [볼륨](/docs/concepts/storage/volumes/)를 참고하길 바란다. +파드는 공유 저장소 집합인 {{< glossary_tooltip text="Volumes" term_id="volume" >}} 을 명시할 수 있다. 파드 내부의 모든 컨테이너는 공유 볼륨에 접근할 수 있고, 그 컨테이너끼리 데이터를 공유하는 것을 허용한다. 또한 볼륨은 컨테이너가 재시작되어야 하는 상황에도 파드 안의 데이터가 영구적으로 유지될 수 있게 한다. 쿠버네티스가 어떻게 파드 안의 공유 저장소를 사용하는지 보려면 [볼륨](/ko/docs/concepts/storage/volumes/)를 참고하길 바란다. ## 파드 작업 diff --git a/content/ko/docs/concepts/workloads/pods/pod.md b/content/ko/docs/concepts/workloads/pods/pod.md index 16f2e4149b..4196a5fbb7 100644 --- a/content/ko/docs/concepts/workloads/pods/pod.md +++ b/content/ko/docs/concepts/workloads/pods/pod.md @@ -41,7 +41,7 @@ _파드_ 는 (고래 떼(pod of whales)나 콩꼬투리(pea pod)와 마찬가지 공유 볼륨에 엑세스 할 수 있다. [도커](https://www.docker.com/)의 구조 관점에서 보면 -파드는 공유 네임스페이스와 공유 [볼륨](/docs/concepts/storage/volumes/)을 가진 +파드는 공유 네임스페이스와 공유 [볼륨](/ko/docs/concepts/storage/volumes/)을 가진 도커 컨테이너 그룹으로 모델링 된다. 개별 애플리케이션 컨테이너와 같이, 파드는 상대적으로 수명이 짧은 엔터티로 간주된다. @@ -146,7 +146,7 @@ _컨테이너의 어피니티(affinity) 기반 공동 스케줄링을 지원하 * 스케줄러 및 컨트롤러 연결 가능 * "프록시" 없이 컨트롤러 API를 통한 파드-레벨 수준의 동작 지원 -* 부트스트랩과 같이 컨트롤러의 생에와 파드의 생애 분리 +* 부트스트랩과 같이 컨트롤러의 생애와 파드의 생애 분리 * 컨트롤러와 서비스의 분리 — 파드를 감시하는 엔드 포인트 컨트롤러 * 클러스터 레벨과 kubelet 레벨 기능의 깔끔한 구성 — Kubelet은 효과적인 "파드 컨트롤러" 이다. * 계획된 삭제 또는 이미지 프리페칭과 같이 파드가 종료되기 전에 교체가 될 것이고, @@ -189,7 +189,7 @@ API에서 파드를 즉시 제거하므로 동일한 이름으로 새 파드를 Kubernetes v1.1부터, 파드의 모든 컨테이너는 컨테이너 스펙의 `SecurityContext`의 `privileged` 플래그를 사용하여 특권 모드를 사용할 수 있다. 이것은 네트워크 스택을 조작하고 장치에 액세스하는 것과 같은 Linux 기능을 사용하려는 컨테이너에 유용하다. 컨테이너 내의 프로세스는 컨테이너 외부의 프로세스에서 사용할 수 있는 거의 동일한 권한을 갖는다. 특권 모드를 사용하면 네트워크 및 볼륨 플러그인을 kubelet에 컴파일 할 필요가 없는 별도의 파드로 쉽게 만들 수 있다. 마스터가 Kubernetes v1.1 이상에서 실행 중이고, 노드가 v1.1 보다 낮은 버전을 실행중인 경우 새 권한이 부여 된 파드는 api-server에 의해 승인되지만 시작되지는 않는다. 이것들은 pending 상태가 될 것이다. -사용자가 `kubectl describe pod FooPodName` 을 호출하면 사용자는 파드가 사용자가 `kubectl describe pod FooPodName` 을 호출하면 사용자는 파드가 pending 상태에 있는 이유를 볼 수 있다. describe 명령 출력의 이벤트 테이블은 다음과 같다. +사용자가 `kubectl describe pod FooPodName` 을 호출하면 사용자는 파드가 pending 상태에 있는 이유를 볼 수 있다. describe 명령 출력의 이벤트 테이블은 다음과 같다. `Error validating pod "FooPodName"."FooPodNamespace" from api, ignoring: spec.containers[0].securityContext.privileged: forbidden '<*>(0xc2089d3248)true'` 마스터가 v1.1보다 낮은 버전에서 실행중인 경우 특권을 갖는 파드를 만들 수 없다. 유저가 특권을 갖는 컨테이너가 있는 파드를 만들려고 하면 다음과 같은 오류가 발생한다. diff --git a/content/ko/docs/contribute/participating.md b/content/ko/docs/contribute/participating.md index 88db56aa34..f1abbfc27c 100644 --- a/content/ko/docs/contribute/participating.md +++ b/content/ko/docs/contribute/participating.md @@ -24,6 +24,7 @@ SIG Docs는 모든 컨트리뷰터의 콘텐츠와 리뷰를 환영한다. 쿠버네티스 커뮤니티 내에서 멤버십이 운영되는 방식에 대한 보다 많은 정보를 확인하려면 [커뮤니티 멤버십](https://github.com/kubernetes/community/blob/master/community-membership.md) 문서를 확인한다. + 문서의 나머지에서는 대외적으로 쿠버네티스를 가장 잘 드러내는 수단 중 하나인 쿠버네티스 웹사이트와 문서를 관리하는 책임을 가지는 SIG Docs에서, 이런 체계가 작동하는 특유의 방식에 대한 윤곽을 잡아보겠다. @@ -52,7 +53,8 @@ SIG Docs는 모든 컨트리뷰터의 콘텐츠와 리뷰를 환영한다. 누구나 다음 작업을 할 수 있다. - 문서를 포함한 쿠버네티스의 모든 부분에 대해 GitHub 이슈 열기. -- 풀 리퀘스트/ 에 대한 구속력 없는 피드백 제공 +- 풀 리퀘스트에 대한 구속력 없는 피드백 제공 +- 기존 컨텐츠를 현지화하는데 도움주는 것 - [슬랙](http://slack.k8s.io/) 또는 [SIG docs 메일링 리스트](https://groups.google.com/forum/#!forum/kubernetes-sig-docs)에 개선할 아이디어를 제시한다. - `/lgtm` Prow 명령 ("looks good to me" 의 줄임말)을 사용해서 병합을 위한 풀 리퀘스트의 변경을 추천한다. {{< note >}} @@ -120,7 +122,6 @@ GitHub 그룹의 멤버이다. 리뷰어는 문서 풀 리퀘스트를 리뷰하 - 이슈 해결 및 분류 - 풀 리퀘스트 리뷰와 구속력있는 피드백 제공 - 다이어그램, 그래픽 자산과 포함가능한 스크린샷과 비디오를 생성 -- 현지화 - 코드에서 사용자 화면 문자열 편집 - 코드 코멘트 개선 @@ -166,7 +167,7 @@ GitHub 그룹에 당신을 추가하기를 요청한다. `kubernetes-website-adm 승인자는 [@kubernetes/sig-docs-maintainers](https://github.com/orgs/kubernetes/teams/sig-docs-maintainers) -GitHub 그룹의 멤버이다. [SIG Docs의 팀과 그룹](#teams-and-groups-within-sig-docs) 문서를 참조한다. +GitHub 그룹의 멤버이다. [SIG Docs 팀과 자동화](#sig-docs-팀과-자동화) 문서를 참조한다. 승인자는 다음의 작업을 할 수 있다. @@ -225,7 +226,7 @@ GitHub 그룹에 당신을 추가하기를 요청한다. `kubernetes-website-adm 것으로 기대한다. [일주일 간 PR Wrangler 되기](/docs/contribute/advanced#be-the-pr-wrangler-for-a-week) 문서를 참고한다. -## SIG Docs chairperson +## SIG Docs 의장 SIG Docs를 포함한 각 SIG는, 한 명 이상의 SIG 멤버가 의장 역할을 하도록 선정한다. 이들은 SIG Docs와 다른 쿠버네티스 조직 간 연락책(point of contact)이 된다. 이들은 쿠버네티스 프로젝트 전반의 조직과 @@ -297,7 +298,7 @@ PR 소유자에게 조언하는데 활용된다. - 모든 쿠버네티스 맴버는 코멘트에 `/lgtm` 을 추가해서 `lgtm` 레이블을 추가할 수 있다. - SIG Docs 승인자들만이 코멘트에 `/approve` 를 추가해서 풀 리퀘스트를 병합할 수 있다. 일부 승인자들은 - [PR Wrangler](#pr-wrangler) EHsms [SIG Docs 의장](#sig-docs-chairperson)과 + [PR Wrangler](#pr-wrangler) 또는 [SIG Docs 의장](#sig-docs-의장)과 같은 특정 역할도 수행한다. {{% /capture %}} diff --git a/content/ko/docs/contribute/style/write-new-topic.md b/content/ko/docs/contribute/style/write-new-topic.md index d6c21c7bc9..c08248e783 100644 --- a/content/ko/docs/contribute/style/write-new-topic.md +++ b/content/ko/docs/contribute/style/write-new-topic.md @@ -92,7 +92,7 @@ YAML 블록이다. 여기 예시가 있다. - 이 코드는 `kubectl get deploy mydeployment -o json | jq '.status'`와 같은 명령어의 출력을 보여준다. - 이 코드는 시도해보기에 적절하지 않다. 예를 들어 - 특정 [FlexVolume](/docs/concepts/storage/volumes#flexvolume) 구현에 따라 + 특정 [FlexVolume](/ko/docs/concepts/storage/volumes#flexvolume) 구현에 따라 파드를 만들기 위해 YAML 파일을 포함할 수 있다. - 이 코드의 목적은 더 큰 파일의 일부를 강조하는 것이기 때문에 diff --git a/content/ko/docs/reference/glossary/volume.md b/content/ko/docs/reference/glossary/volume.md index 4f5c26c88a..8e2841e72c 100755 --- a/content/ko/docs/reference/glossary/volume.md +++ b/content/ko/docs/reference/glossary/volume.md @@ -2,7 +2,7 @@ title: 볼륨(Volume) id: volume date: 2018-04-12 -full_link: /docs/concepts/storage/volumes/ +full_link: /ko/docs/concepts/storage/volumes/ short_description: > 데이터를 포함하고 있는 디렉토리이며, 파드의 컨테이너에서 접근 가능하다. diff --git a/content/ko/docs/tasks/_index.md b/content/ko/docs/tasks/_index.md index 4289d0544d..9624c907d3 100644 --- a/content/ko/docs/tasks/_index.md +++ b/content/ko/docs/tasks/_index.md @@ -57,10 +57,6 @@ content_template: templates/concept 클러스터를 운영하기 위한 일반적인 태스크를 배운다. -## 페더레이션(federation) 운영하기(administering) - -클러스터 페더레이션의 컴포넌트들을 구성한다. - ## 스테이트풀 애플리케이션 관리하기 스테이트풀 셋의 스케일링, 삭제하기, 디버깅을 포함하는 스테이트풀 애플리케이션 관리를 위한 일반적인 태스크를 수행한다. diff --git a/content/ko/docs/tasks/access-application-cluster/configure-access-multiple-clusters.md b/content/ko/docs/tasks/access-application-cluster/configure-access-multiple-clusters.md index 0a3778288d..0ab00f5d1c 100644 --- a/content/ko/docs/tasks/access-application-cluster/configure-access-multiple-clusters.md +++ b/content/ko/docs/tasks/access-application-cluster/configure-access-multiple-clusters.md @@ -86,7 +86,9 @@ kubectl config --kubeconfig=config-demo set-credentials experimenter --username= ``` {{< note >}} -`kubectl config unset users.`을 실행하여 사용자를 삭제할 수 있다. +- 사용자를 삭제하려면 `kubectl --kubeconfig=config-demo config unset users.` 를 실행한다. +- 클러스터를 제거하려면 `kubectl --kubeconfig=config-demo config unset clusters.` 를 실행한다. +- 컨텍스트를 제거하려면 `kubectl --kubeconfig=config-demo config unset contexts.` 를 실행한다. {{< /note >}} 컨텍스트 세부사항들을 구성 파일에 추가한다. diff --git a/content/ko/docs/tutorials/online-training/overview.md b/content/ko/docs/tutorials/online-training/overview.md index 9a9dfd794b..44f1c69ddc 100644 --- a/content/ko/docs/tutorials/online-training/overview.md +++ b/content/ko/docs/tutorials/online-training/overview.md @@ -39,8 +39,6 @@ content_template: templates/concept * [Hands-on Introduction to Kubernetes (Instruqt)](https://play.instruqt.com/public/topics/getting-started-with-kubernetes) -* [IBM Cloud: Deploying Microservices with Kubernetes (Coursera)](https://www.coursera.org/learn/deploy-micro-kube-ibm-cloud) - * [Introduction to Kubernetes (edX)](https://www.edx.org/course/introduction-kubernetes-linuxfoundationx-lfs158x) * [Kubernetes Essentials with Hands-On Labs (Linux Academy)] (https://linuxacademy.com/linux/training/course/name/kubernetes-essentials) diff --git a/content/ko/docs/tutorials/stateful-application/zookeeper.md b/content/ko/docs/tutorials/stateful-application/zookeeper.md index 7486a7fe71..dd7a850134 100644 --- a/content/ko/docs/tutorials/stateful-application/zookeeper.md +++ b/content/ko/docs/tutorials/stateful-application/zookeeper.md @@ -19,7 +19,7 @@ weight: 40 - [파드](/docs/user-guide/pods/single-container/) - [클러스터 DNS](/ko/docs/concepts/services-networking/dns-pod-service/) - [헤드리스 서비스](/ko/docs/concepts/services-networking/service/#헤드리스-headless-서비스) -- [퍼시스턴트볼륨](/docs/concepts/storage/volumes/) +- [퍼시스턴트볼륨](/ko/docs/concepts/storage/volumes/) - [퍼시스턴트볼륨 프로비저닝](https://github.com/kubernetes/examples/tree/{{< param "githubbranch" >}}/staging/persistent-volume-provisioning/) - [스테이트풀셋](/ko/docs/concepts/workloads/controllers/statefulset/) - [파드디스룹션버짓](/ko/docs/concepts/workloads/pods/disruptions/#specifying-a-poddisruptionbudget) diff --git a/content/ko/examples/controllers/job.yaml b/content/ko/examples/controllers/job.yaml new file mode 100644 index 0000000000..b448f2eb81 --- /dev/null +++ b/content/ko/examples/controllers/job.yaml @@ -0,0 +1,14 @@ +apiVersion: batch/v1 +kind: Job +metadata: + name: pi +spec: + template: + spec: + containers: + - name: pi + image: perl + command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"] + restartPolicy: Never + backoffLimit: 4 + diff --git a/content/pt/docs/concepts/cluster-administration/kubelet-garbage-collection.md b/content/pt/docs/concepts/cluster-administration/kubelet-garbage-collection.md new file mode 100644 index 0000000000..78270eedcc --- /dev/null +++ b/content/pt/docs/concepts/cluster-administration/kubelet-garbage-collection.md @@ -0,0 +1,71 @@ +--- +reviewers: +title: Configurando o Garbage Collection do kubelet +content_template: templates/concept +weight: 70 +--- + +{{% capture overview %}} + +O Garbage collection(Coleta de lixo) é uma função útil do kubelet que limpa imagens e contêineres não utilizados. O kubelet executará o garbage collection para contêineres a cada minuto e para imagens a cada cinco minutos. + +Ferramentas externas de garbage collection não são recomendadas, pois podem potencialmente interromper o comportamento do kubelet removendo os contêineres que existem. + +{{% /capture %}} + +{{% capture body %}} + +## Coleta de imagens + +O Kubernetes gerencia o ciclo de vida de todas as imagens através do imageManager, com a cooperação do cadvisor. + +A política para o garbage collection de imagens leva dois fatores em consideração: +`HighThresholdPercent` e `LowThresholdPercent`. Uso do disco acima do limite acionará o garbage collection. O garbage collection excluirá as imagens que foram menos usadas recentemente até que o nível fique abaixo do limite. + +## Coleta de container + +A política para o garbage collection de contêineres considera três variáveis definidas pelo usuário. `MinAge` é a idade mínima em que um contêiner pode ser coletado. `MaxPerPodContainer` é o número máximo de contêineres mortos que todo par de pod (UID, container name) pode ter. `MaxContainers` é o número máximo de contêineres mortos totais. Essas variáveis podem ser desabilitadas individualmente, definindo `MinAge` como zero e definindo `MaxPerPodContainer` e `MaxContainers` respectivamente para menor que zero. + +O Kubelet atuará em contêineres não identificados, excluídos ou fora dos limites definidos pelos sinalizadores mencionados. Os contêineres mais antigos geralmente serão removidos primeiro. `MaxPerPodContainer` e `MaxContainer` podem potencialmente conflitar entre si em situações em que a retenção do número máximo de contêineres por pod (`MaxPerPodContainer`) estaria fora do intervalo permitido de contêineres globais mortos (`MaxContainers`). O `MaxPerPodContainer` seria ajustado nesta situação: O pior cenário seria fazer o downgrade do `MaxPerPodContainer` para 1 e remover os contêineres mais antigos. Além disso, os contêineres pertencentes a pods que foram excluídos são removidos assim que se tornem mais antigos que `MinAge`. + +Os contêineres que não são gerenciados pelo kubelet não estão sujeitos ao garbage collection de contêiner. + +## Configurações do usuário + +Os usuários podem ajustar os seguintes limites para ajustar o garbage collection da imagem com os seguintes sinalizadores do kubelet: + +1. `image-gh-high-threshold`, a porcentagem de uso de disco que aciona o garbage collection da imagem. O padrão é 85%. +2. `image-gc-low-threshold`, a porcentagem de uso de disco com o qual o garbage collection da imagem tenta liberar. O padrão é 80%. + +Também permitimos que os usuários personalizem a política do garbagem collection através dos seguintes sinalizadores do kubelet: + +1. `minimum-container-ttl-duration`, idade mínima para um contêiner finalizado antes de ser colectado. O padrão é 0 minuto, o que significa que todo contêiner finalizado será coletado como lixo. +2. `maximum-dead-containers-per-container`, número máximo de instâncias antigas a serem retidas por contêiner. O padrão é 1. +3. `maximum-dead-containers`, número máximo de instâncias antigas de contêineres para retenção global. O padrão é -1, o que significa que não há limite global. + +Os contêineres podem ser potencialmente coletados como lixo antes que sua utilidade expire. Esses contêineres podem conter logs e outros dados que podem ser úteis para solucionar problemas. Um valor suficientemente grande para `maximum-dead-containers-per-container` é altamente recomendado para permitir que pelo menos 1 contêiner morto seja retido por contêiner esperado. Um valor maior para `maximum-dead-containers` também é recomendados por um motivo semelhante. +Consulte [esta issue](https://github.com/kubernetes/kubernetes/issues/13287) para obter mais detalhes. + +## Descontinuado + +Alguns recursos do Garbage Collection neste documento serão substituídos pelo kubelet eviction no futuro. + +Incluindo: + +| Flag Existente | Nova Flag | Fundamentação | +| ----------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------ | +| `--image-gc-high-threshold` | `--eviction-hard` ou `--eviction-soft` | os sinais existentes de despejo podem acionar o garbage collection da imagem | +| `--image-gc-low-threshold` | `--eviction-minimum-reclaim` | recuperações de despejo atinge o mesmo comportamento | +| `--maximum-dead-containers` | | descontinuado quando os logs antigos forem armazenados fora do contexto do contêiner | +| `--maximum-dead-containers-per-container` | | descontinuado quando os logs antigos forem armazenados fora do contexto do contêiner | +| `--minimum-container-ttl-duration` | | descontinuado quando os logs antigos forem armazenados fora do contexto do contêiner | +| `--low-diskspace-threshold-mb` | `--eviction-hard` ou `eviction-soft` | O despejo generaliza os limites do disco para outros recursos | +| `--outofdisk-transition-frequency` | `--eviction-pressure-transition-period` | O despejo generaliza a transição da pressão do disco para outros recursos | + +{{% /capture %}} + +{{% capture whatsnext %}} + +Consulte [Configurando a Manipulação de Recursos Insuficientes](/docs/tasks/administer-cluster/out-of-resource/) para mais detalhes. + +{{% /capture %}} diff --git a/content/pt/docs/concepts/cluster-administration/logging.md b/content/pt/docs/concepts/cluster-administration/logging.md new file mode 100644 index 0000000000..f605a3e875 --- /dev/null +++ b/content/pt/docs/concepts/cluster-administration/logging.md @@ -0,0 +1,206 @@ +--- +reviewers: + - piosz + - x13n +title: Arquitetura de Log +content_template: templates/concept +weight: 60 +--- + +{{% capture overview %}} + +Os logs de aplicativos e sistemas podem ajudá-lo a entender o que está acontecendo dentro do seu cluster. Os logs são particularmente úteis para depurar problemas e monitorar a atividade do cluster. A maioria das aplicações modernas possui algum tipo de mecanismo de logs; como tal, a maioria dos mecanismos de contêineres também é projetada para suportar algum tipo de log. O método de log mais fácil e abrangente para aplicações em contêiner é gravar nos fluxos de saída e erro padrão. + +No entanto, a funcionalidade nativa fornecida por um mecanismo de contêiner ou tempo de execução geralmente não é suficiente para uma solução completa de log. Por exemplo, se um contêiner travar, um pod for despejado ou um nó morrer, geralmente você ainda desejará acessar os logs do aplicativo. Dessa forma, os logs devem ter armazenamento e ciclo de vida separados, independentemente de nós, pods ou contêineres. Este conceito é chamado _cluster-level-logging_. O log no nível de cluster requer um back-end separado para armazenar, analisar e consultar logs. O kubernetes não fornece uma solução de armazenamento nativa para dados de log, mas você pode integrar muitas soluções de log existentes no cluster do Kubernetes. + +{{% /capture %}} + +{{% capture body %}} + +As arquiteturas de log no nível de cluster são descritas no pressuposto de que um back-end de log esteja presente dentro ou fora do cluster. Se você não estiver interessado em ter o log no nível do cluster, ainda poderá encontrar a descrição de como os logs são armazenados e manipulados no nó para serem úteis. + +## Log básico no Kubernentes + +Nesta seção, você pode ver um exemplo de log básico no Kubernetes que gera dados para o fluxo de saída padrão(standard output stream). Esta demostração usa uma [especificação de pod](/examples/debug/counter-pod.yaml) com um contêiner que grava algum texto na saída padrão uma vez por segundo. + +{{< codenew file="debug/counter-pod.yaml" >}} + +Para executar este pod, use o seguinte comando: + +```shell +kubectl apply -f https://k8s.io/examples/debug/counter-pod.yaml +``` + +A saída será: + +``` +pod/counter created +``` + +Para buscar os logs, use o comando `kubectl logs`, da seguinte maneira: + +```shell +kubectl logs counter +``` + +A saída será: + +``` +0: Mon Jan 1 00:00:00 UTC 2001 +1: Mon Jan 1 00:00:01 UTC 2001 +2: Mon Jan 1 00:00:02 UTC 2001 +... +``` + +Você pode usar `kubectl logs` para recuperar logs de uma instanciação anterior de um contêiner com o sinalizador `--previous`, caso o contêiner tenha falhado. Se o seu pod tiver vários contêineres, você deverá especificar quais logs do contêiner você deseja acessar anexando um nome de contêiner ao comando. Veja a [documentação do `kubectl logs`](/docs/reference/generated/kubectl/kubectl-commands#logs) para mais destalhes. + +## Logs no nível do Nó + +![Log no nível do nó](/images/docs/user-guide/logging/logging-node-level.png) + +Tudo o que um aplicativo em contêiner grava no `stdout` e `stderr` é tratado e redirecionado para algum lugar por dentro do mecanismo de contêiner. Por exemplo, o mecanismo de contêiner do Docker redireciona esses dois fluxos para [um driver de log](https://docs.docker.com/engine/admin/logging/overview), configurado no Kubernetes para gravar em um arquivo no formato json. + +{{< note >}} +O driver de log json do Docker trata cada linha como uma mensagem separada. Ao usar o driver de log do Docker, não há suporte direto para mensagens de várias linhas. Você precisa lidar com mensagens de várias linhas no nível do agente de log ou superior. +{{< /note >}} + +Por padrão, se um contêiner reiniciar, o kubelet manterá um contêiner terminado com seus logs. Se um pod for despejado do nó, todos os contêineres correspondentes também serão despejados, juntamente com seus logs. + +Uma consideração importante no log no nível do nó está implementado a rotação de log, para que os logs não consumam todo o armazenamento disponível no nó. Atualmente, o Kubernentes não é responsável pela rotação de logs, mas uma ferramenta de deployment deve configurar uma solução para resolver isso. +Por exemplo, nos clusters do Kubernetes, implementados pelo script `kube-up.sh`, existe uma ferramenta [`logrotate`](https://linux.die.net/man/8/logrotate) configurada para executar a cada hora. Você pode configurar um tempo de execução do contêiner para girar os logs do aplicativo automaticamente, por exemplo, usando o `log-opt` do Docker. +No script `kube-up.sh`, a última abordagem é usada para imagem COS no GCP, e a anterior é usada em qualquer outro ambiente. Nos dois casos por padrão, a rotação é configurada para ocorrer quando o arquivo de log exceder 10MB. + +Como exemplo, você pode encontrar informações detalhadas sobre como o `kube-up.sh` define o log da imagem COS no GCP no [script][cosconfigurehelper] correspondente. + +Quando você executa [`kubectl logs`](/docs/reference/generated/kubectl/kubectl-commands#logs) como no exemplo de log básico acima, o kubelet no nó lida com a solicitação e lê diretamente do arquivo de log, retornando o conteúdo na resposta. + +{{< note >}} +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 + +### Logs de componentes do sistema + +Existem dois tipos de componentes do sistema: aqueles que são executados em um contêiner e aqueles que não são executados em um contêiner. Por exemplo: + +- O scheduler Kubernetes e o kube-proxy são executados em um contêiner. +- O tempo de execução do kubelet e do contêiner, por exemplo, Docker, não é executado em contêineres. + +Nas máquinas com systemd, o tempo de execução do kubelet e do container é gravado no journald. Se systemd não estiver presente, eles gravam em arquivos `.log` no diretório `/var/log`. +Os componentes do sistema dentro dos contêineres sempre gravam no diretório `/var/log`, ignorando o mecanismo de log padrão. Eles usam a biblioteca de logs [klog][klog]. Você pode encontrar as convenções para a gravidade do log desses componentes nos [documentos de desenvolvimento sobre log](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md). + +Da mesma forma que os logs de contêiner, os logs de componentes do sistema no diretório `/var/log` devem ser rotacionados. Nos clusters do Kubernetes criados pelo script `kube-up.sh`, esses logs são configurados para serem rotacionados pela ferramenta `logrotate` diariamente ou quando o tamanho exceder 100MB. + +[klog]: https://github.com/kubernetes/klog + +## Arquiteturas de log no nível de cluster + +Embora o Kubernetes não forneça uma solução nativa para o log em nível de cluster, há várias abordagens comuns que você pode considerar. Aqui estão algumas opções: + +- Use um agente de log no nível do nó que seja executado em todos os nós. +- Inclua um contêiner sidecar dedicado para efetuar logging em um pod de aplicativo. +- Envie logs diretamente para um back-end de dentro de um aplicativo. + +### Usando um agente de log de nó + +![Usando um agente de log no nível do nó](/images/docs/user-guide/logging/logging-with-node-agent.png) + +Você pode implementar o log em nível de cluster incluindo um _agente de log em nível de nó_ em cada nó. O agente de log é uma ferramenta dedicada que expõe logs ou envia logs para um back-end. Geralmente, o agente de log é um contêiner que tem acesso a um diretório com arquivos de log de todos os contêineres de aplicativos nesse nó. + +Como o agente de log deve ser executado em todos os nós, é comum implementá-lo como uma réplica do DaemonSet, um pod de manifesto ou um processo nativo dedicado no nó. No entanto, as duas últimas abordagens são obsoletas e altamente desencorajadas. + +O uso de um agente de log no nível do nó é a abordagem mais comum e incentivada para um cluster Kubernetes, porque ele cria apenas um agente por nó e não requer alterações nos aplicativos em execução no nó. No entanto, o log no nível do nó _funciona apenas para a saída padrão dos aplicativos e o erro padrão_. + +O Kubernetes não especifica um agente de log, mas dois agentes de log opcionais são fornecidos com a versão Kubernetes: [Stackdriver Logging](/docs/user-guide/logging/stackdriver) para uso com o Google Cloud Platform e [Elasticsearch](/docs/user-guide/logging/elasticsearch). Você pode encontrar mais informações e instruções nos documentos dedicados. Ambos usam [fluentd](http://www.fluentd.org/) com configuração customizada como um agente no nó. + +### Usando um contêiner sidecar com o agente de log + +Você pode usar um contêiner sidecar de uma das seguintes maneiras: + +- O container sidecar transmite os logs do aplicativo para seu próprio `stdout`. +- O contêiner do sidecar executa um agente de log, configurado para selecionar logs de um contêiner de aplicativo. + +#### Streaming sidecar conteiner + +![Conteiner sidecar com um streaming container](/images/docs/user-guide/logging/logging-with-streaming-sidecar.png) + +Fazendo com que seus contêineres de sidecar fluam para seus próprios `stdout` e `stderr`, você pode tirar proveito do kubelet e do agente de log que já executam em cada nó. Os contêineres sidecar lêem logs de um arquivo, socket ou journald. Cada contêiner sidecar individual imprime o log em seu próprio `stdout` ou `stderr` stream. + +Essa abordagem permite separar vários fluxos de logs de diferentes partes do seu aplicativo, algumas das quais podem não ter suporte para gravar em `stdout` ou `stderr`. A lógica por trás do redirecionamento de logs é mínima, portanto dificilmente representa uma sobrecarga significativa. Além disso, como `stdout` e `stderr` são manipulados pelo kubelet, você pode usar ferramentas internas como o `kubectl logs`. + +Considere o seguinte exemplo. Um pod executa um único contêiner e grava em dois arquivos de log diferentes, usando dois formatos diferentes. Aqui está um arquivo de configuração para o Pod: + +{{< codenew file="admin/logging/two-files-counter-pod.yaml" >}} + +Seria uma bagunça ter entradas de log de diferentes formatos no mesmo fluxo de logs, mesmo se você conseguisse redirecionar os dois componentes para o fluxo `stdout` do contêiner. Em vez disso, você pode introduzir dois contêineres sidecar. Cada contêiner sidecar pode direcionar um arquivo de log específico de um volume compartilhado e depois redirecionar os logs para seu próprio fluxo `stdout`. + +Aqui está um arquivo de configuração para um pod que possui dois contêineres sidecar: + +{{< codenew file="admin/logging/two-files-counter-pod-streaming-sidecar.yaml" >}} + +Agora, quando você executa este pod, é possível acessar cada fluxo de log separadamente, executando os seguintes comandos: + +```shell +kubectl logs counter count-log-1 +``` + +``` +0: Mon Jan 1 00:00:00 UTC 2001 +1: Mon Jan 1 00:00:01 UTC 2001 +2: Mon Jan 1 00:00:02 UTC 2001 +... +``` + +```shell +kubectl logs counter count-log-2 +``` + +``` +Mon Jan 1 00:00:00 UTC 2001 INFO 0 +Mon Jan 1 00:00:01 UTC 2001 INFO 1 +Mon Jan 1 00:00:02 UTC 2001 INFO 2 +... +``` + +O agente no nível do nó instalado em seu cluster coleta esses fluxos de logs automaticamente sem nenhuma configuração adicional. Se desejar, você pode configurar o agente para analisar as linhas de log, dependendo do contêiner de origem. + +Observe que, apesar do baixo uso da CPU e da memória (ordem de alguns milicores por CPU e ordem de vários megabytes de memória), gravar logs em um arquivo e depois transmiti-los para o `stdout` pode duplicar o uso do disco. Se você tem um aplicativo que grava em um único arquivo, geralmente é melhor definir `/dev/stdout` como destino, em vez de implementar a abordagem de contêiner de transmissão no sidecar. + +Os contêineres sidecar também podem ser usados para rotacionar arquivos de log que não podem ser rotacionados pelo próprio aplicativo. Um exemplo dessa abordagem é um pequeno contêiner executando `logrotate` periodicamente. +No entanto, é recomendável usar o `stdout` e o `stderr` diretamente e deixar as políticas de rotação e retenção no kubelet. + +#### Contêiner sidecar com um agente de log + +![Contêiner sidecar com um agente de log](/images/docs/user-guide/logging/logging-with-sidecar-agent.png) + +Se o agente de log no nível do nó não for flexível o suficiente para sua situação, você poderá criar um contêiner secundário com um agente de log separado que você configurou especificamente para executar com seu aplicativo. + +{{< note >}} +O uso de um agente de log em um contêiner sidecar pode levar a um consumo significativo de recursos. Além disso, você não poderá acessar esses logs usando o comando `kubectl logs`, porque eles não são controlados pelo kubelet. +{{< /note >}} + +Como exemplo, você pode usar o [Stackdriver](/docs/tasks/debug-application-cluster/logging-stackdriver/), que usa fluentd como um agente de log. Aqui estão dois arquivos de configuração que você pode usar para implementar essa abordagem. O primeiro arquivo contém um [ConfigMap](/docs/tasks/configure-pod-container/configure-pod-configmap/) para configurar o fluentd. + +{{< codenew file="admin/logging/fluentd-sidecar-config.yaml" >}} + +{{< note >}} +A configuração do fluentd está além do escopo deste artigo. Para obter informações sobre como configurar o fluentd, consulte a [documentação oficial do fluentd](http://docs.fluentd.org/). +{{< /note >}} + +O segundo arquivo descreve um pod que possui um contêiner sidecar rodando fluentemente. +O pod monta um volume onde o fluentd pode coletar seus dados de configuração. + +{{< codenew file="admin/logging/two-files-counter-pod-agent-sidecar.yaml" >}} + +Depois de algum tempo, você pode encontrar mensagens de log na interface do Stackdriver. + +Lembre-se de que este é apenas um exemplo e você pode realmente substituir o fluentd por qualquer agente de log, lendo de qualquer fonte dentro de um contêiner de aplicativo. + +### Expondo logs diretamente do aplicativo + +![Expondo logs diretamente do aplicativo](/images/docs/user-guide/logging/logging-from-application.png) + +Você pode implementar o log no nível do cluster, expondo ou enviando logs diretamente de todos os aplicativos; no entanto, a implementação desse mecanismo de log está fora do escopo do Kubernetes. + +{{% /capture %}} diff --git a/content/pt/docs/home/_index.md b/content/pt/docs/home/_index.md index 2fb80a8781..61c2921ce9 100644 --- a/content/pt/docs/home/_index.md +++ b/content/pt/docs/home/_index.md @@ -5,7 +5,7 @@ title: Kubernetes noedit: true cid: docsHome layout: docsportal_home -class: gridPage +class: gridPage gridPageHome linkTitle: "Home" main_menu: true weight: 10 diff --git a/content/pt/examples/admin/logging/fluentd-sidecar-config.yaml b/content/pt/examples/admin/logging/fluentd-sidecar-config.yaml new file mode 100644 index 0000000000..eea1849b03 --- /dev/null +++ b/content/pt/examples/admin/logging/fluentd-sidecar-config.yaml @@ -0,0 +1,25 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: fluentd-config +data: + fluentd.conf: | + + type tail + format none + path /var/log/1.log + pos_file /var/log/1.log.pos + tag count.format1 + + + + type tail + format none + path /var/log/2.log + pos_file /var/log/2.log.pos + tag count.format2 + + + + type google_cloud + diff --git a/content/pt/examples/admin/logging/two-files-counter-pod-agent-sidecar.yaml b/content/pt/examples/admin/logging/two-files-counter-pod-agent-sidecar.yaml new file mode 100644 index 0000000000..b37b616e6f --- /dev/null +++ b/content/pt/examples/admin/logging/two-files-counter-pod-agent-sidecar.yaml @@ -0,0 +1,39 @@ +apiVersion: v1 +kind: Pod +metadata: + name: counter +spec: + containers: + - name: count + image: busybox + args: + - /bin/sh + - -c + - > + i=0; + while true; + do + echo "$i: $(date)" >> /var/log/1.log; + echo "$(date) INFO $i" >> /var/log/2.log; + i=$((i+1)); + sleep 1; + done + volumeMounts: + - name: varlog + mountPath: /var/log + - name: count-agent + image: k8s.gcr.io/fluentd-gcp:1.30 + env: + - name: FLUENTD_ARGS + value: -c /etc/fluentd-config/fluentd.conf + volumeMounts: + - name: varlog + mountPath: /var/log + - name: config-volume + mountPath: /etc/fluentd-config + volumes: + - name: varlog + emptyDir: {} + - name: config-volume + configMap: + name: fluentd-config diff --git a/content/pt/examples/admin/logging/two-files-counter-pod-streaming-sidecar.yaml b/content/pt/examples/admin/logging/two-files-counter-pod-streaming-sidecar.yaml new file mode 100644 index 0000000000..87bd198cfd --- /dev/null +++ b/content/pt/examples/admin/logging/two-files-counter-pod-streaming-sidecar.yaml @@ -0,0 +1,38 @@ +apiVersion: v1 +kind: Pod +metadata: + name: counter +spec: + containers: + - name: count + image: busybox + args: + - /bin/sh + - -c + - > + i=0; + while true; + do + echo "$i: $(date)" >> /var/log/1.log; + echo "$(date) INFO $i" >> /var/log/2.log; + i=$((i+1)); + sleep 1; + done + volumeMounts: + - name: varlog + mountPath: /var/log + - name: count-log-1 + image: busybox + args: [/bin/sh, -c, 'tail -n+1 -f /var/log/1.log'] + volumeMounts: + - name: varlog + mountPath: /var/log + - name: count-log-2 + image: busybox + args: [/bin/sh, -c, 'tail -n+1 -f /var/log/2.log'] + volumeMounts: + - name: varlog + mountPath: /var/log + volumes: + - name: varlog + emptyDir: {} diff --git a/content/pt/examples/admin/logging/two-files-counter-pod.yaml b/content/pt/examples/admin/logging/two-files-counter-pod.yaml new file mode 100644 index 0000000000..6ebeb717a1 --- /dev/null +++ b/content/pt/examples/admin/logging/two-files-counter-pod.yaml @@ -0,0 +1,26 @@ +apiVersion: v1 +kind: Pod +metadata: + name: counter +spec: + containers: + - name: count + image: busybox + args: + - /bin/sh + - -c + - > + i=0; + while true; + do + echo "$i: $(date)" >> /var/log/1.log; + echo "$(date) INFO $i" >> /var/log/2.log; + i=$((i+1)); + sleep 1; + done + volumeMounts: + - name: varlog + mountPath: /var/log + volumes: + - name: varlog + emptyDir: {} diff --git a/content/pt/examples/debug/counter-pod.yaml b/content/pt/examples/debug/counter-pod.yaml new file mode 100644 index 0000000000..f997886386 --- /dev/null +++ b/content/pt/examples/debug/counter-pod.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: Pod +metadata: + name: counter +spec: + containers: + - name: count + image: busybox + args: [/bin/sh, -c, + 'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done'] diff --git a/content/ru/docs/concepts/overview/components.md b/content/ru/docs/concepts/overview/components.md new file mode 100644 index 0000000000..9689c2e1fd --- /dev/null +++ b/content/ru/docs/concepts/overview/components.md @@ -0,0 +1,118 @@ +--- +reviewers: +- lavalamp +title: Компоненты Kubernetes +content_template: templates/concept +weight: 20 +card: + name: concepts + weight: 20 +--- + +{{% capture overview %}} +При развёртывании Kubernetes вы имеете дело с кластером. +{{< glossary_definition term_id="cluster" length="all" prepend="Кластер Kubernetes cluster состоит из">}} + +На этой странице в общих чертах описывается различные компоненты, необходимые для работы кластера Kubernetes. + +Ниже показана диаграмма кластера Kubernetes со всеми связанными компонентами. + +![Компоненты Kubernetes](/images/docs/components-of-kubernetes.png) + +{{% /capture %}} + +{{% capture body %}} + +## Панель управления компонентами + +Компоненты панели управления отвечают за основные операции кластера (например, планирование), а также обрабатывают события кластера (например, запускают новый {{< glossary_tooltip text="под" term_id="pod">}}, когда поле `replicas` развертывания не соответствует требуемому количеству реплик). + +Компоненты панели управления могут быть запущены на любой машине в кластере. Однако для простоты сценарии настройки обычно запускают все компоненты панели управления на одном компьютере и в то же время не позволяют запускать пользовательские контейнеры на этом компьютере. Смотрите страницу [Создание высоконадёжных кластеров](/docs/admin/high-availability/) для примера настройки нескольких ведущих виртуальных машин. + +### kube-apiserver + +{{< glossary_definition term_id="kube-apiserver" length="all" >}} + +### etcd + +{{< glossary_definition term_id="etcd" length="all" >}} + +### kube-scheduler + +{{< glossary_definition term_id="kube-scheduler" length="all" >}} + +### kube-controller-manager + +{{< glossary_definition term_id="kube-controller-manager" length="all" >}} + +Эти контроллеры включают: + + * Контроллер узла (Node Controller): уведомляет и реагирует на сбои узла. + * Контроллер репликации (Replication Controller): поддерживает правильное количество подов для каждого объекта контроллера репликации в системе. + * Контроллер конечных точек (Endpoints Controller): заполняет объект конечных точек (Endpoints), то есть связывает сервисы (Services) и поды (Pods). + * Контроллеры учетных записей и токенов (Account & Token Controllers): создают стандартные учетные записи и токены доступа API для новых пространств имен. + +### cloud-controller-manager + +[cloud-controller-manager](/docs/tasks/administer-cluster/running-cloud-controller/) запускает контроллеры, которые взаимодействуют с основными облачными провайдерами. Двоичный файл cloud-controller-manager — это альфа-функциональность, появившиеся в Kubernetes 1.6. + +cloud-controller-manager запускает только циклы контроллера, относящиеся к облачному провайдеру. Вам нужно отключить эти циклы контроллера в kube-controller-manager. Вы можете отключить циклы контроллера, установив флаг `--cloud-provider` со значением `external` при запуске kube-controller-manager. + +С помощью cloud-controller-manager код как облачных провайдеров, так и самого Kubernetes может разрабатываться независимо друг от друга. В предыдущих версиях код ядра Kubernetes зависел от кода, предназначенного для функциональности облачных провайдеров. В будущих выпусках код, специфичный для облачных провайдеров, должен поддерживаться самим облачным провайдером и компоноваться с cloud-controller-manager во время запуска Kubernetes. + +Следующие контроллеры зависят от облачных провайдеров: + + * Контроллер узла (Node Controller): проверяет облачный провайдер, чтобы определить, был ли удален узел в облаке после того, как он перестал работать + * Контроллер маршрутов (Route Controller): настраивает маршруты в основной инфраструктуре облака + * Контроллер сервисов (Service Controller): создаёт, обновляет и удаляет балансировщики нагрузки облачного провайдера. + * Контроллер тома (Volume Controller): создаёт, присоединяет и монтирует тома, а также взаимодействует с облачным провайдером для оркестрации томов. + +## Компоненты узла + +Компоненты узла работают на каждом узле, поддерживая работу подов и среды выполнения Kubernetes. + +### kubelet + +{{< glossary_definition term_id="kubelet" length="all" >}} + +### kube-proxy + +{{< glossary_definition term_id="kube-proxy" length="all" >}} + +### Среда выполнения контейнера + +{{< glossary_definition term_id="container-runtime" length="all" >}} + +## Дополнения + +Дополнения используют ресурсы Kubernetes ({{< glossary_tooltip term_id="daemonset" >}}, {{< glossary_tooltip term_id="deployment" >}} и т.д.) для расширения функциональности кластера. Поскольку дополнения охватывают весь кластер, ресурсы относятся к пространству имен `kube-system`. + +Некоторые из дополнений описаны ниже; более подробный список доступных расширений вы можете найти на странице [Дополнения](/docs/concepts/cluster-administration/addons/). + +### DNS + +Хотя прочие дополнения не являются строго обязательными, однако при этом у всех Kubernetes-кластеров должен быть [кластерный DNS](/docs/concepts/services-networking/dns-pod-service/), так как многие примеры предполагают его наличие. + +Кластерный DNS — это DNS-сервер наряду с другими DNS-серверами в вашем окружении, который обновляет DNS-записи для сервисов Kubernetes. + +Контейнеры, запущенные посредством Kubernetes, автоматически включают этот DNS-сервер в свои DNS. + +### Веб-интерфейс (Dashboard) + +[Dashboard](/docs/tasks/access-application-cluster/web-ui-dashboard/) — это универсальный веб-интерфейс для кластеров Kubernetes. С помощью этой панели, пользователи могут управлять и устранять неполадки кластера и приложений, работающих в кластере. + +### Мониторинг ресурсов контейнера + +[Мониторинг ресурсов контейнера](/docs/tasks/debug-application-cluster/resource-usage-monitoring/) записывает общие метрики о контейнерах в виде временных рядов в центральной базе данных и предлагает пользовательский интерфейс для просмотра этих данных. + +### Логирование кластера + +Механизм [логирования кластера](/docs/concepts/cluster-administration/logging/) отвечает за сохранение логов контейнера в централизованном хранилище логов с возможностью их поиска/просмотра. + +{{% /capture %}} +{{% capture whatsnext %}} +* Подробнее про [узлы](/docs/concepts/architecture/nodes/) +* Подробнее про [контроллеры](/docs/concepts/architecture/controller/) +* Подробнее про [kube-scheduler](/docs/concepts/scheduling/kube-scheduler/) +* Официальная [документация](https://etcd.io/docs/) etcd +{{% /capture %}} diff --git a/content/ru/docs/concepts/overview/what-is-kubernetes.md b/content/ru/docs/concepts/overview/what-is-kubernetes.md index 3289c8980e..0d57355d1f 100644 --- a/content/ru/docs/concepts/overview/what-is-kubernetes.md +++ b/content/ru/docs/concepts/overview/what-is-kubernetes.md @@ -58,7 +58,7 @@ Kubernetes предоставляет вам: * **Мониторинг сервисов и распределение нагрузки** Kubernetes может обнаружить контейнер, используя имя DNS или собственный IP-адрес. Если трафик в контейнере высокий, Kubernetes может сбалансировать нагрузку и распределить сетевой трафик, чтобы развертывание было стабильным. -* **Орекстрация хранилища** +* **Оркестрация хранилища** Kubernetes позволяет вам автоматически смонтировать систему хранения по вашему выбору, такую как локальное хранилище, провайдеры общедоступного облака и многое другое. * **Автоматическое развертывание и откаты** Используя Kubernetes можно описать желаемое состояние развернутых контейнеров и изменить фактическое состояние на желаемое. Например, вы можете автоматизировать Kubernetes на создание новых контейнеров для развертывания, удаления существующих контейнеров и распределения всех их ресурсов в новый контейнер. diff --git a/content/ru/docs/contribute/advanced.md b/content/ru/docs/contribute/advanced.md new file mode 100644 index 0000000000..b450c088b5 --- /dev/null +++ b/content/ru/docs/contribute/advanced.md @@ -0,0 +1,196 @@ +--- +title: Участие для опытных +slug: advanced +content_template: templates/concept +weight: 30 +--- + +{{% capture overview %}} + +На этой странице предполагается, что вы изучили темы [Участие для начинающих](/ru/docs/contribute/start/) и [Участие для опытных](/ru/docs/contribute/intermediate/) и теперь хотите узнать ещё больше про то, как можно помочь проекту. Для решения некоторых задач вам потребуется использовать Git из командной строки и прочие другие инструменты. + +{{% /capture %}} + +{{% capture body %}} + +## Дежурный по PR на неделю + +[Утверждающие](/ru/docs/contribute/participating/#утверждающие) группы SIG Docs регулярно по очереди становятся дежурными по PR в репозитории и поэтому участвуют в [графике ротации PR-дежурного](https://github.com/kubernetes/website/wiki/PR-Wranglers#2019-schedule-q1q2) на неделю. + +В обязанности дежурного по PR входят: + +- Ежедневно проверять [открытые пулреквесты](https://github.com/kubernetes/website/pulls) для контроля качества и соблюдения рекомендаций по [оформлению](/docs/contribute/style/style-guide/) и [содержимому](/docs/contribute/style/content-guide/). + - В первую очередь просматривайте самые маленькие пулреквесты (`size/XS`), и только потом беритесь за самые большие (`size/XXL`). + - Проверяйте столько пулреквестов, сколько сможете. +- Проследить, что CLA подписан каждым участником. + - Помогайте новым участникам подписать [CLA](https://github.com/kubernetes/community/blob/master/CLA.md). + - Используйте [этот](https://github.com/zparnold/k8s-docs-pr-botherer) скрипт, чтобы автоматически напомнить участникам, не подписавшим CLA, чтобы они подписали CLA. +- Оставить свое мнение о предложенных изменениях и поспособствовать в проведении технического обзора от членов других SIG-групп. + - Предложить исправления для измененного контента в PR. + - Если вы хотите убедиться в правильности контента, прокомментируйте PR и задайте уточняющие вопросы. + - Добавьте нужны метки с `sig/`. + - Если нужно, то назначьте рецензентов из секции `reviewers:` в фронтальной части файла. + - Добавьте метки `Docs Review` и `Tech Review` для установки статуса проверки PR. + - Добавьте метку `Needs Doc Review` или `Needs Tech Review` для пулреквестов, которые ещё не были проверены. + - Добавьте метку `Doc Review: Open Issues` или `Tech Review: Open Issues` для пулреквестов, которые были проверены и требуют дополнительную информацию и выполнение действия перед слиянием. + - Добавьте метки `/lgtm` и `/approve` для пулреквестов, которые могут быть приняты. +- Объедините пулреквесты, если они готовы, либо закройте те, которые не могут быть приняты. +- Ежедневно отсортируйте и пометьте новые заявки. Обратитесь к странице [Участие для опытных](/ru/docs/contribute/intermediate/) для получения информации по использование метаданных SIG Docs. + +### Полезные ссылки на GitHub для дежурных + +Следующие ссылки помогут при дежурстве. После обработки заявок по трём первым ссылкам, как правило, список пулреквестов для проверки сократится. По указанным ссылкам вы найдете PR только в английскую версию, предназначенные для слияния в ветку `master` (кроме последней ссылки). + +- [Нет CLA, нет права на слияние](https://github.com/kubernetes/website/pulls?q=is%3Aopen+is%3Apr+label%3A%22cncf-cla%3A+no%22+-label%3Ado-not-merge+label%3Alanguage%2Fen): напомните участнику подписать CLA. Если об этом уже напомнил и бот, и человек, то закройте PR и напишите автору, что он может открыть свой PR после подписания CLA. +**Не проверяйте PR, если их авторы не подписали CLA!** +- [Требуется LGTM](https://github.com/kubernetes/website/pulls?utf8=%E2%9C%93&q=is%3Aopen+is%3Apr+-label%3Ado-not-merge+label%3Alanguage%2Fen+-label%3Algtm+): если нужен проверка с технической точки зрения, попросите её провести одного из рецензентов, который предложил бот. Если требуется просмотр пулреквест со стороны группы документации или вычитка, то предложите изменения, либо сами измените PR, чтобы ускорить процесс принятия пулреквеста. +- [Имеет LGTM, нужно одобрение со стороны группы документации](https://github.com/kubernetes/website/pulls?q=is%3Aopen+is%3Apr+-label%3Ado-not-merge+label%3Alanguage%2Fen+label%3Algtm): выясните, нужно ли внести какие-либо дополнительные изменения или обновления, чтобы принять PR. Если по вашему мнению PR готов к слияния, оставьте комментарий с текстом `/approve`. +- [Быстрые результаты](https://github.com/kubernetes/website/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+base%3Amaster+-label%3A%22do-not-merge%2Fwork-in-progress%22+-label%3A%22do-not-merge%2Fhold%22+label%3A%22cncf-cla%3A+yes%22+label%3A%22size%2FXS%22+label%3A%22language%2Fen%22+): если маленький PR направлен в основную ветку и не имеет условий для объединения. (поменяйте "XS" в метке с размером при работе с другими пулреквестами [XS, S, M, L, XL, XXL]). +- [Вне основной ветки](https://github.com/kubernetes/website/pulls?utf8=%E2%9C%93&q=is%3Aopen+is%3Apr+-label%3Ado-not-merge+label%3Alanguage%2Fen+-base%3Amaster): если PR отправлен в ветку `dev-`, значит он предназначается для будущего выпуска. Убедитесь, что [release meister](https://github.com/kubernetes/sig-release/tree/master/release-team) знает об этом, добавив комментарий с `/assign @`. Если он направлен в старую ветку, помогите автору PR изменить на более подходящую ветку. + +### Когда закрывать пулреквесты + +Обзоры и одобрения — это только один из способов, позволяющих держать список PR коротким и актуальным. Закрытие пулреквестов — альтернативный метод для этого. + +- Можете закрыть любой PR, если CLA-соглашение не было подписано в течение двух недель. +Авторы PR могут повторно открыть PR после подписания CLA, так что это безопасный способ убедиться, что ничто не будет объединено без подписанного CLA. + +- Закройте любой PR, если автор не отреагировал на комментарии или проверки в течение 2 или более недель. + +Не бойтесь закрывать пулреквесты. Участники с лёгкостью открыть и возобновить незаконченную работу. Зачастую уведомление о закрытии стимулировать автора возобновить и закончить свой вклад. + +Чтобы закрыть пулреквест, оставьте комментарий `/close` в PR. + +{{< note >}} + +Бот [`fejta-bot`](https://github.com/fejta-bot) автоматически помечает заявки как устаревшие после 90 дней отсутствия активности, а затем закрывает их после ещё 30 дней простоя, когда они становятся тухлыми. Дежурные по PR должны закрывать заявки после 14-30 дней бездействия. + +{{< /note >}} + +## Внесение улучшений + +[Члены](/ru/docs/contribute/participating/#члены) SIG Docs могут предлагать улучшения. + +После того, как вы давно начали работать над документацией Kubernetes, у наверняка появились какие-нибудь идеи по улучшению [руководства по оформлению](/docs/contribute/style/style-guide/), [руководства по оформлению](/docs/contribute/style/content-guide/), набору инструментов, который используется для создания документации, стилизации сайта, процессов проверки и объединения пулреквестов. Для максимальной открытости подобные типы предложений по улучшению должны обсуждаться на встречи SIG Docs или в [списке рассылки kubernetes-sig-docs](https://groups.google.com/forum/#!forum/kubernetes-sig-docs). +Помимо этого, это поможет разъяснить, как всё устроено в данный момент, и объяснить, почему так было принято, прежде чем предлагать радикальные изменения. Самый быстрый способ узнать ответы на вопросы о том, как в настоящее время работает документация, это задать их на канале `#sig-docs` Slack на [kubernetes.slack.com](https://kubernetes.slack.com). + +Когда обсуждение состоялось, а SIG-группа согласилась с желаемым результатом, вы можете работать над предлагаемыми изменениями наиболее приемлемым способом. Например, обновление руководства по оформлению или функциональности сайта может включать открытие пулреквеста, а изменение, связанное с тестированием документации, может предполагать взаимодействие с sig-testing. + +## Координация документации по выпуску Kubernetes + +[Утверждающие](/ru/docs/contribute/participating/#утверждающие) SIG Docs могут координировать документацию для выпуска Kubernetes. + +Каждый выпуск Kubernetes координируется командой людей, участвующих в специальной группе (Special Interest Group, SIG) sig-release. Другие члены команды в данном выпуске включают в себя общего руководителя выпуском, а также представителей sig-pm, sig-testing и др. Чтобы узнать больше о процессах выпуска версий Kubernetes, обратитесь к [https://github.com/kubernetes/sig-release](https://github.com/kubernetes/sig-release). + +Представитель SIG Docs для данного выпуска координирует следующие задачи: + +- Мониторинг электронной таблицы с отслеживанием функциональности на наличие новых или измененных возможностей, затрагивают документацию. Если документация для определенной функциональности не будет готова к выпуску, возможно, она не попадет в выпуск. +- Регулярное посещение встречи sig-release и обновлять информацию о статусе документации в выпуске. +- Проверка и вычитка документации по функциональности, подготовленной SIG-группой, ответственной за реализацию этой функциональности. +- Объединение связанных с выпуском пулреквестов и поддержка Git-ветки выпуска. +- Консультируйте других участников SIG Docs, которые хотят научиться выполнять эту роль в будущем. Это называется сопровождение (shadowing). +- Публикация изменений в документации, связанные с выпуском при размещении артефактов. + +Координация выпуска обычно занимает 3-4 месяца, а обязанности распределяются между утверждающими SIG Docs. + +## Амбассадор нового участника + +[Утверждающие](/ru/docs/contribute/participating/#утверждающие) SIG Docs могут выступать в качестве амбассадоров новых участников. + +Амбассадоры новых участников работают бок о бок, чтобы поприветствовать новых участников SIG Docs, предлагать PR новым участникам и консультировать новых участников в их собственных PR. + +Обязанности амбассадоров новых участников включают в себя: + +- Отвечать на вопросы новых участников на [Slack-канале Kubernetes #sig-docs](https://kubernetes.slack.com). +- Совместно работать с дежурным по PR, чтобы определять заявки, которые подойдут для решения новыми участниками. +- Консультировать новых участников в их PR. +- Помогать новых участникам в создании более сложных PR, чтобы они могли стать членами Kubernetes. +- [Оказывать содействие участникам](/ru/docs/contribute/advanced/#поддержка-нового-участника) на их пути становления членом в Kubernetes. + +Текущие амбассадоры новых участников объявляются на каждом собрании SIG Docs и на канале [#sig-docs в Kubernetes](https://kubernetes.slack.com). + +## Поддержка нового участника + +[Рецензенты](/ru/docs/contribute/participating/#рецензенты) SIG Docs могут содействовать новым участникам в членстве организации. + +Если участник сделал 5 значительных пулреквестов в один или несколько репозиториев Kubernetes, он имеет право на [членство](/ru/docs/contribute/participating#члены) в организации Kubernetes. Членство участника должно быть поддержано двумя спонсорами, которые уже являются рецензентами. + +Новые участники документации могут найти спонсоров в канале #sig-docs в [в Slack Kubernetes](https://kubernetes.slack.com) или в [списке рассылки SIG Docs](https://groups.google.com/forum/#!forum/kubernetes-sig-docs). Если вы осознали полезность работы автора заявки на членство, вы добровольно можете поддержать (спонсировать) его. Когда они подадут заявку на членство, отреагируйте на заявку "+1" и напишите подробный комментарий о том, почему вы считаете, что кандидат отлично вписывается в члены организации Kubernetes. + +## Сопредседатель SIG + +[Утверждающие](/ru/docs/contribute/participating/#утверждающие) SIG Docs могут быть сопредседателями SIG Docs. + +### Требования + +Сопредседатели должны соответствовать следующим требованиям: + +- Быть утверждающим SIG Docs не меньше 6 месяцев +- [Руководить выпуском документации Kubernetes](/docs/contribute/advanced/#coordinate-docs-for-a-kubernetes-release) или сопровождать два выпуска +- Понимание рабочих процессов и инструментов SIG Docs: git, Hugo, локализация, блог +- Понимать, как другие SIG-группы и репозитории Kubernetes влияют на рабочий процесс SIG Docs, включая: [команды в k/org](https://github.com/kubernetes/org/blob/master/config/kubernetes/sig-docs/teams.yaml), [процессы в k/community](https://github.com/kubernetes/community/tree/master/sig-docs), плагины в [k/test-infra](https://github.com/kubernetes/test-infra/) и роль [SIG Architecture](https://github.com/kubernetes/community/tree/master/sig-architecture). +- Уделять не менее 5 часов в неделю (но зачастую больше) в течение как минимум 6 месяцев для выполнения обязанностей. + +### Обязанности + +Роль сопредседателя посвящена в основном одной из задач: сопредседатели управляют процессом и политикой, планируют и проводят собрания, назначают дежурных по PR и, как правило, делают то, что никто больше не хочет делать, для увеличения количества участников. + +Обязанности включают в себя: + +- Сосредоточить группу SIG Docs на достижении максимального счастья для разработчиков через отличную документацию +- Быть примером соблюдения [норм поведения сообщества]https://github.com/cncf/foundation/blob/master/code-of-conduct.md) и контролировать их выполнение членами SIG +- Изучение и внедрение передовых практик для SIG-группы, обновляя рекомендации по участию +- Планирование и проведение встреч SIG: еженедельные обновления информации, ежеквартальные ретроспективные/плановые совещания и многое другое +- Планирование и проведение спринтов по документации на мероприятиях KubeCon и других конференциях +- Набирать персонал и выступать в поддержку {{< glossary_tooltip text="CNCF" term_id="cncf" >}} и его платиновых партнеров, включая Google, Oracle, Azure, IBM и Huawei. +- Поддерживать нормальную работу SIG + +### Проведение продуктивных встреч + +Для планирования и проведения результативных встреч мы составили рекомендации, которые показывают и объясняют, как лучше всего их подготовить. + +**Соблюдайте [нормы поведения сообщества](https://github.com/cncf/foundation/blob/master/code-of-conduct.md)**: + +- Привлекайте самый широкий круг участников к дискуссии и уважительно общайтесь между собой, стараясь никого не обидеть. + +**Сформулируйте четкую повестку дня**: + +- Определите конкретную цель встречи +- Опубликуйте программу дня заранее + +Для еженедельных встреч скопируйте примечания из предыдущей недели в раздел "Past meetings". + +**Работайте вместе для создания точных примечания**: + +- Запишите обсуждение встречи +- Подумайте над тем, чтобы делегировать роль стенографист кому-нибудь другому + +**Определяйте решения по пунктам повестки четко и точно**: + +- Записывайте решения по пунктам, кто будет ими заниматься и ожидаемую дату завершения + +**Руководите обсуждением, когда это необходимо**: + +- Если обсуждение выходит за пределы повестки дня, снова обратите внимание участников на обсуждаемую тему +- Найдите место для различных стилей ведения обсуждения, не отвлекаясь от темы обсуждения и уважая время людей + +**Уважайте время людей**: + +- Начинайте и заканчивайте встречи своевременно + +**Используйте Zoom эффективно**: + +- Ознакомьтесь с [рекомендациями Zoom для Kubernetes](https://github.com/kubernetes/community/blob/master/communication/zoom-guidelines.md) +- Попробуйте попроситься быть ведущим в самом начале встречи, введя ключ ведущего + +Исполнение роли ведущего в Zoom + +### Запись встреч на Zoom + +Когда вам потребуется начать запись, нажмите пункт с надписью Record to Cloud. + +Если нужно остановить запись, нажмите на кнопку Stop. + +Запись автоматически загрузится на YouTube. + +{{% /capture %}} diff --git a/content/ru/docs/contribute/intermediate.md b/content/ru/docs/contribute/intermediate.md new file mode 100644 index 0000000000..69dfa285ef --- /dev/null +++ b/content/ru/docs/contribute/intermediate.md @@ -0,0 +1,606 @@ +--- +title: Участие для продвинутых +slug: intermediate +content_template: templates/concept +weight: 20 +card: + name: contribute + weight: 50 +---1 + +{{% capture overview %}} + +На этой странице предполагается, что вы изучили и понимаете задачи на странице [Участие для начинающих](/ru/docs/contribute/start/) и теперь готовы узнать о других способах внести свой вклад. + +{{< note >}} +Некоторые задачи требуют использование Git-клиента из командной строки и других инструментов. +{{< /note >}} + +{{% /capture %}} + +{{% capture body %}} + +Теперь, когда вы уже знаете кое-что и приняли участие в документации Kubernetes, как описано в теме [Участие для начинающих](/ru/docs/contribute/start/), вы можете пойти ещё дальше. Далее пойдут задачи, предусматривающие наличие и желание получить глубокие знания по следующим темам: + +- Концепции Kubernetes +- Рабочие процессы документации Kubernetes +- Поиск нужной информации о будущих возможностях Kubernetes +- Сильные аналитические навыки в целом + +Эти задачи не такие последовательные, как задачи для начинающих. Поэтому мы не ожидаем, что кто-то в одиночку будет постоянно заниматься всеми ими. + +## Знакомство с Prow + +[Prow](https://github.com/kubernetes/test-infra/blob/master/prow/README.md) — это система CI/CD, использующая Kubernetes, которая выполняет задания с пулреквестами (PR). Prow с помощью команд, похожих на те, что есть в чатботах, даёт возможность обрабатывать действия в организации Kubernetes на GitHub. Вы можете выполнять целый ряд действий, такие как добавление и удаление меток, закрытие заявок и назначение утверждающего. Введите Prow-команду в поле для комментария в формате `/`. Некоторые популярные команды: + +- `/lgtm` (looks good to me): добавляет метку `lgtm`, которая сообщает, что рецензент проверил PR +- `/approve`: одобряет PR так, чтобы он мог быть принят (эта команда работает только для утверждающих) +- `/assign`: назначает проверяющего на PR +- `/close`: закрывает ишью или PR +- `/hold`: добавляет метку `do-not-merge/hold`, которая означает, что PR не может быть автоматически принят +- `/hold cancel`: удаляет метку `do-not-merge/hold` + +{{% note %}} +Не все команды работают для каждого пользователя. Бот Prow сообщит вам, если вы пытаетесь выполнить команду, не разрешенную для вашего уровня. +{{% /note %}} + +Детально изучите [список команд Prow](https://prow.k8s.io/command-help), прежде чем начать проверять PR или сортировать ишью. + +## Проверка пулреквестов + +Каждую неделю утверждающий доброволец документации сортирует и просматривает [пулреквесты и заявки](#сортировка-и-классификация-ишью). Такой человек называется "PR Wrangler" на неделю. Расписание ведется с помощью [планировщика PR Wrangler](https://github.com/kubernetes/website/wiki/PR-Wranglers). Чтобы поучаствовать в этом списке, посетите еженедельную встречу SIG Docs. Даже если вас не выбрали дежурным по PR на текущую неделю, вы все равно можете проверять пулреквесты (PR), которые еще не были детально просмотрены. + +В дополнение к ротации автоматизированная система добавляет в каждый новый PR и предлагает рецензентов и утверждающих для него, основываясь на списке утверждающих и рецензентов в измененных файлах. Ожидается, что автор PR будет следовать указаниям бота, поэтому PR должен быть быстро проверить. + +Мы хотим, чтобы пулреквесты принимались и публиковались как можно быстрее. Чтобы документация оставалась точной и актуальной, каждый PR должен проверяться людьми, понимающие суть темы, а также теми, кто имеет опыт написания отличной документации. + +Рецензенты и утверждающие должны предоставить конкретную и конструктивную обратную связь, чтобы заинтересованные участники были вовлечены и помогали им улучшаться. Иногда, чтобы помочь новому участнику подготовить свой PR к слиянию, требуется больше времени, чем просто переписать его самостоятельно, но проект лучше в долгосрочной перспективе, когда у нас есть множество активных участников. + +Прежде чем приступить к проверке PR, убедитесь, что вы знакомы с [руководством по содержанию документации](/docs/contribute/style/content-guide/), [руководством по оформлению документации](/docs/contribute/style/style-guide/) и [нормы поведения](/community/code-of-conduct/). + +### Поиск пулреквестов для проверки + +Чтобы посмотреть все открытые пулреквесты, перейдите на вкладку **Pull Requests** в GitHub-репозитории. +PR можно проверять только, если он соответствует всем перечисленным ниже критериям: + +- Имеет метку `cncf-cla:yes` +- Не содержит надписи WIP в описании +- Не имеет тег с фразой `do-not-merge` +- Нет конфликтов для слияния +- Сделан в правильную ветку (обычно это `master`, за исключением, если PR не относится к невыпущенной ещё функциональности) +- Не проверялся ещё детально другим проверяющим документации (то же самое касается и остальных технических рецензентов), если только этот человек явно не обратился за вашей помощью. В частности, не рекомендуется добавлять много новых комментариев после других циклов рассмотрения PR. + +Если PR не имеет условия для проверки, можно оставить комментарий, чтобы сообщить автору о текущих проблемах и предложить помочь решить их. Если автор пулреквеста был оповещён о проблемах и не устранил их в течение нескольких недель или месяцев, то рано или поздно такой PR будет закрыт. + +Если вы новичок в проверке пулреквестов или у вас недостаточно времени и возможностей, попробуйте поискать PR с тегом `size/XS` или `size/S`. Размер пулреквеста автоматически определяется по количеству изменённых строк в PR. + +#### Рецензенты и утверждающие + +В репозитории сайта Kubernetes работа построена иначе, чем в других репозиториях Kubernetes, когда речь идет о роли рецензентов и утверждающих. Для получения дополнительной информации об обязанностях рецензентов и утверждающих см. [Участие в SIG Docs](/ru/docs/contribute/participating/). Ниже вы найдете краткий обзор. + +- Рецензент проверяет содержание пулреквеста для соблюдения технической точности. Рецензент даёт понять, что PR технически точен, оставляя комментарий с `/lgtm` к PR. + + {{< note >}}Не добавляйте `/lgtm`, если вы не уверены в технической точности документации, измененной или добавленной в PR.{{< /note >}} + +- Утверждающий проверяет содержание запроса на предмет качества и соответствия рекомендациям SIG Docs, приведенным в руководствах по содержанию и оформлению. Только люди, указанные в качестве утверждающих в файле [`OWNERS`](https://github.com/kubernetes/website/blob/master/OWNERS), могут одобрить PR. Чтобы одобрить PR, оставьте комментарий `/approve` к PR. + +PR объединяется, когда у него есть комментарий `/lgtm` от кого-либо из организации Kubernetes и комментарий `/approve` от утверждающего в группе `sig-docs-maintainers`, если он не удерживается, а автор PR подписал CLA. + +{{< note >}} + +Раздел ["Участие"](/ru/docs/contribute/participating/#утверждающие) содержит больше информации для рецензентов и утверждающих, включая конкретные обязанности для утверждающих. + +{{< /note >}} + +### Проверка PR + +1. Изучите описание PR вместе с указанными ишью и ссылками, если они есть. Кратковременные мимолетные обзоры иногда могут наносит больше вреда, чем пользы, поэтому убедитесь, что вы обладаете нужными знаниями, чтобы сделать содержательный обзор. + +2. Если кто-то другой может лучше всего проверит определенный PR, упомяните этого человека, добавив комментарий `/assign @`. Если вы обратились за технической проверкой к человеку, который не занимается документацией, но при этом вы хотите сами посмотреть PR как участник группы документации, то не стесняйтесь это делать. + +3. Перейдите на вкладку **Files changed**. Посмотрите на все изменённые строки. Удалённый текст выделен красным, а строки с ним начинаются с символа `-`. Добавленный текст отмечен зелёным фоном, а строки с ним начинаются с символа `+`. Внутри строки фактически измененный контент имеет чуть более темный зеленый фон, чем остальная часть строки. + + - В частности, если в PR есть сложное форматирование или он изменяет CSS, JavaScript или другие элементы сайта, вы можете просмотреть сайт, сгенерированный с этими изменениями в PR. Перейдите на вкладку **Conversation** и нажмите ссылку **Details** в проверке `deploy/netlify` в нижней части страницы. По умолчанию ссылка открывается в текущей вкладке браузера, поэтому чтобы потерять частичный отзыв, откройте ссылку в новой вкладке. Вернитесь на вкладку **Files changed**, чтобы продолжить проверку пулреквеста. + - Убедитесь, что PR соответствует правилам содержания и оформления; если что-то не так, укажите на этом со ссылкой на раздел в руководстве. + - Если у вас есть вопрос или вы хотите прокомментировать определённое изменение, наведите курсор мыши на строку и кликните на появившуюся сине-белую кнопку с иконкой `+`. Напишите свой комментарий и нажмите на кнопку **Start a review**. + - Если вам нужно оставить больше одного комментария, сделайте это по аналогии с предыдущим шагом. + - По соглашению, если вы видите небольшую проблему, не имеющей отношение к основному назначению PR, например, опечатку или лишний пробел, вы можете сообщить о ней, начав комментарий с `nit:`, чтобы автор знал, что это незначительная ошибка. Хотя это не означает, что автор пулреквеста может проигнорировать такие проблемы. + - Когда вы всё проверили или у вас не осталось комментариев, прокрутите в верхнюю часть страницы и нажмите на кнопку **Review changes**. Далее кликните либо на **Comment** или **Request Changes**. Напишите краткий итог вашей проверки и добавьте соответствующие [Prow-команды](https://prow.k8s.io/command-help) по одной на каждой строке в поле Review Summary. SIG Docs следует [процессу проверки кода Kubernetes](https://github.com/kubernetes/community/blob/master/contributors/guide/owners.md#the-code-review-process). Все ваши комментарии будут отправлены автору PR в виде одного уведомления. + + - Если вы считаете, что PR в хорошем состоянии, чтобы его принять, добавьте команду `/approve` в резюме вашей проверки. + - Если PR не нуждается в дополнительном техническом рассмотрении, добавьте ещё команду `/lgtm`. + - Если PR *требуется* дополнительный технический обзор, добавьте команду `/assign` и после неё укажите логин человека на GitHub, который должен сделать технический анализ. Посмотрите на поле рецензентов во вступительной (фронтальной) части вверху данного Markdown-файла, чтобы выяснить, кто может провести технический разбор пулреквеста. + - Чтобы заблокировать слияние PR, используйте команду `/hold`. Она добавит метку `do-not-merge/hold`. + - Если в PR нет конфликтов и есть метки `lgtm` и `approve` (и нет метки `hold`), то он автоматически объединиться. + - Если PR имеет метки `lgtm` и/или `approve`, и появляются новые изменения, эти метки будут автоматически удалены. + + Посмотрите [список доступных команд](https://prow.k8s.io/command-help), которые можно использовать в PR. + + - Если вы ранее выбрали нажали на **Request changes** и затем автор PR решил все указанные проблемы, вы можете обновить статус проверки либо на вкладке **Files changed**, либо в нижней части вкладки **Conversation**. Обязательно укажите команду `/approve` и при необходимости выберите технических рецензентов, чтобы можно было объединить PR. + +### Редактирование PR другого человека + +Добавление комментариев в PR — полезное дело, но могут быть случаи, когда нужно сделать коммит в пулреквест другого человека, а не просто оставить свой отзыв. + +Не поддавайтесь желанию выполнить работу за другого человека, если только он явно не попросит вас об этом или вы не захотите оживить давно заброшенный PR. Хотя это может быть быстрее в краткосрочной плане, но это лишает человека возможности внести собственный вклад. + +Используемый процесс зависит от того, нужно ли вам отредактировать файл, который уже изменен в PR, либо вам нужно отредактировать файл, который в PR не участвовал. + +Вы не можете отредактировать чужой PR, если выполняется одно из условий: + +- Если автор PR отправил свою ветку непосредственно в репозиторий [https://github.com/kubernetes/website/](https://github.com/kubernetes/website/), то только рецензент с правом отправки изменений напрямую в репозиторий может вносить изменения в PR. + Авторам следует открыть PR из ветки в своей копии репозитория. +- Если автор PR явно запретил редактирование утверждающими, вы не сможете внести изменения в его PR, пока он не изменит эту настройку. + +#### Если файл уже изменён в PR + +Этот метод использует интерфейс GitHub. Вы можете использовать командную строку, если вам комфортнее работать в ней, даже если вам нужно изменить файл, который ранее редактировался в PR. + +1. Перейдите на вкладку **Files changed**. +2. Прокрутите к блоку с файлом, который вы хотите отредактировать и нажмите на иконку с карандашом. +3. Внесите изменения, напишите сообщение коммита в соответствующем поле под текстовым редактором и нажмите **Commit changes**. + +После этого ваш коммит отправляется в ветку из PR (скорее всего, в копию репозитория автора), и теперь отображается в PR, а ваши изменения отражаются на вкладке **Files changed**. Оставьте комментарий, чтобы автор PR знал, что вы что-то сделали в PR. + +Если автор использует командную строку, а не сайт GitHub для работы с этим PR, он должен получить изменения со своей копии репозитория и перебазировать свою локальную ветку на ветку своей копии, прежде чем заниматься своим PR. + +#### Если файл ещё не был изменён в PR + +Если необходимо внести изменения в файл, который не был отредактирован в рамках конкретного PR, нужно использовать командную строку. Вам придётся по душе такой метод, если вы предпочитаете использовать терминал вместо использования сайта GitHub. + +1. Узнайте URL-адрес копии репозитория автора пулреквеста. Вы можете найти его в нижней части вкладки **Conversation**. Найдите текст **Add more commits by pushing to**. Первая ссылка после этой надписи ведет на ветку, а вторая ссылка — на саму копию репозитория. Скопируйте вторую ссылку. Запомните название ветки, пригодится впоследствии. + +2. Добавьте копию репозитория как новый удаленный репозиторий. В терминале перейдите в директорию своей копии репозитория. Придумайте имя для удаленного репозитория (например, по имени логина автора на GitHub) и добавьте его, используя следующую команду: + + ```bash + git remote add + ``` + +3. Получите информацию о добавленном удаленном репозитории. Это действие не затронет локальные файлы, а только загрузит в вашу копии репозитория информацию о другой копии (например, ветки и теги). + + ```bash + git remote fetch + ``` + +4. Перейдите в ветку, полученную с удаленного репозитория. Эта команда не получится, если у вас локально уже есть ветка с таким же именем. + + ```bash + git checkout + ``` + +5. Внесите изменения и добавьте их через `git add`, а затем зафиксируйте их. + +6. Отправьте изменения в удаленный репозиторий автора. + + ```bash + git push + ``` + +7. Откройте снова сайт GitHub и обновите страницу PR. Вы увидите ваши изменения. Добавьте комментарий для автора, чтобы он был в курсе, что вы изменили его PR. + +Если автор использует командную строку, а не интерфейс на GitHub для работы над PR, ему нужно получить новые изменения из своей копии репозитоии и перебазировать свою локальную ветку на ветку своей копии репозитории, прежде чем снова заниматься собственным PR. + +## Работа из локальной копии + +В случае изменений нескольких файлов, либо добавлением новых или перемещением старых, лучше работать из локальной копии Git-репозитория на компьютере, нежели чем использовать для этого GitHub. Следующие инструкции используют командую утилиту `git`, которая предполагается, что она уже установлена на вашем компьютере. Вы можете воспользоваться ими даже, если пользуетесь графическим Git-клиента. + +### Клонирование репозитория + +Вам нужно только один раз клонировать репозиторий на каждом компьютере, на котором вы работаете с документацией Kubernetes. + +1. Создайте копию репозитория `kubernetes/website` на GitHub. В браузере перейдите по [https://github.com/kubernetes/website](https://github.com/kubernetes/website) и нажмите на кнопку **Fork**. После нескольких секунд вы будете автоматически перенаправлены на URL-адрес вашей копии, которая будет иметь следующий вид: `https://github.com//website`. + +2. В окне термина используйте команду `git clone` для получения копии репозитория. + + ```bash + git clone git@github.com//website + ``` + + После выполнения этой команды в текущей рабочей директории появится новая директория `website` с содержимым вашего репозитория на GitHub. В данном случае удаленный репозиторий `origin` будет ссылаться на вашу копию репозитория. + +3. Перейдите в новую директорию `website`. Добавьте новый удалённый репозиторий `kubernetes/website` под именем `upstream`. + + ```bash + cd website + + git remote add upstream https://github.com/kubernetes/website.git + ``` + +4. Проверьте ваши репозитории `origin` и `upstream`. + + ```bash + git remote -v + ``` + + Output is similar to: + + ```bash + origin git@github.com:/website.git (fetch) + origin git@github.com:/website.git (push) + upstream https://github.com/kubernetes/website (fetch) + upstream https://github.com/kubernetes/website (push) + ``` + +### Работа в локальном репозитории + +Прежде чем начать работать в локальном репозитории, вам нужно выяснить, из какой ветки будет основываться ваша работа. Ответ на этот вопрос зависит от того, что хотите сделать, но можно руководствоваться следующими правилами: + +- Для общих улучшений существующего контента создайте собственную ветку от ветки `master`. +- Для добавления нового контента про функциональность, которая уже есть в текущих версиях Kubernetes, начните с ветки `master`. +- В случае большой и длительной работы, над которой будут трудиться несколько участников SIG Docs, например, реорганизация контента, создайте отдельную ветку, специально предназначенной для этого. +- Для нового контента про будущие, но ещё не выпущенные версии Kubernetes, работайте в ветке предварительного выпуска, созданной специально для этой версии Kubernetes. + +Для получения дополнительной информации обратитесь к разделу [Выбор правильной ветки](/ru/docs/contribute/start/#выбор-правильной-ветки-в-git). + +После того, как вы определили, с какой ветви начать свою работу (или на какой ветке будет _базироваться_ ваша работа, если говорить в терминологии Git), следуйте определённому ниже рабочему процессу, чтобы ваша работа оставалась актуальной. + +1. Когда вы работаете локально, есть три разные копии репозитория: `local`, `upstream` и `origin`. Получите данные по удалённым репозиториям `origin` и `upstream`. Эта команда очистит кеш удаленных репозиториях без фактического изменения каких-либо из копии. + + ```bash + git fetch origin + git fetch upstream + ``` + + Этот рабочий процесс отличается от того, который определен в [сообществе GitHub](https://github.com/kubernetes/community/blob/master/contributors/guide/github-workflow.md). Здесь вам не нужно объединять вашу локальную копию `master` из репозитория `upstream/master`, прежде чем отправлять изменения в вашу копию. Этот шаг не требуется в `kubernetes/website`, потому что ваша ветка базируется на репозитории upstream. + +2. Создайте локальную рабочую ветку из наиболее подходящей ветки upstream-репозитория: `upstream/dev-1.xx` для разработчиков в конкретных версиях или `upstream/master` для всех остальных участников. В этом примере предполагается, что вы будете работать с ветки `upstream/master`. Так как ваша локальная ветка `master` не настроена для отслеживания изменений с `upstream/master` на предыдущем шаге, поэтому вам нужно явно создать свою ветку от `upstream/master`. + + ```bash + git checkout -b upstream/master + ``` + +3. После переключения на новую ветку можно начать в ней работать в текстовом редакторе. Используйте команду `git status` , чтобы посмотреть измененные файлы. + +4. Когда вы закончите работу, зафиксируйте изменения. Сначала выполните команду `git status`, чтобы увидеть, какие изменения будут добавлены в коммит. В выводе этой команды есть две важные секции: `Changes staged for commit` и `Changes not staged for commit`. Файлы в последней секции, рядом с которыми есть надпись `modified` или `untracked`, необходимо добавить, если вы хотите, чтобы они попали в коммит. Для каждого файла, который нужно добавить, используйте команду `git add`. + + ```bash + git add example-file.md + ``` + + Когда все изменённые файлы добавлены, зафиксируйте их с помощью команды `git commit`: + + ```bash + git commit -m "Your commit message" + ``` + + {{< note >}} + В сообщении коммита не указывайте идентификатор или URL-адрес ишью или пулреквеста на GitHub. Если вы это сделаете, на странице ишью или пулреквеста будет показана информация о коммите всякий раз, когда коммит будет появляться в новой Git-ветке. Вы можете сослаться на ишью и пулреквесты позже на сайте GitHub. + {{< /note >}} + +5. При желании вы можете посмотреть, как ваши изменения будут выглядеть на сайте, если запустите сайт на вашей машине с помощью команды `hugo`. Посмотрите раздел [Просмотр ваших изменений локально](#просмотр-изменений-локально). Кроме этого, вы увидите свои изменения после создания пулреквеста. + +6. Перед тем, как открывать пулреквест с вашими изменениями вам для начала отправить в ветку удаленного репозитория, чем в данном случае является `origin`. + + ```bash + git push origin + ``` + + Технически вы можете не указать имя ветки в команде `push`, но корректное выполнение команды в таком случае зависит от используемой версии Git. Результаты будут более ожидаемыми, если вы напишите название ветки. + +7. Перейдите по адресу https://github.com/kubernetes/website в вашем браузере. GitHub определит и укажет вам, что вы загрузили новую ветку в свою копию, и поэтому предложит создать пулреквест. Заполните шаблон запроса. + + - Название должно быть не длиннее 50 символов и отражать краткий итог изменений. + - Подробное описание должно содержать больше информации про исправление, включая строку типа `Fixes #12345`, если пулреквест решает проблему на GitHub. Это приведет к автоматическому закрытию указанной ишью после принятия пулреквеста. + - Вы можете добавить метки или другие метаданные и назначить рецензентов. Смотрите страницу [Сортировка и классификация ишью](#сортировка-и-классификация-ишью). + + Нажмите на кнопку **Create pull request**. + +8. Начнут выполняться автоматические тесты в зависимости от состояния сайта с вашими изменениями. Если какой-либо из тестов завершился неудачно, нажмите на ссылку **Details** для получения дополнительной информации. Если тест Netlify прошёл успешно, по ссылке **Details** вы можете найти предварительную версию сайта Kubernetes с внесенными вашими изменениями. Именно на ней рецензенты будут проверять ваши изменения. + +9. Если вам необходимо что-то дополнить, изменить пулреквест в соответствии с выполненной проверкой, либо изменить текст коммита, вы можете использовать команду ниже. + + ```bash + git commit -a --amend + ``` + + - `-a`: зафиксировать все изменения + - `--amend`: изменить предыдущий коммит вместо создания нового + + Откроется текстовый редактор, чтобы вы могли отредактировать сообщение коммита, если это нужно. + + Если вы используете `git commit -m`, как в шаге 4, вы сделаете новый коммит, а не измените исходный (предыдущий) коммит. Создание нового коммита означает, что вам нужно объединить свои коммиты до того, прежде чем пулреквест может быть объединен. + + Следуйте инструкциям в шаге 6, чтобы отправить новый коммит в удаленный репозиторий. После этого новое изменение отобразится в пулреквесте, а дальше снова запустятся тесты, а также произойдет новая сборка предварительной версии сайта на Netlify с последними изменениями. + +10. Если рецензент изменяет файлы в вашем пулреквесте, вам нужно получить новые изменения в вашей локальной копии, до того как снова начать что-то делать. Используйте команды ниже, чтобы обновить свою ветку (предполагается, что ветка уже получена с вашей копии репозитория). + + ```bash + git fetch origin + git rebase origin/ + ``` + + После перебазирования вам нужно добавить флаг `--force-with-lease`, чтобы принудительно отправить новые изменения в ветке на вашу копию. + + ```bash + git push --force-with-lease origin + ``` + +11. Может возникнуть конфликт, если кто-то, как и вы, изменил те же части файла в ветке, из которой была создана ваша ветка. Если пулреквест показывает, что есть конфликты, которые нужно разрешить, вы можете сделать это либо на сайте GitHub, либо исправить их локально. + + Сначала выполните шаг 10, чтобы актуализировать локальную ветку в соответствии с веткой в удаленном репозитории. + + Затем обновите репозиторий `upstream` и перебазируйте вашу ветку на ту, с которой она была создана, в данном случае это `upstream/master`. + + ```bash + git fetch upstream + git rebase upstream/master + ``` + + Если есть конфликты, которые Git не может разрешить автоматически, вы можете увидеть конфликтующие файлы с помощью команды `git status`. Отредактируйте каждый конфликтующий файл: найдите в них маркеры конфликта `>>>`, `<<<` и `===`. Разрешение конфликта происходит путём удаления указанных маркеров конфликта. После это нужно добавить измененные файлы с помощью команды `git add ` и продолжить перебазирование ветки, используя команду `git rebase --continue`. Когда всё зафиксировано в репозитории и не осталось неразрешенных конфликтов, команда `git status` покажет, что вы вышли из состояния перебазирования ветки и нет изменений для фиксации. На этом этапе вам осталось принудительно отправить ветку в свою копию репозитория, после чего на странице пулреквеста не должны быть конфликты. + +12. Если у вашего PR отображаются несколько сделанных коммитов после редактирования предыдущих коммитов, вам следует объединить эти несколько коммитов в один коммит, чтобы PR мог быть объединен. Проверить количество коммитов можно на вкладке `Commits` на странице PR или выполнив `git log` в терминале. Объединение коммитов (Squashing commits) — это одна из форм перебазирования. + + ```bash + git rebase -i HEAD~ + ``` + + Ключ `-i` сообщает git, что вы хотите сделать перебазирование в интерактивном режиме. В этом режиме вы сможете выбрать для git, какие коммиты нужно объединить в один. Например, в вашей ветке есть 3 коммита: + + ``` + 12345 commit 4 (2 minutes ago) + 6789d commit 3 (30 minutes ago) + 456df commit 2 (1 day ago) + ``` + + Вам нужно объединить свои последние три коммита в один-единственный. + + ``` + git rebase -i HEAD~3 + ``` + + Эта команда откроет редактор с таким содержимым: + + ``` + pick 456df commit 2 + pick 6789d commit 3 + pick 12345 commit 4 + ``` + + Измените `pick` на `squash` у тех коммитов, которые вы хотите объединить, и проверьте, что коммит с выбранным `pick` находится сверху. + + ``` + pick 456df commit 2 + squash 6789d commit 3 + squash 12345 commit 4 + ``` + + Сохраните и закройте редактор. Затем отправьте объединённый коммит в репозитории с помощью команды `git push --force-with-lease origin `. + +Если у вас возникли проблемы с разрешением конфликтов или вы долго не можете что-то разрешить, что связано с вашим пулреквестом, обратитесь за помощью в Slack-канал `#sig-docs` или в [список рассылки kubernetes-sig-docs](https://groups.google.com/forum/#!forum/kubernetes-sig-docs). + +### Просмотр изменений локально + +{{< tabs name="tab_with_hugo" >}} +{{% tab name="Hugo в контейнере" %}} + +Если вы ещё не готовы создать пулреквесты, но при этом хотите посмотреть, как будет выглядеть сайт с вашими изменениями, то можете собрать и запустить образ Docker, чтобы сгенерировать всю документацию и открыть ее на своем компьютере. + +1. Соберите образ локально: + + ```bash + make docker-image + ``` + +2. После того. как образ `kubernetes-hugo` собран, вы можете использовать его для запуска сайта: + + ```bash + make docker-serve + ``` + +3. В адресной строке браузера введите вставьте адрес `localhost:1313`. Hugo будет следить за изменениями файловой системы и пересобирать сайт по мере необходимости. + +4. Чтобы остановить локальный сайт Hugo, откройте снова терминал и введите `Ctrl+C` или просто закройте окно с терминалом. + +{{% /tab %}} +{{% tab name="Hugo на локальном компьютере" %}} + +1. Установите версию [Hugo](https://gohugo.io/getting-started/installing/), которая указана в файле [`website/netlify.toml`](https://raw.githubusercontent.com/kubernetes/website/master/netlify.toml). + +2. В терминале перейдите в корневую директорию вашей копии документации Kubernetes и введите следующую команду: + + ```bash + hugo server + ``` + +3. В адресной строке браузера скопируйте `localhost:1313`. + +4. Чтобы остановить локальный сайт Hugo, откройте снова терминал и введите `Ctrl+C` или просто закройте окно с терминалом. +{{% /tab %}} +{{< /tabs >}} + +## Сортировка и классификация ишью + +Люди в SIG Docs отвечают только за сортировку и классификацию ишью, связанных с документацией. Вопросы и проблемы общего характера также хранятся в репозитории `kubernetes/website`. + +Что вы делаете, когда сортируете ишью: + +- Проверить ишью + - Убедитесь, что ишью связана с документацией сайта. Некоторые заявки можно быстро закрыть, ответив на вопрос или указав автору на ресурс. Подробности смотрите в разделе [Заявки с помощью или отчёты об ошибке в коде](#заявки-с-помощью-или-отчёты-об-ошибке-в-коде). + - Рассмотрите, насколько обоснованной является заявка. Добавьте метку `triage/needs-information`, если в ишью описано мало подробностей, чтобы ее можно было начать решать, либо если шаблон был неправильно заполнен. + Закройте заявку, если она имеет метки `lifecycle/stale` и `triage/needs-information`. +- Добавьте метку с приоритетом (см. [руководство по сортировке заявок](https://github.com/kubernetes/community/blob/master/contributors/guide/issue-triage.md#define-priority), где подробно определены метки) + - `priority/critical-urgent` - заниматься нужно прямо сейчас + - `priority/important-soon` - нужно выполнить в течение 3 months + - `priority/important-longterm` - нужно сделать в течение 6 months + - `priority/backlog` - решение можно быть отложено на неопределенный срок indefinitely; самый низкий приоритет; делать, когда будут свободны ресурсы + - `priority/awaiting-more-evidence` - указание, что это возможно хорошая задача, которую нужно иметь на виду +- Дополнительно вы можете добавить метку `help` или `good first issue`, если определенная заявка может быть решена человеком, мало знакомым с Kubernetes или SIG Docs. В качестве руководства обратитесь к файлу [Help Wanted and Good First Issue Labels](https://github.com/kubernetes/community/blob/master/contributors/guide/help-wanted.md). +- При желании примите сами участие в ишью и отправьте PR для ее решения (в частности если она может быстро разрешена или вы ранее выполняли нечто подобное). + +С помощью [этого фильтра](https://github.com/kubernetes/website/issues?q=is%3Aissue+is%3Aopen+-label%3Apriority%2Fbacklog+-label%3Apriority%2Fimportant-longterm+-label%3Apriority%2Fimportant-soon+-label%3Atriage%2Fneeds-information+-label%3Atriage%2Fsupport+sort%3Acreated-asc) можно найти заявки, которые необходимо отсортировать. + +Если у вас есть вопросы о про сортировку, спросите в Slack-канале `#sig-docs` или в [списке рассылки kubernetes-sig-docs](https://groups.google.com/forum/#!forum/kubernetes-sig-docs). + +### Добавление и удаление меток + +Для добавления метки нужен комментарий, содержащий что-то вроде `/` или `/ `. Метка уже должна быть создана в репозитории. Если вы попытаетесь добавить несуществующую метку, команда проигнорируется. + +Примеры: + +- `/triage needs-information` +- `/priority important-soon` +- `/language ja` +- `/help` +- `/good-first-issue` +- `/lifecycle frozen` + +Для удаления метки нужен комментарий с `/remove-` или `/remove- `. + +Примеры: + +- `/remove-triage needs-information` +- `/remove-priority important-soon` +- `/remove-language ja` +- `/remove-help` +- `/remove-good-first-issue` +- `/remove-lifecycle frozen` + +Список всех меток, используемых в Kubernetes, находится [здесь](https://github.com/kubernetes/kubernetes/labels). Не все метки используются группой SIG Docs. + +### Дополнительные сведения о метках + +- Ишью может иметь несколько ярлыков. +- Некоторые метки в своём имени содержат слеш для группировки, это своего рода "подметки". Например, существует множество меток `sig/`, например, `sig/cli` и `sig/api-machinery` ([полный список](https://github.com/kubernetes/website/labels?utf8=%E2%9C%93&q=sig%2F)). +- Некоторые метки добавляются автоматически, в зависимости от метаданных файлов из ишью, либо от используемых в комментариях команд со слешем, а также от указанной информации в описании. +- Новые метки могут добавляться вручную человеком, который сортировкой ишью (либо тем, кто создает ишью). + - `kind/bug`, `kind/feature` и `kind/documentation`: баг (bug) — это проблема в текущем контенте или в функциональности, а возможность (feature) — запрос на добавление нового контента или функциональности. + Метка `kind/documentation` используется редко. + - Метки `language/ja`, `language/ko` и похожие [языковые метки](https://github.com/kubernetes/website/labels?utf8=%E2%9C%93&q=language) добавляются, если ишью относится к локализованному контенту. + +### Жизненный цикл ишью + +Ишью обычно открываются и закрываются в течение относительно короткого промежутка времени. Однако иногда решение заявки после ее создания может и не быть. Иногда ишью может оставаться открытой гораздо дольше, чем 90 дней. + +`lifecycle/stale`: после 90 дней бездействия ишью автоматически помечается как устаревшая (stale). Такая заявка будет автоматически закрыта, если эта метка не будет удалена с помощью команды `/remove-lifecycle stale`. + +`lifecycle/frozen`: заявка с данной меткой не будет считаться устаревшей после 90 дней отсутствия активности. Пользователь вручную добавляет эту метку к заявкам, которые должны оставаться открытыми значительно дольше 90 дней, например, у ишью с меткой `priority/important-longterm`. + +### Обработка специальных типов ишью + +Мы встречаем перечисленные ниже типы заявкой достаточно часто, поэтому расписали, как их обрабатывать. + +#### Дублирование заявок + +Если для какой-нибудь проблемы есть одна или несколько открытых заявок, решение этой проблемы должно быть вынесено в одну заявку. Вам нужно решить, какую заявку оставить открытой (либо вовсе открыть новую ишью), перенести всю соответствующую информацию и указать связанные заявки. Затем для всех остальных похожих заявок добавьте метку с `triage/duplicate` и закройте их. Наличие только одной-единственной заявки поможет уменьшить путаницу и избежать дублирования работы над одной и той же проблемой. + +#### Заявки про неработающие ссылки + +В зависимости от того, где сообщается о неработающей ссылке, для решения этой проблемы требуются различные действия. Неработающие ссылки в API и документации Kubectl — это заявки, связанные с автоматизацией и поэтому их нужно отмечать меткой `/priority critical-urgent`, пока проблема не будет полностью проанализирована. Все остальные неработающие ссылки — это ишью, которым нужно заниматься вручную, поэтому им нужно добавить метку `/priority important-longterm`. + +#### Заявки, связанные с блогом + +Записи в [блоге Kubernetes](https://kubernetes.io/blog/) будут терять актуальность со временем, поэтому мы поддерживаем записи, опубликованные в течение года. Если заявка сообщает о проблеме в записи блога, которой более одного года, ее следует закрыть без какого-либо исправления. + +#### Заявки с помощью или отчёты об ошибке в коде + +Некоторые открытые заявки — это проблемы с основным кодом или просьбы с помощью, когда что-то (например, учебное руководство) не работает. Для заявок, не имеющих отношение к документации, закройте её, проставив метку `triage/support` и добавив комментарий с ресурсами, где можно найти помощь (Slack, Stack Overflow) и при необходимости укажите, где нужно открыть заявку, чтобы сообщить об ошибке в функциональности (вероятно, репозиторий kubernetes/kubernetes отлично подойдет для этого). + +Пример ответа на запрос о помощи: + +```none +This issue 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. +``` + +Пример ответа на сообщение об ошибке в коде: + +```none +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. +``` + +## Добавление документации для новой функциональности + +Каждый мажорный выпуск Kubernetes несет в себе новую функциональность, для большей части из которой нужно написать хоть краткую документацию, чтобы показать людям, как её использовать. + +Зачастую SIG-группа, ответственная за новую функциональность, представляют черновик документацию в виде пулреквеста в соответствующую ветку выпуска в репозитории `kubernetes/website`, а кто-то из команды SIG Docs могут сделать вычитку или отредактировать черновик напрямую. + +### Поиск информации о новой функциональности + +Чтобы узнать о будущей функциональности, посетите еженедельную встречу sig-release (см. страницу [Сообщество](https://kubernetes.io/community/), чтобы быть в курсе предстоящих собраний) и отслеживайте документацию к новому релизу в репозитории [kubernetes/sig-release](https://github.com/kubernetes/sig-release/). Каждый выпуск имеет поддиректорию в директории [/sig-release/tree/master/releases/](https://github.com/kubernetes/sig-release/tree/master/releases). Каждая директорию содержит график выхода новой версии, черновик с примечаниями к выпуску, а также документ, в котором перечислена команда, занимающаяся новым выпуском. + +- График выпуска содержит ссылки на все другие документы, встречи, протоколы собраний и этапы, связанные с выпуском. Он также содержит информацию о целях и сроках выпуска, а также о любых специальных процессах, используемых этом выпуске. В нижней части документа определены несколько терминов, связанных с выпуском. + + Этот документ также содержит ссылку на **лист отслеживания функциональности** — это "официальный" способ узнать про новую функциональность, запланированной в выпуске. + +- В документе команды выпуска указано, кто какую роль занимает. Если непонятно, с кем можно поговорить об определенной функциональности или вы хотите что-то спросить, то либо посетите встречу по этому выпуску, чтобы задать свой вопрос, либо обратитесь к руководителю. + +- Черновик примечаний к выпуску — хорошая отправная точка, где можно узнать чуть больше о конкретной функциональности, изменениях, устаревших возможностях и в целом что-то ещё о выпуске. Содержимое может обновляться до конца цикла выпуска, поэтому будьте начеку. + +#### Лист отслеживания функциональности + +В списке отслеживания функциональности [для данного выпуска Kubernetes](https://github.com/kubernetes/sig-release/tree/master/releases) перечислена вся функциональность, запланированная для выпуска. Каждая строка содержит название возможности, ссылку на основную заявку GitHub, уровень стабильности (Alpha, Beta или Stable), группу SIG и ответственного лица за её реализацию, информацию про документацию, черновик примечания для выпуска, а также указание, была ли функциональность уже принята. Имейте в виду следующее: + +- Функциональность в состоянии Beta и Stable обычно имеет более высокий приоритет по сравнению с версией Alpha. +- Трудно протестировать (и, следовательно, написать документацию) функциональности, которая не ещё принята или,по крайней мере, считается полнофункциональной в своем PR. +- Определение, нужна ли документировать функциональности, производится вручную, и даже если у функциональности нет метки, что ей нужна документация, это не означает, это действительно так. + +### Документирование функциональности + +Как отмечалось выше, черновик документации для новой функциональности обычно предлагается SIG-группой, ответственной за реализацию новой функциональности. Это означает, вы в данном случае будете больше наблюдающим (куратором) в данной функциональности, нежели чем полноценным автором документации для неё. + +После того, как вы выбрали функциональность для документирования/наблюдения, заявите об этом в Slack-канале `#sig-docs`, на еженедельной встрече sig-docs или напрямую в PR, отправленном SIG. Если вам дали добро, вы можете редактировать PR, используя один из способов, указанных в разделе [Редактирование PR другого человека](#редактирование-PR-другого-человека). + +Если вам нужно написать новую тему, полезны следующие ссылки: + +- [Написание новых тем](/docs/contribute/style/write-new-topic/) +- [Использование шаблонов страниц](/docs/contribute/style/page-templates/) +- [Руководство по оформлению документации](/docs/contribute/style/style-guide/) +- [Руководство по содержанию документации](/docs/contribute/style/content-guide/) + +### Члены SIG, участвующие в документировании новой функциональности + +Если вы участник SIG-группы, кто разрабатывает новую функциональность для Kubernetes, вам нужно работать с документацией SIG, чтобы убедиться, что на момент новой версии написана документация для этой функциональности. Проверьте [электронную таблицу с отслеживанием функциональности](https://github.com/kubernetes/sig-release/tree/master/releases) или присоединитесь в Slack-канал #sig-release, чтобы узнать информацию о сроках выхода. Некоторые крайние сроки касательно документации: + +- **Docs deadline - Open placeholder PRs**: откройте пулреквест в ветку `release-X.Y` в репозитории `kubernetes/website` с небольшим коммитом, который вы позже измените. Используйте команду Prow `/milestone X.Y`, чтобы назначить PR соответствующему этапу. Это уведомляет человека, который занимается документацией и ответственный за этот выпуск, что выходит документация для новой функциональности. Если функциональность не нуждается в каких-либо изменениях документации, убедитесь, что команда sig-release знает об этом, написав им сообщение в Slack-канале #sig-release. Если для функциональности нужна документация, но PR для этого ещё не создан, функциональность может быть удалена из этапа. +- **Docs deadline - PRs ready for review**: теперь ваш PR должен содержать первый черновик документации для вашей функциональности. Не беспокойтесь о форматировании или всяких улучшениях. Просто опишите, что делает эта функциональность и как ее использовать. Участник из группы документации, управляющий выпуском новой версии, будет работать вместе с вами, чтобы подготовить контент для публикации. Если вашей функциональности нужна документация и первого черновика с документацией до сих пор нет, эта функциональность может быть удалена из этапа. +- **Docs complete - All PRs reviewed and ready to merge**: если ваш PR еще не был объединен в ветку `release-X.Y` к заданному крайнему сроку, обратитесь за помощью к человеку, ответственному за выпуск новой версии. Если вашей функциональности требуется документация, но она ещё не сделана, функциональность может быть удалена из этапа. + +Если ваша функциональность находится в альфа-версии и ее не нельзя отключить, убедитесь, что вы добавили ее к [переключателем возможностей](/docs/reference/command-line-tools-reference/feature-gates/) в вашем пулреквесте. Если ваша функциональность переходит из альфа-версии, обязательно удалите ее из этого файла. + +## Участие к других репозиториях + +В [проекте Kubernetes](https://github.com/kubernetes) более 50 самостоятельных репозиториев. Многие из этих репозиториев хранят код или контент, который можно рассматривать как документацию, например, справочный текст для пользователях, сообщения об ошибках, пользовательский текст в справочниках API или даже комментарии кода. + +Если вы видите текст и не знаете, откуда он берётся, вы можете использовать поиск GitHub по репозиториям организации Kubernetes, чтобы выяснить, где встречается этот текст. Это поможет вам определиться с тем, куда создать заявку или PR. + +У каждого репозитория могут быть определены собственные процессы и правила. До того как открыть проблему или отправить PR, изучите файлы `README.md`, `CONTRIBUTING.md` и `code-of-conduct.md` в репозитории, если они есть. + +Большинство репозиториев используют шаблоны для заявок и PR. Просмотрите некоторые открытые заявки и PR, чтобы понять, как устроена работа. Обязательно как можно более подробно заполните шаблоны при открытии заявок или PR. + +## Локализация контента + +Английский является основным языком документации Kubernetes, однако мы хотим, чтобы у людей была возможность читать документацию на своём родном языке. Если вам комфортно писать на другом языке, особенно в теме программного обеспечения, вы можете помочь перевести документацию Kubernetes или помочь с существующим переводом. Посмотрите страницу [Локализация](/ru/docs/contribute/localization/) и задайте вопрос в [списке рассылки kubernetes-sig-docs](https://groups.google.com/forum/#!forum/kubernetes-sig-docs) или в канале `#sig-docs` на Slack, если вы хотите помочь. + +### Работа с локализованным контентом + +Старайтесь соблюдать эти рекомендации по работе с переведенным контентом: + +- В PR должны быть изменения касающиеся только одного языка. + + В каждом языке есть собственные рецензенты и утверждающие. + +- Рецензентам: убедитесь, что PR содержат изменения только на одном языке. + + Если PR изменяет файлы на нескольких языках, попросите автора открыть отдельные PR для каждого языка. + +{{% /capture %}} + +{{% capture whatsnext %}} + +Если вы хорошо осознали все задачи, затронутые в этом разделе, и хотите более тесно работать с командой документации Kubernetes, переходите к изучению [руководства для опытного участника](/ru/docs/contribute/advanced/). + +{{% /capture %}} diff --git a/content/ru/docs/contribute/localization.md b/content/ru/docs/contribute/localization.md new file mode 100644 index 0000000000..4706ff4e90 --- /dev/null +++ b/content/ru/docs/contribute/localization.md @@ -0,0 +1,286 @@ +--- +title: Локализация документации Kubernetes +content_template: templates/concept +card: + name: contribute + weight: 30 + title: Перевод документации +--- + +{{% capture overview %}} + +На этой странице рассказывается, как [локализовать](https://blog.mozilla.org/l10n/2011/12/14/i18n-vs-l10n-whats-the-diff/) документацию на разные языки. + +{{% /capture %}} + +{{% capture body %}} + +## Начало работы + +Из-за того, что участники не могут одобрять собственные пулреквесты, нужно как минимум два участника для инициализации локализацию. + +Все команды по локализации должны быть самодостаточными. Это означает, что мы с радостью разместим вашу работу, но мы не можем сделать перевод за вас. + +### Определение двухбуквенного кода языка + +Первым делом ознакомьтесь со [стандартом ISO 639-1](https://www.loc.gov/standards/iso639-2/php/code_list.php), чтобы найти двухбуквенный код страны для вашей локализации. Например, двухбуквенный код для корейского языка будет `ko`. + +### Создание копии репозитория + +Для начала [создайте собственную копию репозитория](/ru/docs/contribute/start/#улучшение-существующего-текста) оригинального репозитория [kubernetes/website](https://github.com/kubernetes/website). + +Затем клонируйте свою копию репозитория и перейдите в неё с помощью команды `cd`: + +```shell +git clone https://github.com//website +cd website +``` + +### Создание пулреквеста + +Далее [откройте пулреквест](/ru/docs/contribute/start/#отправка-пулреквеста) (PR) с локализацией в репозиторий `kubernetes/website`. + +Для того, чтобы ваш пулреквест был одобрен, он должен содержать [необходимый минимум контента](#необходимый-минимум-контента). + +В качестве примера добавления новой локализации, изучите PR, который добавляет [документацию на французском](https://github.com/kubernetes/website/pull/12548). + +### Вступление в GitHub-организацию Kubernetes + +Как только, как вы открыли PR с локализацией, вы можете стать членом организации Kubernetes на GitHub. Каждый член команды должен подать [запрос на членство в организации](https://github.com/kubernetes/org/issues/new/choose) в репозитории `kubernetes/org`. + +### Добавление команды локализации на GitHub + +Теперь нужно добавить вашу команду локализации Kubernetes в файл [`sig-docs/teams.yaml`](https://github.com/kubernetes/org/blob/master/config/kubernetes/sig-docs/teams.yaml). Для примера добавления команды локализации можете посмотреть PR, добавляющий [испанскую команду локализации](https://github.com/kubernetes/org/pull/685). + +Члены `@kubernetes/sig-docs-**-owners` — могут одобрять PR, которые изменяют файлы внутри (и только там) директории с локализацией: `/content/**/`. + +Для каждой локализации группа `@kubernetes/sig-docs-**-reviews` служит для автоматизации выбора проверяющих новых PR. + +Члены `@kubernetes/website-maintainers` могут создавать новые ветки для координации работ по переводу. + +Члены `@kubernetes/website-milestone-maintainers` могут использовать [Prow-команду](https://prow.k8s.io/command-help) `/milestone` для контрольных точек для ишью или PR. + +### Настройка рабочего процесса + +Затем добавьте собственную GitHub-метку для вашей локализации в репозиторий `kubernetes/test-infra`. Метка позволяет фильтровать ишью и пулреквесты по конкретному языку. + +Смотрите пример добавления [метки для итальянского языка](https://github.com/kubernetes/test-infra/pull/11316). + +### Поиск сообщества + +Сообщите участниками группы Kubernetes SIG Docs о вашем намерении перевода документации! Подключайтесь к [Slack-каналу SIG Docs](https://kubernetes.slack.com/messages/C1J0BPD2M/). Остальные команды по локализации с радостью помогут вам начать и ответят на любые вопросы. + +Вы также можете создать Slack-канал для своей локализации в репозитории `kubernetes/community`. Для примера посмотрите PR с [добавлением Slack-канала для индонезийского и португальского языков](https://github.com/kubernetes/community/pull/3605). + +## Необходимый минимум контента + +### Изменение конфигурации сайта + +Сайт Kubernetes использует использует фреймворк Hugo. Конфигурация сайта у Hugo находится в файле [`config.toml`](https://github.com/kubernetes/website/tree/master/config.toml). Для поддержки новой локализации вам нужно отредактировать файл `config.toml`. + +Добавьте блок с конфигурацией для нового языка в `config.toml` после существующего блока `[languages]`. Например, конфигурация для немецкой локализации будет выглядить так: + +```toml +[languages.de] +title = "Kubernetes" +description = "Produktionsreife Container-Verwaltung" +languageName = "Deutsch" +contentDir = "content/de" +weight = 3 +``` + +При выбора значения для параметра `weight` в блока найдите языковой блок с наибольшим значением и прибавьте к нему 1. + +Для получения дополнительной информации о многоязычной поддержке в Hugo посмотрите страницу "[Multilingual Mode](https://gohugo.io/content-management/multilingual/)". + +### Добавление директории для локализации + +Добавьте директорию для вашего языка в директорию [`content`](https://github.com/kubernetes/website/tree/master/content) репозитория. Например, двухбуквенный код для немецкого будет `de`: + +```shell +mkdir content/de +``` + +### Перевод норм поведения сообщества + +Откройте PR в репозитории [`cncf/foundation`](https://github.com/cncf/foundation/tree/master/code-of-conduct-languages) и добавьте перевод норм поведения на своём языке. + +### Добавление перевода для файла README + +Чтобы помочь другим участников локализации добавьте новый файл [`README-**.md`](https://help.github.com/articles/about-readmes/) в корневую директорию k/website, где `**` означает двухбуквенный код языка. Например, немецкий файл README будет именоваться как `README-de.md`. + +Подготовьте рекомендации для участников в файле для конкретной локализации `README-**.md`. В этом файле должна быть точно такая же информация, что и в оригинальном README.md ту же информацию, включая также: + +- Контактное лицо проекта локализации +- Любая другая информация, относящаяся к локализации + +После создания перевода файла README добавьте ссылку на файл в основной английский файл `README.md` и добавьте контактную информацию на английском языке. Вы можете указать логин на GitHub, адрес электронной почты, Slack-канал или какой-нибудь способ связи. Вам также нужно добавить ссылку на перевод норм поведения в сообществе. + +### Настройка файлов OWNERS + +Для определения роли каждого пользователя, участвующего в локализации, создайте файл `OWNERS` в директории языка, указав в нём следующие секции: + +- **reviewers**: список Kubernetes-команд с ролями рецензентов, в данном случае команда `sig-docs-**-reviews` будет создана в разделе [Добавление команды локализации на GitHub](#добавление-команды-локализации-на-github). +- **approvers**: список Kubernetes-команд с ролями утверждающих, в данном случае команда `sig-docs-**-owners` будет создана в разделе [Добавление команды локализации на GitHub](#добавление-команды-локализации-на-github). +- **labels**: список GitHub-меток, которые будут автоматически добавляться к PR, в данном случае метка языка будет создана в разделе [Настройка рабочего процесса](#настройка-рабочего-процесса). + +Дополнительную информацию о файле `OWNERS` вы можете получить по ссылке [go.k8s.io/owners](https://go.k8s.io/owners). + +[Испанский файл OWNERS](https://git.k8s.io/website/content/es/OWNERS) с кодом языка `es` выглядит следующим образом: + +```yaml +# See the OWNERS docs at https://go.k8s.io/owners + +# This is the localization project for Spanish. +# Teams and members are visible at https://github.com/orgs/kubernetes/teams. + +reviewers: +- sig-docs-es-reviews + +approvers: +- sig-docs-es-owners + +labels: +- language/es +``` + +После добавления файла `OWNERS` в определенном языке нужно обновить [корневой файл `OWNERS_ALIASES`](https://git.k8s.io/website/OWNERS_ALIASES), добавив новые команды локализации Kubernetes — `sig-docs-**-owners` и `sig-docs-**-reviews`. + +Для каждой команды добавьте список GitHub-пользователей из раздела [Добавление команды локализации на GitHub](#добавление-команды-локализации-на-github), перечислите их в алфавитном порядке. + +```diff +--- a/OWNERS_ALIASES ++++ b/OWNERS_ALIASES +@@ -48,6 +48,14 @@ aliases: + - stewart-yu + - xiangpengzhao + - zhangxiaoyu-zidif ++ sig-docs-es-owners: # Admins for Spanish content ++ - alexbrand ++ - raelga ++ sig-docs-es-reviews: # PR reviews for Spanish content ++ - alexbrand ++ - electrocucaracha ++ - glo-pena ++ - raelga + sig-docs-fr-owners: # Admins for French content + - perriea + - remyleone +``` + +## Перевод контента + +Локализация *всей* документации Kubernetes — колоссальная задача. Вполне нормально начать переводить что-то небольшое, а затем со временем делать перевод больших страниц. + +Как минимум, все локализации должны включать: + +Описание | URL-адреса +-----|----- +Главная | [Все заголовки и подзаголовки URL-адресов](/ru/docs/home/) +Установка | [Все заголовки и подзаголовки URL-адресов](/ru/docs/setup/) +Руководства | [Основы Kubernetes](/ru/docs/tutorials/kubernetes-basics/), [Привет, Minikube](/ru/docs/tutorials/stateless-application/hello-minikube/) +Надписи на сайте | [Все надписи сайта в собственном TOML-файле](https://github.com/kubernetes/website/tree/master/i18n) + +Переведенные файлы должны находиться в собственной директории `content/**/`, но в во всём остальном должны быть такие, как и оригинал на английском. Например, чтобы подготовить [Основы Kubernetes](/ru/docs/tutorials/kubernetes-basics/) для перевода на немецкий язык, создайте поддиректорию в директории `content/de/` и скопируйте туда оригинальный английский файл: + +```shell +mkdir -p content/de/docs/tutorials +cp content/en/docs/tutorials/kubernetes-basics.md content/de/docs/tutorials/kubernetes-basics.md +``` + +С помощью соответствующих инструментов можно ускорить процесс перевода. Например, у некоторых редакторов есть плагины для быстрого перевода текста. + +{{< caution >}} +Использование только машинного перевода не будет соответствовать минимальному уровню качества и поэтому такой перевод требует тщательного ручного рассмотрения для соблюдения стандарта качества. +{{< /caution >}} + +To ensure accuracy in grammar and meaning, members of your localization team should carefully review all machine-generated translations before publishing. + +### Исходные файлы + +Локализация должна исходить из самой последней версии оригинальной документации — {{< latest-version >}}. + +Для того, чтобы получить исходные файлы последней версии: + +1. Перейдите в репозиторий сайта Kubernetes по адресу https://github.com/kubernetes/website. +2. Выберите ветку `release-1.X` самой последней версии. + +Текущая последняя версия {{< latest-version >}}, поэтому веткой для этого релиза будет [`{{< release-branch >}}`](https://github.com/kubernetes/website/tree/{{< release-branch >}}). + +### Сообщения на сайте в i18n/ + +Локализации должны включать содержимое файла [`i18n/en.toml`](https://github.com/kubernetes/website/blob/master/i18n/en.toml) в новый языковой файл. В качестве примера рассмотрим немецкую локализацию: `i18n/de.toml`. + +Добавьте новый файл локализации в `i18n/`. Например, для немецкой локализации (`de`): + +```shell +cp i18n/en.toml i18n/de.toml +``` + +Затем переведите значение каждого сообщения: + +```TOML +[docs_label_i_am] +other = "ICH BIN..." +``` + +Локализация сообщений сайта позволяет изменить сообщения, используемые на всём сайте, к примеру, текст авторских прав в футере на каждой странице. + +### Глоссарий и руководство по оформления для языка + +У некоторых языковых команд есть собственные руководства по оформлению и глоссарий. Например, посмотрите [руководство корейской локализации](/ko/docs/contribute/localization_ko/). + +## Стратегия работы с ветками + +Работа в проектах локализации осуществляется посредством совместных усилий, поэтому мы приветствуем решение команды работать в общих ветках разработки. + +Совместная работа в рабочих ветках может быть организована следующим образом: + +1. Член команды [@kubernetes/website-maintainers](https://github.com/orgs/kubernetes/teams/website-maintainers) создает ветку из оригинальной ветки на https://github.com/kubernetes/website. + + После того, как вы [добавите свою команду локализации](#добавление-команды-локализации-на-github) в репозиторий [`kubernetes/org`](https://github.com/kubernetes/org), ваши утверждающие из группы будет присоединены к команде `@kubernetes/website-maintainers`. + + Мы рекомендуем следующую схему именования веток: + + `dev-<оригинальная версия>-<код языка>.<контрольная точка команды>` + + Например, утверждающий в немецкой группе локализации открывает рабочую ветку `dev-1.12-de.1` непосредственно в репозитории kubernetes/website из ветки для Kubernetes v1.12. + +2. Остальные участники создают новые ветки с изменениями на основе рабочей ветки. + + Например, участник немецкой группы локализации открывает пулреквест с изменениями в `kubernetes:dev-1.12-de.1` из `username:local-branch-name`. + +3. Утверждающий проверяет изменения и объединяют ветки в рабочую веткой. + +4. Периодически утверждающий объединяет рабочую ветку в оригинальную ветку, открывая и принимая новый пулреквест. Не забудьте объединить (squash) коммиты перед слиянием пулреквеста. + +Повторяйте шаги 1-4 до тех пор, пока не будет завершена локализация. Например, по мере работы над немецким переводом, рабочие ветки будут меняться: `dev-1.12-de.2`, `dev-1.12-de.3` и т.д. + +Команды должны объединять переведённый контент в ту же ветку выпуска, из которой она была создана. Например, рабочая ветка, созданная из версии {{< release-branch >}}, должна сливаться с веткой версии 1.17. + +Утверждающему следует поддерживать рабочую веку в актуальном состоянии в соответствии с оригинальной веткой, разрешая конфликты при слиянии. Чем дольше существует рабочая ветки, тем больше потребуется сил для ее поддержки. Поэтому лучше как можно быстрее сливать рабочую ветку и открывать новую, а не поддерживать только одну-единственную в течение длительного времени. + +В начале каждой контрольной точки команды полезно открыть ишью для сравнения изменений между предыдущей веткой и текущей рабочей веткой. + +Хотя только утверждающие могут открывать новую рабочую ветку и сливать пулреквесты, но любой может открыть пулреквест с новой веткой, которая может быть рабочей для команды. Никаких специальных разрешений для этого не требуется. + +Для получения дополнительной информации о работе с копиями или непосредственно с оригинальным репозиторией смотрите раздел по [созданию и клонированию копии репозитория](#создание-копии-репозитория). + +## Участие в работе над оригинальным контентом + +SIG Docs приветствует [участие и дополнения](/ru/docs/contribute/intermediate#локализация-контента) в английскую документацию. + +## Помощь для существующей локализации + +Вы также можете добавлять или улучшать контент в уже существующей локализации. Обратитесь к соответствующему [Slack-каналу](https://kubernetes.slack.com/messages/C1J0BPD2M/) для этого и начинайте помогать через PR. + +{{% /capture %}} + +{{% capture whatsnext %}} + +Как только локализация будет соответствовать требованиям установленного рабочего процесса и содержать требуемый минимум контента, группа SIG Docs: + +- Добавит язык на сайт +- Сообщит о новой локализации на каналах [Cloud Native Computing Foundation](https://www.cncf.io/about/) (CNCF), включая [блог Kubernetes](https://kubernetes.io/blog/). + +{{% /capture %}} diff --git a/content/ru/docs/contribute/participating.md b/content/ru/docs/contribute/participating.md index 2460e19d6d..b0f1a743ba 100644 --- a/content/ru/docs/contribute/participating.md +++ b/content/ru/docs/contribute/participating.md @@ -20,7 +20,7 @@ SIG Docs активно принимает правки и дополнения ## Роли и обязанности -- **Любой** может поучаствовать в документацию Kubernetes. Для этого вам нужно только [подписать CLA](/docs/contribute/start#sign-the-cla) и иметь аккаунт на GitHub. +- **Любой** может поучаствовать в документацию Kubernetes. Для этого вам нужно только [подписать CLA](/ru/docs/contribute/start#sign-the-cla) и иметь аккаунт на GitHub. - **Члены** организации Kubernetes — участники, которые активно занимаются пректом Kubernetes, как правило, открывая пулреквесты с принятыми изменениями. Посмотрите файл [Членство в сообществе](https://github.com/kubernetes/community/blob/master/community-membership.md), чтобы узнать про необходимые условия для членства. - **Рецензент** SIG Docs — член организации Kubernetes, который занимается проверкой пулреквестов и поэтому был добавлен в соответствующую группу на GitHub и в файлы `OWNERS` в GitHub-репозитории. - **Утверждающий** SIG Docs — член организации с хорошей репутацией, который подтвердил неизменную приверженность проекту. Утверждающий может принимать пулреквесты и публиковаться от имени организации Kubernetes. Утверждающие также могут представлять группу SIG Docs в более крупном сообществе Kubernetes. Некоторые из задач утверждающего SIG Docs, например, координация новой версии, требуют значительных затрат по времени. @@ -37,7 +37,7 @@ SIG Docs активно принимает правки и дополнения Если вы не входите в организацию Kubernetes, то команда `/lgtm` не проставил автоматически соответствующую метку. {{< /note >}} -После [подписания CLA](/docs/contribute/start#sign-the-cla) каждый также может: +После [подписания CLA](/ru/docs/contribute/start#sign-the-cla) каждый также может: - Открыть пулреквест, чтобы улучшить существующий текст, либо что-то новое, или написать запись в блоге или описать пример использования. ## Члены @@ -55,7 +55,7 @@ SIG Docs активно принимает правки и дополнения После того, как вы успешно отправили не менее 5 содержательных пулреквестов, вы можете стать [членом](https://github.com/kubernetes/community/blob/master/community-membership.md#member) организации Kubernetes. Следуйте нижеперечисленным шагам: -1. Найдите двух рецензентов или утверждающих, которые [поддержат](/docs/contribute/advanced#sponsor-a-new-contributor) ваше членство. +1. Найдите двух рецензентов или утверждающих, которые [поддержат](/ru/docs/contribute/advanced#поддержка-нового-участника) ваше членство. Запросите спонсорство в канале [#sig-docs Kubernetes Slack](https://kubernetes.slack.com) или в [списке рассылки SIG Docs](https://groups.google.com/forum/#!forum/kubernetes-sig-docs). @@ -150,7 +150,7 @@ SIG Docs активно принимает правки и дополнения - Перед одобрением пулреквеста перейдите на предварительный просмотр сайта на Netlify для сделанных изменений в PR, и убедитесь, что всё содержимое выглядит хорошо. -- Участвуйте в [графике дежурства смотрителя PR](https://github.com/kubernetes/website/wiki/PR-Wranglers), чтобы вас назначили дежурным проверяющим на неделю. SIG Docs ожидает, что все утверждающие примут участие в этом графике. За подробностям обратитесь к странице [Be the PR Wrangler for a week](/docs/contribute/advanced#be-the-pr-wrangler-for-a-week). +- Участвуйте в [графике дежурства смотрителя PR](https://github.com/kubernetes/website/wiki/PR-Wranglers), чтобы вас назначили дежурным проверяющим на неделю. SIG Docs ожидает, что все утверждающие примут участие в этом графике. За подробностям обратитесь к странице [Be the PR Wrangler for a week](/ru/docs/contribute/advanced#дежурный-по-pr-на-неделю). ## Председатель SIG Docs @@ -194,7 +194,7 @@ SIG Docs активно принимает правки и дополнения - Когда пулреквест имеет метки `lgtm` и `approve`, при этом у него нет метки `hold`, и то же время все тесты успешно проходят, то пулреквест автоматически сливается. - Члены организации Kubernetes и утверждающие SIG Docs могут оставлять комментарии со специальными командами, которые блокирует автоматическое объединение пулреквеста (добавление комментарий с текстом `/hold` или удаление ранее установленной метки `/lgtm`). - Любой участник Kubernetes может добавить метку `lgtm`, добавив комментарий, включающий в себя `/lgtm`. -- Только утверждающие SIG Docs могут слить пулреквест путём добавления комментария с `/approve`. Некоторые утверждающие также играют дополнительные роли, например, [смотрителя PR](#pr-wrangler) или [председателя SIG Docs](#председатель-sig-docs). +- Только утверждающие SIG Docs могут слить пулреквест путём добавления комментария с `/approve`. Некоторые утверждающие также играют дополнительные роли, например, [дежурного по PR](#pr-wrangler) или [председателя SIG Docs](#председатель-sig-docs). {{% /capture %}} @@ -202,7 +202,7 @@ SIG Docs активно принимает правки и дополнения Для получения дополнительной информации про участие в документации Kubernetes, посмотрите следующие страницы: -- [Начало участия](/ru/docs/contribute/start/) +- [Участие для начинающих](/ru/docs/contribute/start/) - [Правила оформления документации](/ru/docs/contribute/style/) {{% /capture %}} diff --git a/content/ru/docs/contribute/start.md b/content/ru/docs/contribute/start.md index c6149d60a2..da0af7eb22 100644 --- a/content/ru/docs/contribute/start.md +++ b/content/ru/docs/contribute/start.md @@ -1,5 +1,5 @@ --- -title: Start contributing +title: Участие для начинающих slug: start content_template: templates/concept weight: 10 @@ -25,12 +25,12 @@ card: Вы можете создавать новые задачи, редактировать содержимое и проверять изменения от других участников, — всё это доступно с сайта GitHub. Вы также можете использовать встроенный в GitHub поиск и историю коммитов. -Не все задачи могут быть выполнены на GitHub, поэтому они обсуждаются в [intermediate](/docs/contribute/intermediate/) and -[advanced](/docs/contribute/advanced/) docs contribution guides. +Не все задачи могут быть выполнены с помощью интерфейса GitHub, но некоторые из них обсуждаются в руководствах для [продвинутых](/ru/docs/contribute/intermediate/) и +[опытных](/ru/docs/contribute/advanced/) участников. ### Участие в документации SIG -Документация Kubernetes поддерживается {{< glossary_tooltip text="специальной группой" term_id="sig" >}} (Special Interest Group, SIG) под названием SIG Docs. Мы [общаемся](#participate-in-sig-docs-discussions) с помощью канала Slack, списка рассылки и еженедельных видеозвонков. Будем рады новым участникам. Для получения дополнительной информации обратитесь к странице [Participating in SIG Docs](/docs/contribute/participating/). +Документация Kubernetes поддерживается {{< glossary_tooltip text="специальной группой" term_id="sig" >}} (Special Interest Group, SIG) под названием SIG Docs. Мы [общаемся](#participate-in-sig-docs-discussions) с помощью канала Slack, списка рассылки и еженедельных видеозвонков. Будем рады новым участникам. Для получения дополнительной информации обратитесь к странице [Участие в SIG Docs](ru/docs/contribute/participating/). ### Руководящие принципы по содержанию @@ -40,7 +40,7 @@ card: Мы поддерживаем [руководство по оформлению](/docs/contribute/style/style-guide/) с информацией о выборе, сделанном сообществом SIG Docs в отношении грамматики, синтаксиса, исходного форматирования и типографских соглашений. Прежде чем сделать свой первый вклад, просмотрите руководство по стилю и используйте его, когда у вас есть вопросы. -SIG Docs совместными усилиями вносит изменения в руководство по оформлению. Чтобы предложить изменение или дополнение, добавьте его в повестку дня предстоящей встречи SIG Docs и посетите её, чтобы принять участие в обсуждении. Смотрите страницу с [продвинутым руководством](/docs/contribute/advanced/) для получения дополнительной информации. +SIG Docs совместными усилиями вносит изменения в руководство по оформлению. Чтобы предложить изменение или дополнение, добавьте его в повестку дня предстоящей встречи SIG Docs и посетите её, чтобы принять участие в обсуждении. Смотрите руководство для [продвинутых участников](/docs/contribute/advanced/), чтобы получить дополнительную информацию. ### Шаблоны страниц @@ -56,7 +56,7 @@ SIG Docs совместными усилиями вносит изменения Более подробную информацию про участие в работе над документацией на нескольких языках ["Localize content"](/docs/contribute/intermediate#localize-content) в промежуточном руководстве по добавлению. -Если вы заинтересованы в переводе документации на новый язык, посмотрите раздел ["Локализация"](/docs/contribute/localization/). +Если вы заинтересованы в переводе документации на новый язык, посмотрите раздел ["Локализация"](/ru/docs/contribute/localization/). ## Создание хороших заявок @@ -66,7 +66,7 @@ SIG Docs совместными усилиями вносит изменения - **Для существующей страницы** - Если заметили проблему на существующей странице в [документации Kubernetes](/docs/), перейдите в конец страницы и нажмите кнопку **Create an Issue**. Если вы ещё не авторизованы в GitHub, сделайте это. После этого откроется страница с форма для создания нового запроса в GitHub с уже предварительно заполненным полями. + Если заметили проблему на существующей странице в [документации Kubernetes](/ru/docs/), перейдите в конец страницы и нажмите кнопку **Create an Issue**. Если вы ещё не авторизованы в GitHub, сделайте это. После этого откроется страница с форма для создания нового запроса в GitHub с уже предварительно заполненным полями. При помощи разметки Markdown опишите как можно подробнее, что хотите. Там, где вы видите пустые квадратные скобки (`[ ]`), проставьте `x` между скобками. Если у вас есть предлагаемое решение проблемы, напишите его. @@ -106,7 +106,7 @@ SIG Docs совместными усилиями вносит изменения Примечание. Разработчики кода Kubernetes. Если вы документируете новую функцию для предстоящего выпуска Kubernetes, ваш процесс будет немного другим. См. Документирование функции для руководства по процессу и информации о сроках. {{< note >}} -**Для разработчиков кода Kubernetes**: если вы документируете новую функциональность для новой версии Kubernetes, то процесс рассмотрения будет немного другим. Посетите страницу [Документирование функциональности](/docs/contribute/intermediate/#sig-members-documenting-new-features), чтобы узнать про процесс и информацию о крайних сроках. +**Для разработчиков кода Kubernetes**: если вы документируете новую функциональность для новой версии Kubernetes, то процесс рассмотрения будет немного другим. Посетите страницу [Документирование функциональности](/ru/docs/contribute/intermediate/#добавление-документации-для-новой-функциональности), чтобы узнать про процесс и информацию о крайних сроках. {{< /note >}} ### Подписание CLA-соглашения CNCF {#sign-the-cla} @@ -116,7 +116,7 @@ SIG Docs совместными усилиями вносит изменения ### Поиск задач для работы -Если вы уже нашли что исправить, просто следуйте инструкциям ниже. Для этого вам не обязательно [создавать ишью](#file-actionable-issues) (хотя вы, безусловно, пойти этим путём). +Если вы уже нашли что исправить, просто следуйте инструкциям ниже. Для этого вам не обязательно [создавать ишью](#создание-хороших-заявок) (хотя вы, безусловно, пойти этим путём). Если вы хотите ещё не определились с тем, над чем хотите поработать, перейдите по адресу [https://github.com/kubernetes/website/issues](https://github.com/kubernetes/website/issues) и найдите ишью с меткой `good first issue` (вы можете использовать [эту](https://github.com/kubernetes/website/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) ссылку для быстрого поиска). Прочитайте комментарии, чтобы убедиться что нет открытого пулреквеста для решения текущей ишью, а также, что никто другой не оставил комментарий, что он работает над этой задачей в последнее время (как правило, 3 дня). Добавьте комментарий, что вы хотели бы заняться решением этой задачи. @@ -174,7 +174,7 @@ SIG Docs совместными усилиями вносит изменения 7. Если ваши изменения одобрены, то рецензент объединяет соответствующий пулреквест. Через несколько минут вы сможете сможете увидеть его в действии на сайте Kubernetes. -Это только один из способов отправить пулреквест. Если вы уже опытный пользователь Git и GitHub, вы можете вносить изменения, используя локальный GUI-клиент или Git из терминала вместо того, чтобы использовать интерфейс GitHub для этого. Некоторые основы использования Git-клиента из командной строки обсуждаются в [продвинутом](/docs/contribute/intermediate/) руководстве участника. +Это только один из способов отправить пулреквест. Если вы уже опытный пользователь Git и GitHub, вы можете вносить изменения, используя локальный GUI-клиент или Git из терминала вместо того, чтобы использовать интерфейс GitHub для этого. Некоторые основы использования Git-клиента из командной строки обсуждаются в руководстве для [продвинутого участника](/ru/docs/contribute/intermediate/). ## Просмотр пулреквестов в документацию diff --git a/content/ru/docs/contribute/style/_index.md b/content/ru/docs/contribute/style/_index.md new file mode 100644 index 0000000000..57686140c2 --- /dev/null +++ b/content/ru/docs/contribute/style/_index.md @@ -0,0 +1,7 @@ +--- +title: Обзор оформления документации +main_menu: true +weight: 80 +--- + +Темы в этом разделе содержат рекомендации по написанию, форматированию и организации контента, а также охватывают настройку Hugo в контексте документации Kubernetes. diff --git a/content/ru/docs/contribute/style/content-guide.md b/content/ru/docs/contribute/style/content-guide.md new file mode 100644 index 0000000000..567e3b6dce --- /dev/null +++ b/content/ru/docs/contribute/style/content-guide.md @@ -0,0 +1,101 @@ +--- +title: Руководство по содержанию документации +linktitle: Руководство по содержанию +content_template: templates/concept +weight: 10 +card: + name: contribute + weight: 20 + title: Руководство по содержанию документации +--- + +{{% capture overview %}} + +Эта страница содержит рекомендации по добавлению контента в документацию Kubernetes. +Если у вас есть вопросы по поводу допустимого контента, обратитесь к каналу #sig-docs в [Slack Kubernetes](http://slack.k8s.io/) и задайте свои вопросы! Поступайте на своё усмотрение и не стесняйтесь вносить изменения в этот документ через пулреквест. + +Для получения дополнительной информации о создании нового контента для документации Kubernetes следуйте инструкциям в [руководстве по оформлению](/ru/docs/contribute/style/style-guide). +{{% /capture %}} + +{{% capture body %}} + +## Участие в контенте + +Документация Kubernetes включает содержимое из оригинального репозитория [kubernetes/website](https://github.com/kubernetes/website). Документация Kubernetes находится в директории `kubernetes/website/content//docs`, большая часть которой относится к [проекту Kubernetes](https://github.com/kubernetes/kubernetes). Документация Kubernetes может также включать содержимое их проектов в GitHub-организациях [kubernetes](https://github.com/kubernetes) и [kubernetes-sigs](https://github.com/kubernetes-sigs), если у этих проектов нет собственной документации. Всегда можно ссылаться на действующие проекты kubernetes, kubernetes-sigs и ({{< glossary_tooltip text="CNCF" term_id="cncf" >}}) в документации Kubernetes, но перелинковка с продуктами определённого разработчика не допускается. Проверьте списки проектов CNCF ([Graduated/Incubating](https://www.cncf.io/projects/), [Sandbox](https://www.cncf.io/sandbox-projects/), [Archived](https://www.cncf.io/archived-projects/)), если вы не уверены в статусе CNCF проекта + +### Контент, полученный из двух источников + +Документация Kubernetes не содержит дублированный контент, полученный из разных мест (так называемый **контент из двумя источниками**). Контент из двух источников требует дублирования работы со стороны мейнтейнеров проекта и к тому же быстро теряет актуальность. +Перед добавлением контента, задайте себе вопрос: + +- Новая информация относится к действующему проекту CNCF ИЛИ проекту в организациях на GitHub kubernetes или kubernetes-sigs? + - Если да, то: + - У этого проекта есть собственная документация? + - если да, то укажите ссылку на документацию проекта в документации Kubernetes + - если нет, добавьте информацию в репозиторий проекта (если это возможно), а затем укажите ссылку на неё в документации Kubernetes + - Если нет, то: + - Остановитесь! + - Добавление информации по продуктам от других разработчиков не допускается + - Не разрешено ссылаться на документацию и сайты сторонних разработчиков. + +### Разрешенная и запрещённая информация + +Есть несколько условий, когда в документации Kubernetes может быть информация, относящиеся не к проектам Kubernetes. +Ниже перечислены основные категории по содержанию проектов, не касающихся к Kubernetes, а также приведены рекомендации о том, что разрешено, а что нет: + +1. Инструкции по установке или эксплуатации Kubernetes, которые не связаны с проектами Kubernetes + - Разрешено: + - Ссылаться на документацию на CNCF-проекта или на проект в GitHub-организациях kubernetes или kubernetes-sigs + - Пример: для установки Kubernetes в процессе обучения нужно обязательно установить и настроить minikube, а также сослаться на соответствующую документацию minikube + - Добавление инструкций для проектов в организации kubernetes или kubernetes-sigs, если по ним нет инструкций + - Пример: добавление инструкций по установке и решению неполадок [kubadm](https://github.com/kubernetes/kubeadm) + - Запрещено: + - Добавление информацию, которая повторяет документацию в другом репозитории + - Примеры: + - Добавление инструкций по установке и настройке minikube; Minikube имеет собственную [документацию](https://minikube.sigs.k8s.io/docs/), которая включают эти инструкции + - Добавление инструкций по установке Docker, CRI-O, containerd и других окружений для выполнения контейнеров в разных операционных системах + - Добавление инструкций по установке Kubernetes в промышленных окружениях, используя разные проекты: + -Kubernetes Rebar Integrated Bootstrap (KRIB) — это проект стороннего разработчика, поэтому все содержимое находится репозитории разработчика. + - У проекта [Kubernetes Operations (kops)](https://github.com/kubernetes/kops) есть инструкции по установке и руководства в GitHub-репозитории. + - У проекта [Kubespray](https://kubespray.io) есть собственная документация + - Добавление руководства, в котором объясняется, как выполнить задачу с использованием продукта определенного разработчика или проекта с открытым исходным кодом, не являющиеся CNCF-проектом или проектом в GitHub-организациях kubernetes или kubnetes-sigs. + - Добавление руководства по использованию CNCF-проекта или проекта в GitHub-организациях kubernetes или kubnetes-sigs, если у проекта есть собственная документация +1. Подробное описание технических аспектов по использованию стороннего проекта (не Kubernetes) или как этот проект разработан + + Добавление такого типа информации в документацию Kubernetes не допускается. +1. Информация стороннему проекту + - Разрешено: + - Добавление краткого введения о CNCF-проекте или проекте в GitHub-организациях kubernetes или kubernetes-sigs; этот абзац может содержать ссылки на проект + - Запрещено: + - Добавление информации по продукту определённого разработчика + - Добавление информации по проекту с открытым исходным кодом, который не является CNCF-проектом или проектом в GitHub-организациях kubernetes или kubnetes-sigs + - Добавление информации, дублирующего документацию из другого проекта, независимо от оригинального репозитория + - Пример: добавление документации для проекта [Kubernetes in Docker (KinD)](https://kind.sigs.k8s.io) в документацию Kubernetes +1. Только ссылки на сторонний проект + - Разрешено: + - Ссылаться на проекты в GitHub-организациях kubernetes и kubernetes-sigs + - Пример: добавление ссылок на [документацию](https://kind.sigs.k8s.io/docs/user/quick-start) проекта Kubernetes in Docker (KinD), который находится в GitHub-организации kubernetes-sigs + - Добавление ссылок на действующие CNCF-проекты + - Пример: добавление ссылок на [документацию](https://prometheus.io/docs/introduction/overview/) проекта Prometheus; Prometheus — это действующий проект CNCF + - Запрещено: + - Ссылаться на продукты стороннего разработчика + - Ссылаться на архивированные проекты CNCF + - Ссылаться на недействующие проекты в организациях GitHub в kubernetes и kubernetes-sigs + - Ссылаться на проекты с открытым исходным кодом, которые не являются проектами CNCF или не находятся в организациях GitHub kubernetes или kubernetes-sigs. +1. Содержание учебных курсов + - Разрешено: + - Ссылаться на независимые от разработчиков учебные курсы Kubernetes, предлагаемыми [CNCF](https://www.cncf.io/), [Linux Foundation](https://www.linuxfoundation.org/) и [Linux Academy](https://linuxacademy.com/) (партнер Linux Foundation) + - Пример: добавление ссылок на курсы Linux Academy, такие как [Kubernetes Quick Start](https://linuxacademy.com/course/kubernetes-quick-start/) в [Kubernetes Security](https://linuxacademy.com/course/kubernetes-security/) + - Запрещено: + - Ссылаться на учебныЕе онлайн-курсы, вне CNCF, Linux Foundation или Linux Academy; документация Kubernetes не содержит ссылок на сторонний контент + - Пример: добавление ссылок на учебные руководства или курсы Kubernetes на Medium, KodeKloud, Udacity, Coursera, learnk8s и т.д. + - Ссылаться на руководства определённых разработчиков вне зависимости от обучающей организации + - Пример: добавление ссылок на такие курсы Linux Academy, как [Google Kubernetes Engine Deep Dive](https://linuxacademy.com/google-cloud-platform/training/course/name/google-kubernetes-engine-deep-dive) and [Amazon EKS Deep Dive](https://linuxacademy.com/course/amazon-eks-deep-dive/) + +Если у вас есть вопросы по поводу допустимого контента, присоединяйтесь к каналу #sig-docs в [Slack Kubernetes](http://slack.k8s.io/)! + +{{% /capture %}} + +{{% capture whatsnext %}} +* Прочитайте [руководство по оформлению](/ru/docs/contribute/style/style-guide). +{{% /capture %}} diff --git a/content/ru/docs/contribute/style/content-organization.md b/content/ru/docs/contribute/style/content-organization.md new file mode 100644 index 0000000000..5c2e00dba6 --- /dev/null +++ b/content/ru/docs/contribute/style/content-organization.md @@ -0,0 +1,131 @@ +--- +title: Организация контента +content_template: templates/concept +weight: 40 +--- + + +{{% capture overview %}} + +Этот сайт использует Hugo. В Hugo [организация контента](https://gohugo.io/content-management/organization/) — основная концепция. + +{{% /capture %}} + +{{% capture body %}} + +{{% note %}} +**Подсказка:** при редактировании контента используйте команду `hugo server --navigateToChanged`, чтобы запустить Hugo. +{{% /note %}} + +## Списки страниц + +### Порядок страницы + +Меню в сайдбаре, каталог страниц документации используют стандартный порядок перечисления Hugo, который сортирует элементы по весу (от 1), дате (начиная с самых новых) и затем по заголовку ссылки. + +Таким образом, если вам нужно поднять страницу или раздел, определите её вес в фронтальной части: + +```yaml +title: Моя страница +weight: 10 +``` + +{{% note %}} +Для значений веса страниц лучше не использовать привычный порядок 1, 2, 3..., а предпочесть другой интервал, например, 10, 20, 30... В будущем это позволит вставить последующие страницы в желаемую позицию. +{{% /note %}} + +### Главное меню документации + +Главное меню `Документация` состоит из разделов по пути `docs/` с установленным флагом `main_menu` в фронтальной части файла раздела `_index.md`: + +```yaml +main_menu: true +``` + +Обратите внимание, что текст ссылки берётся из переменной `linkTitle`, поэтому, если вы хотите, чтобы он отличался от заголовка страницы, измените его в файле: + +```yaml +main_menu: true +title: Название страницы +linkTitle: Название, которое будет использоваться в ссылках +``` + +{{% note %}} +Перечисленные выше переменные должны быть определены для каждого перевода. Если вы не видите созданный вами раздел в меню, скорее всего, это может быть связано с тем, что Hugo не определил его как раздел. Создайте файл `_index.md` в директории раздела. +{{% /note %}} + +### Документация в боковом меню + +Меню сайдбара в документации собирается из _текущего дерева разделов_ по пути `docs/`. + +Оно отобразит все разделы и их страницы. + +Если вы хотите, чтобы раздел или страница не отображались в меню, установите для флага `toc_hide` значение `true` в фронтальной части файла: + +```yaml +toc_hide: true +``` + +При переходе к непустому разделу будет отображаться указанный раздел или страница (например, `_index.md`). В противном случае выводиться первая страница в этом разделе. + +### Каталог документации + +Каталог страниц на главной странице документации сгенерирован с учётом всех разделов и страниц документации. + +Если вы хотите скрыть раздел или страницу, установите для флага `toc_hide` значение `true` в фронтальной части файла: + +```yaml +toc_hide: true +``` + +### Главное меню + +Ссылки сайта в верхнем правом меню, а также в футере, создаются посредством сканирования страниц. Этот процесс гарантирует, что страница действительно существует на сайте. Поэтому, если раздела `case-studies` на сайте (или в переводе) не существует, ссылка не появится. + +## Пакеты страниц + +В дополнение к отдельным страницам с контентом (Markdown-файлам), Hugo поддерживает [пакеты страниц (page bundles)](https://gohugo.io/content-management/page-bundles/). + +К примеру, [пользовательские макрокоды Hugo](/docs/contribute/style/hugo-shortcodes/) — узел пакета (`leaf bundle`). Все, что находится в директории, включая `index.md`, будет частью пакета. Сюда также относятся относительные ссылки на страницы, изображения, которые могут быть обработаны и т.д.: + +```bash +en/docs/home/contribute/includes +├── example1.md +├── example2.md +├── index.md +└── podtemplate.json +``` + +Другой распространённый пример — это пакет `includes`. Он устанавливает переменную `headless: true`, которая означает, что файл не будет доступен по собственному URL-адресу. Вместо этого он будет использоваться в других страницах как вставляемый файл. + +```bash +en/includes +├── default-storage-class-prereqs.md +├── federated-task-tutorial-prereqs.md +├── index.md +├── partner-script.js +├── partner-style.css +├── task-tutorial-prereqs.md +├── user-guide-content-moved.md +└── user-guide-migration-notice.md +``` + +Необходимо отметить следующие особенности файлов в пакетах: + +* Для переведенных пакетов любые отсутствующие файлы будут унаследованы от файлов на оригинальном (английском) языке. Это позволяет избежать дублирования. +* Все файлы в пакете — в Hugo называются ресурсы (`Resources`), в которых вы можете определить метаданные, зависимые от языка, например, параметры и заголовок, даже если они не поддерживают в фронтальной части (YAML-файлы и т.д.). Смотрите [Метаданные ресурсов страницы](https://gohugo.io/content-management/page-resources/#page-resources-metadata) для получения дополнительной информации. +* Значение, которое вы получаете через `.RelPermalink` в `Resource` будет отличаться в зависимости от страницы. Смотрите [Постоянные ссылки](https://gohugo.io/content-management/urls/#permalinks) для получения дополнительной информации. + +## Стилизация + +Исходные файлы стилей в формате [SASS](https://sass-lang.com/) находятся в директории `assets/sass` и автоматически собираются Hugo. + +{{% /capture %}} + +{{% capture whatsnext %}} + +* Подробнее про [пользовательские макрокоды Hugo](/ru/docs/contribute/style/hugo-shortcodes/) +* Подробнее про [оформление документации](/ru/docs/contribute/style/style-guide) +* Подробнее про [содержание документации](/ru/docs/contribute/style/content-guide) + +{{% /capture %}} diff --git a/content/ru/docs/contribute/style/hugo-shortcodes/example1.md b/content/ru/docs/contribute/style/hugo-shortcodes/example1.md new file mode 100644 index 0000000000..30ffcf0235 --- /dev/null +++ b/content/ru/docs/contribute/style/hugo-shortcodes/example1.md @@ -0,0 +1,9 @@ +--- +title: Пример #1 +--- + +Это **пример** содержимого в файле внутри пакета узла **includes**. + +{{< note >}} +Подключаемые файлы также могут содержать макрокоды. +{{< /note >}} \ No newline at end of file diff --git a/content/ru/docs/contribute/style/hugo-shortcodes/example2.md b/content/ru/docs/contribute/style/hugo-shortcodes/example2.md new file mode 100644 index 0000000000..68a9730617 --- /dev/null +++ b/content/ru/docs/contribute/style/hugo-shortcodes/example2.md @@ -0,0 +1,7 @@ +--- +title: Пример #1 +--- + +Это другой **пример** содержимого в файле внутри пакета узла **includes**. + + diff --git a/content/ru/docs/contribute/style/hugo-shortcodes/index.md b/content/ru/docs/contribute/style/hugo-shortcodes/index.md new file mode 100644 index 0000000000..b77cc77ec1 --- /dev/null +++ b/content/ru/docs/contribute/style/hugo-shortcodes/index.md @@ -0,0 +1,245 @@ +--- +approvers: +- chenopis +title: Пользовательские макрокоды Hugo +content_template: templates/concept +--- + +{{% capture overview %}} +На этой странице объясняются пользовательские макрокоды Hugo, которые можно использовать в Markdown-файлах документации Kubernetes. + +Узнать подробнее про макрокоды можно в [документации Hugo](https://gohugo.io/content-management/shortcodes). +{{% /capture %}} + +{{% capture body %}} + +## Состояние функциональности + +В Markdown странице (файл с расширением `.md`) вы можете добавить макрокод, чтобы отобразить версию и состояние документированной функциональной возможности. + +### Демонстрация состояния функциональности + +Ниже показан фрагмент кода для вывода состояния функциональности, который сообщает о функциональности в стабильной версии Kubernetes 1.10. + +``` +{{}} +``` + +Результат: + +{{< feature-state for_k8s_version="v1.10" state="stable" >}} + +Допустимые значения для `state`: + +* alpha +* beta +* deprecated +* stable + +### Код состояния функциональности + +По умолчанию отображается версия Kubernetes, соответствующая версии страницы или сайта. Это значение можно переопределить, передав параметр макрокода for_k8s_version. + +``` +{{}} +``` + +Результат: + +{{< feature-state for_k8s_version="v1.10" state="stable" >}} + +#### Функциональность в альфа-версии + +``` +{{}} +``` + +Результат: + +{{< feature-state state="alpha" >}} + +#### Функциональность в бета-версии + +``` +{{}} +``` + +Результат: + +{{< feature-state state="beta" >}} + +#### Функциональность в стабильной версии + +``` +{{}} +``` + +Результат: + +{{< feature-state state="stable" >}} + +#### Устаревшая функциональность + +``` +{{}} +``` + +Результат: + +{{< feature-state state="deprecated" >}} + +## Глоссарий + +Вы можете сослаться на термины из [глоссария](/docs/reference/glossary/) в виде всплывающей (при наведении мыши) подсказки, что удобно при чтении документации через интернет. + +Исходные файлы терминов глоссария хранятся в отдельной директории по URL-адресу [https://github.com/kubernetes/website/tree/master/content/en/docs/reference/glossary](https://github.com/kubernetes/website/tree/master/content/en/docs/reference/glossary). + +### Демонстрация глоссария + +Например, следующий фрагмент кода в Markdown будет отображен в виде всплывающей подсказки — {{< glossary_tooltip text="cluster" term_id="cluster" >}}: + +```liquid +{{}} +``` + +## Заголовки таблиц + +Для улучшения доступности таблиц для программ для чтения с экрана, добавьте заголовок к таблице. Чтобы добавить [заголовок](https://www.w3schools.com/tags/tag_caption.asp) таблицы, поместите таблицу в макрокод `table` и определите значение заголовка в параметре` caption`. + +{{< note >}} +Заголовки таблиц предназначены только для программ чтения с экрана, поэтому в браузере они не будут отображаться. +{{< /note >}} + +Пример: + +```go-html-template +{{}} +Параметр | Описание | Значение по умолчанию +:---------|:------------|:------- +`timeout` | Тайм-аут для запросов | `30s` +`logLevel` | Уровень логирования | `INFO` +{{< /table */>}} +``` + +Результат: + +{{}} +Параметр | Описание | Значение по умолчанию +:---------|:------------|:------- +`timeout` | Тайм-аут для запросов | `30s` +`logLevel` | Уровень логирования | `INFO` +{{< /table >}} + +Если вы изучите HTML-код таблицы, вы заметите следующий ниже элемент сразу после открывающего элемента ``: + +```html + +``` + +## Вкладки + +Страница в формате Markdown (файл с расширением `.md`) на этом сайте может содержать набор вкладок для отображения нескольких разновидностей определённого решения. + +Макрокод `tabs` принимает следующие параметры: + +* `name`: имя, отображаемое на вкладке. +* `codelang`: если вы указываете встроенный контент для макрокода `tab`, вы можете сообщить Hugo, какой язык использовать для подсветки синтаксиса. +* `include`: включаемый файл в вкладку. Если вкладка находится в [узле пакета (leaf bundle)](https://gohugo.io/content-management/page-bundles/#leaf-bundles) Hugo, то файл (может быть любым MIME-типом, который поддерживает Hugo) ищется в самом пакете. Если нет, то включаемое содержимое ищется относительно текущей страницы. Обратите внимание, что при использовании `include` вам следует использовать самозакрывающийся синтаксис. Например, {{}}. Язык может быть указан в `codelang`, в противном случае язык определяется из имени файла. +* Если содержимое вкладки это Markdown, вам нужно использовать символ `%`. Например, `{{%/* tab name="Вкладка 1" %}}This is **markdown**{{% /tab */%}}` +* Вы можете совместно использовать перечисленные выше параметры. +Ниже приведена демонстрация шорткода вкладок. + +Ниже приведены примеры вкладок. + +{{< note >}} +**Имя** вкладки в элементе `tabs` должно быть уникальным на странице. +{{< /note >}} + +### Демонстрация вкладок: подсветка синтаксиса в блоках кода + +```go-text-template +{{}} +{{{< tab name="Вкладка 1" codelang="bash" >}} +echo "Это вкладка 1." +{{< /tab >}} +{{< tab name="Вкладка 2" codelang="go" >}} +println "Это вкладка 2." +{{< /tab >}}} +{{< /tabs */>}} +``` + +Результат: + +{{< tabs name="tab_with_code" >}} +{{< tab name="Вкладка 1" codelang="bash" >}} +echo "Это вкладка 1." +{{< /tab >}} +{{< tab name="Вкладка 2" codelang="go" >}} +println "Это вкладка 2." +{{< /tab >}} +{{< /tabs >}} + +### Демонстрация вкладок: встроенный Markdown и HTML + +```go-html-template +{{}} +{{% tab name="Markdown" %}} +Это **разметка Markdown.** +{{< note >}} +Также можно использовать макрокоды. +{{< /note >}} +{{% /tab %}} +{{< tab name="HTML" >}} +
    +

    Обычный HTML

    +

    Это обычный HTML.

    +
    +{{< /tab >}} +{{< /tabs */>}} +``` + +Результат: + +{{< tabs name="tab_with_md" >}} +{{% tab name="Markdown" %}} +Это **разметка Markdown.** + +{{< note >}} +Также можно использовать макрокоды. +{{< /note >}} + +{{% /tab %}} +{{< tab name="HTML" >}} +
    +

    Обычный HTML

    +

    Это обычный HTML.

    +
    +{{< /tab >}} +{{< /tabs >}} + +### Демонстрация вкладок: включение файлов + +```go-text-template +{{}} +{{< tab name="Content File #1" include="example1" />}} +{{< tab name="Content File #2" include="example2" />}} +{{< tab name="JSON File" include="podtemplate" />}} +{{< /tabs */>}} +``` + +Результат: + +{{< tabs name="tab_with_file_include" >}} +{{< tab name="Content File #1" include="example1" />}} +{{< tab name="Content File #2" include="example2" />}} +{{< tab name="JSON File" include="podtemplate" />}} +{{< /tabs >}} + +{{% /capture %}} + +{{% capture whatsnext %}} +* Подробнее про [Hugo](https://gohugo.io/). +* Подробнее про [написание новой темы](/ru/docs/contribute/style/write-new-topic/). +* Подробнее про [использование шаблонов страниц](/ru/docs/contribute/style/page-templates/). +* Подробнее про [создание пулреквеста](/ru/docs/contribute/start/#отправка-пулреквеста). +{{% /capture %}} \ No newline at end of file diff --git a/content/ru/docs/contribute/style/hugo-shortcodes/podtemplate.json b/content/ru/docs/contribute/style/hugo-shortcodes/podtemplate.json new file mode 100644 index 0000000000..bd4327414a --- /dev/null +++ b/content/ru/docs/contribute/style/hugo-shortcodes/podtemplate.json @@ -0,0 +1,22 @@ + { + "apiVersion": "v1", + "kind": "PodTemplate", + "metadata": { + "name": "nginx" + }, + "template": { + "metadata": { + "labels": { + "name": "nginx" + }, + "generateName": "nginx-" + }, + "spec": { + "containers": [{ + "name": "nginx", + "image": "dockerfile/nginx", + "ports": [{"containerPort": 80}] + }] + } + } + } diff --git a/content/ru/docs/contribute/style/page-templates.md b/content/ru/docs/contribute/style/page-templates.md new file mode 100644 index 0000000000..f49307b414 --- /dev/null +++ b/content/ru/docs/contribute/style/page-templates.md @@ -0,0 +1,186 @@ +--- +title: Использование шаблонов страниц +content_template: templates/concept +weight: 30 +card: + name: contribute + weight: 30 +--- + +{{% capture overview %}} +При добавлении новых тем воспользуйтесь одним из перечисленных ниже шаблонов. +Это регламентирует пользовательское восприятие определённой страницы. + +Шаблоны страниц находятся в директории [`layouts/partials/templates`](https://git.k8s.io/website/layouts/partials/templates) репозитория [`kubernetes/website`](https://github.com/kubernetes/website). + +{{< note >}} +Каждая новая тема должна использовать шаблон. Если вы не уверены, какой шаблон использовать для новой темы, начните с [шаблона концепции](#шаблон-концепции). +{{< /note >}} + +{{% /capture %}} + + +{{% capture body %}} + +## Шаблон концепции + +Страница концепции объясняет некоторые аспекты Kubernetes. Например, страницы концепции может описывать объект Deployment в Kubernetes и разъяснить какую роль он играет после развертывания, масштабирования и обновления приложения. Как правило, страницы концепций не включают последовательности шагов, и вместо этого содержат ссылки на задачи или руководства. + +Для написания новой страницы концепции в директории `/content/en/docs/concepts` создайте поддиректорию с Markdown-файлом со следующим требованиями: + +- Во фронтальной части YAML этой страницы определите поле `content_template: templates/concept`. +- В теле страницы укажите переменные `capture` и любые другие, которые вы хотите включить: + + | Переменная | Обязательна? | + |------------|--------------| + | overview | да | + | body | да | + | whatsnext | нет | + + + Тело страницы будет выглядеть следующим образом (удалите все необязательные capture-блоки, если они вам не понадобятся): + + ``` + {{%/* capture overview */%}} + + {{%/* /capture */%}} + + {{%/* capture body */%}} + + {{%/* /capture */%}} + + {{%/* capture whatsnext */%}} + + {{%/* /capture */%}} + ``` + +- Заполните каждый раздел информацией. Следуйте этим рекомендациям: + - Структурируйте контент с помощью заголовков H2 и H3. + - В блоке `overview` одним абзацем сформируйте контекст темы. + - В блоке `body` объясните суть концепции. + - В блоке `whatsnext` сформируйте ненумерованный список тем (до 5), к которым нужно обратиться, чтобы получить дополнительную информацию о концепции. + +[Annotations](/docs/concepts/overview/working-with-objects/annotations/) — это готовый пример шаблона концепции. Кстати, текущая страница использует шаблон концепции. + +## Шаблон задачи + +На странице задачи показывается, как сделать что-то одно конкретное, главным образом с помощью короткой последовательности шагов. В страницах задач очень короткое объяснение, хотя они часто ссылаются на концептуальные темы, где уже можно найти соответствующую справочную информацию и ресурсы. + +Для написания новой страницы задачи в директории `/content/en/docs/tasks` создайте поддиректорию с Markdown-файлом со следующим требованиями: + +- Во фронтальной части YAML этой страницы определите поле `content_template: templates/task`. +- В теле страницы укажите переменные `capture` и любые другие, которые вы хотите включить: + + | Переменная | Обязательна? | + |------------|--------------| + | overview | да | + | prerequisites | да | + | steps | нет | + | discussion | нет | + | whatsnext | нет | + + + Тело страницы будет выглядеть следующим образом (удалите все необязательные capture-блоки, если они вам не нужны): + + ``` + {{%/* capture overview */%}} + + {{%/* /capture */%}} + + {{%/* capture prerequisites */%}} + + {{}} {{}} + + {{%/* /capture */%}} + + {{%/* capture steps */%}} + + {{%/* /capture */%}} + + {{%/* capture discussion */%}} + + {{%/* /capture */%}} + + {{%/* capture whatsnext */%}} + + {{%/* /capture */%}} + ``` + +- Заполните каждый блок информацией. Следуйте этим рекомендациям: + - Используйте по минимуму заголовков H2 (с двумя ведущими символами `#`). У самих разделов заголовок формируется автоматически по заданному шаблону. + - В блоке `overview` обозначьте контекст для всей темы. + - В блоке `prerequisites` используйте ненумерованные списки, где это возможно. Добавьте дополнительные предварительные условия ниже `include`. Предварительные условия по умолчанию содержат пункт про наличие работающего кластера. + - В блоке `steps` используйте нумерованные списки. + - В блоке `discussion` подробно распишите информацию, описанную в разделе `steps`. + - В блоке `whatsnext` сформируйте ненумерованный список тем (до 5), которые могут быть интересны читателю в качестве дополнительного чтения. + +Пример готовой темы, в которой используется шаблон задачи — [Using an HTTP proxy to access the Kubernetes API](/docs/tasks/access-kubernetes-api/http-proxy-access-api). + +## Шаблон руководства + +На странице руководства показывается, как выполнить что-то более крупнее одной-единственной задачи. Как правило, страницы руководства поделена на несколько разделов, в каждом из которых есть последовательность шагов. Например, руководство может включать анализ примера кода, демонстрирующий определенную возможность Kubernetes. Руководства могут содержать поверхностные объяснения и одновременно включать ссылки на соответствующие концептуальные темы для получения углубленных знаний. + +Для написания новой страницы задачи в директории `/content/en/docs/tutorials` создайте поддиректорию с Markdown-файлом со следующим требованиями: + +- Во фронтальной части YAML этой страницы определите поле `content_template: templates/tutorial`. +- В теле страницы укажите переменные `capture` и любые другие, которые вы хотите включить: + + | Переменная | Обязательна? | + |------------|--------------| + | overview | да | + | prerequisites | да | + | objectives | да | + | lessoncontent | да | + | cleanup | нет | + | whatsnext | нет | + + Тело страницы будет выглядеть следующим образом (удалите все необязательные capture-блоки, если они вам не понадобятся): + + ``` + {{%/* capture overview */%}} + + {{%/* /capture */%}} + + {{%/* capture prerequisites */%}} + + {{}} {{}} + + {{%/* /capture */%}} + + {{%/* capture objectives */%}} + + {{%/* /capture */%}} + + {{%/* capture lessoncontent */%}} + + {{%/* /capture */%}} + + {{%/* capture cleanup */%}} + + {{%/* /capture */%}} + + {{%/* capture whatsnext */%}} + + {{%/* /capture */%}} + ``` + +- Заполните каждый блок информацией. Следуйте этим рекомендациям: + - Используйте по минимуму заголовков H2 (с двумя ведущими символами `#`). У самих разделов заголовок формируется автоматически по заданному шаблону. + - В блоке `overview` обозначьте контекст для всей темы. + - В блоке `prerequisites` используйте ненумерованные списки, где это возможно. Добавьте дополнительные предварительные условия ниже `include`. Предварительные условия по умолчанию содержат пункт про наличие работающего кластера. + - В блоке `objectives` используйте ненумерованные списки. + - В блоке `lessoncontent` целесообразно используйте совместно нумерованные списки и повествовательное содержание. + - В блоке `cleanup` используйте нумерованные списки для описания шагов для очистки состояния кластера после выполнения задачи. + - В блоке `whatsnext` сформируйте ненумерованный список тем (до 5), которые могут быть интересны читателю в качестве дополнительного чтения. + +Пример завершенной темы, в которой используется шаблон руководства — [Running a Stateless Application Using a Deployment](/docs/tutorials/stateless-application/run-stateless-application-deployment/). + +{{% /capture %}} + +{{% capture whatsnext %}} + +- Подробнее про [оформление документации](/ru/docs/contribute/style/style-guide/) +- Подробнее про [содержание документации](/ru/docs/contribute/style/content-guide/) +- Подробнее про [организацию контента](/ru/docs/contribute/style/content-organization/) + +{{% /capture %}} diff --git a/content/ru/docs/contribute/style/style-guide.md b/content/ru/docs/contribute/style/style-guide.md new file mode 100644 index 0000000000..612111c673 --- /dev/null +++ b/content/ru/docs/contribute/style/style-guide.md @@ -0,0 +1,570 @@ +--- +title: Руководство по оформлению документации +linktitle: Руководство по оформлению +content_template: templates/concept +weight: 10 +card: + name: contribute + weight: 20 + title: Руководство по оформлению документации +--- + +{{% capture overview %}} +На этой странице вы найдёте рекомендации по оформлению написания документации Kubernetes. Это рекомендации, а не правила. Используйте здравый смысл и не стесняйтесь предлагать изменения в этот документ в виде пулреквеста. + +Для получения подробной информации о создании нового контента в документацию Kubernetes посмотрите [руководство по контенту документации](/ru/docs/contribute/style/content-guide/), а также следуйте инструкциям по [использованию шаблонов страниц](/ru/docs/contribute/style/page-templates/) и [открытию пулревеста в документацию](/ru/docs/contribute/start/#улучшение-существующего-текста). + +{{% /capture %}} + +{{% capture body %}} + +{{< note >}} +В документации Kubernetes используется [Blackfriday Markdown Renderer](https://github.com/russross/blackfriday) вместе с несколькими [макрокодами Hugo](/docs/home/contribute/includes/) для добавления поддержки записей глоссария, вкладок и отображения состояний функциональностей. +{{< /note >}} + +## Язык + +Документация Kubernetes была переведена на несколько языков (см. [README-файлы локализаций](https://github.com/kubernetes/website/blob/master/README.md#localization-readmemds)). + +Процесс локализации документации на другие языки описан в [соответствующей странице по локализации](/ru/docs/contribute/localization/). + +## Правила форматирования документации + +### Используйте верблюжью нотацию для написания объектов API + +Когда вы указываете имя API-объекта, используйте те же самые прописные и строчные буквы так, как они записаны в имени объекта. Как правило, имена объектов API написаны с использованием [верблюжьей нотации](https://ru.wikipedia.org/wiki/Camel_case). + +Не разделяйте имя объекта API на отдельные слова. Например, пишите PodTemplateList, а не Pod Template List. + +Указывая имена API-объектов, не добавляйте к ним слово "объект", за исключением случаев, когда это только ухудшает читаемость. + +{{< table caption = "Можно делать и нельзя - Объекты API" >}} +Можно | Нельзя +:--| :----- +В Pod два контейнера. | В поде два контейнера. +Deployment отвечает за ... | Объект Deployment отвечает за ... +PodList — это список Pod. | Pod List — это список подов. +Два ContainerPorts ... | Два объекта ContainerPort ... +Два объекта ContainerStateTerminated ... | Два ContainerStateTerminated ... +{{< /table >}} + + +### Используйте угловые скобки для заполнителей + +Используйте угловые скобки для заполнителей. Сообщите читателю, что означает заполнитель. + +1. Отобразить информацию о Pod: + + kubectl describe pod -n + + Если пространство имён пода равняется `default`, вы можете опустить параметр '-n'. + +### Используйте полужирное начертание для элементов пользовательского интерфейса + +{{< table caption = "Можно делать и нельзя - Элементы интерфейса в полужирном начертании" >}} +Можно | Нельзя +:--| :----- +Нажмите на **Fork**. | Нажмите на "Fork". +Выберите **Other**. | Выберите "Other". +{{< /table >}} + +### Используйте курсивное начертание для определения или включения новых терминов + +{{< table caption = "Можно делать и нельзя - Используйте курсивное начертание для новых терминов" >}} +Можно | Нельзя +:--| :----- +_Кластер_ — это набор узлов ... | "Кластер" — это набор узлов ... +Эти компоненты формируют _панель управления_. | Эти компоненты формируют **панель управления**. +{{< /table >}} + +### Оформляйте как код имена файлов, директории и пути + +{{< table caption = "Можно делать и нельзя - Оформляйте как код имена файлов, директории и пути" >}} +Можно | Нельзя +:--| :----- +Откройте файл `envars.yaml`. | Откройте файл envars.yaml. +Перейдите в директорию `/docs/tutorials`. | Перейдите в директорию /docs/tutorials. +Откройте файл `/_data/concepts.yaml` file. | Откройте файл /_data/concepts.yaml. +{{< /table >}} + +### Используйте международные правила для пунктуации внутри кавычек + +{{< table caption = "Можно делать и нельзя - Используйте международные правила для пунктуации внутри кавычек" >}} +Можно | Нельзя +:--| :----- +события записываются с соответствующей "стадией". | события записываются с соответствующей "стадией." +Копия называется "fork". | Копия называется "fork." +{{< /table >}} + +## Форматирование с использованием однострочного кода + +### Используйте оформление кода для встроенного кода и команд + +Для однострочного (встроенного) блока кода в HTML-документе используйте тег ``. В файле Markdown используйте обратную кавычку (`). + +{{< table caption = "Можно делать и нельзя - Use code style for inline code and commands" >}} +Можно | Нельзя +:--| :----- +Команда `kubectl run` создает Deployment. | Команда "kubectl run" создает Deployment. +Для декларативного управления используйте `kubectl apply`. | Для декларативного управления используйте "kubectl apply". +Заключите примеры кода в тройные обратные кавычки. `(```)` | Заключите примеры кода с использованием любого другого синтаксиса. +Используйте одинарные обратные кавычки для выделения встроенного кода. Например, `var example = true`. | Используйте две звездочки (**) или подчёркивание (_) для выделения встроенного кода. Например, **var example = true**. +Используйте тройные обратные кавычки до и после многострочного блока кода для отдельных блоков кода. | Используйте многострочные блоки кода для создания диаграмм, блок-схем или т.д. +Используйте понятные имена переменных с соответствующим контекстом. | Используйте имена переменных, такие как 'foo', 'bar' и 'baz', которые не имеют смысла и которым не хватает контекста. +Удаляйте завершающие пробелы в коде. | Добавляйте конечные пробелы в код там, где они необходимо, поскольку программа для чтения с экрана также будет зачитывать пробелы. +{{< /table >}} + +{{< note >}} +На сайте включена подсветка синтаксиса для примеров кода, хотя указывать язык необязательно. Подсветка синтаксиса в блоке кода должна соответствовать [рекомендациям по контрастности](https://www.w3.org/WAI/WCAG21/quickref/?versions=2.0&showtechniques=141%2C143#contrast-minimum). +{{< /note >}} + +### Имена полей объектов и пространства имён оформляйте как код + +{{< table caption = "Можно делать и нельзя - Имена полей объектов и пространства имён оформляйте как код" >}} +Можно | Нельзя +:--| :----- +Задайте значение для поля `replicas` в конфигурационном файле. | Задайте значение для поля "replicas" в конфигурационном файле. +Значением поля `exec` является объект ExecAction. | Значением поля "exec" является объект ExecAction. +Запустите процесс как Daemonset в пространстве имен `kube-system`. | Запустите процесс как Daemonset в пространстве имен kube-system. +{{< /table >}} + +### Имена компонентов и командного инструмента оформляйте как код + +{{< table caption = "Можно делать и нельзя - Имена компонентов и командного инструмента оформляйте как код" >}} +Можно | Нельзя +:--| :----- +kubelet сохраняет стабильность узла. | `kubelet` сохраняет стабильность узла. +`kubectl` обрабатывает поиск и аутентификацию на сервере API. | kubectl обрабатывает поиск и аутентификацию на apiserver. +Запустите процесс с использованием сертификата `kube-apiserver --client-ca-file=FILENAME`. | Запустите процесс с использованием сертификата kube-apiserver --client-ca-file=FILENAME. +{{< /table >}} + +### Начинайте предложение с имени инструмента или компонента + +{{< table caption = "Можно делать и нельзя - Начинайте предложение с имени инструмента или компонента" >}} +Можно | Нельзя +:--| :----- +The `kubeadm` tool bootstraps and provisions machines in a cluster. | `kubeadm` tool bootstraps and provisions machines in a cluster. +The kube-scheduler is the default scheduler for Kubernetes. | kube-scheduler is the default scheduler for Kubernetes. +{{< /table >}} + +### Используйте общее описание вместо имени компонента + +{{< table caption = "Можно делать и нельзя - Используйте общее описание вместо имени компонента" >}} +Можно | Нельзя +:--| :----- +Сервер Kubernetes API следует спецификации OpenAPI. | apiserver следует спецификации OpenAPI. +Агрегированные API-интерфейсы — вспомогательные API-серверы. | Агрегированные API-интерфейсы — вспомогательные APIServers. +{{< /table >}} + +### Cтроковые и целочисленные значения полей пишите в обычном стиле + +Для значений полей типа string или integer используйте обычный стиль без кавычек. + +{{< table caption = "Можно делать и нельзя - Cтроковые и целочисленные значения полей пишите в обычном стиле" >}} +Можно | Нельзя +:--| :----- +Задайте значение для поля `imagePullPolicy` как Always. | Задайте значение для поля `imagePullPolicy` как "Always". +Задайте значение для поля `image` как nginx:1.8. | Задайте значение для поля`image` как `nginx:1.8`. +Задайте значение для поля `replicas` как 2. | Задайте значение для поля `replicas` как `2`. +{{< /table >}} + + +## Форматирование фрагментов кода + +### Не добавляйте символ приглашения командной строки + +{{< table caption = "Можно делать и нельзя - Не добавляйте символ приглашения командной строки" >}} +Можно | Нельзя +:--| :----- +kubectl get pods | $ kubectl get pods +{{< /table >}} + + +### Отделяйте команды от вывода + +Убедитесь, что Pod работает на выбранном вами узле: + + kubectl get pods --output=wide + +Вывод будет примерно таким: + + NAME READY STATUS RESTARTS AGE IP NODE + nginx 1/1 Running 0 13s 10.200.0.4 worker0 + +### Версионирование примеров Kubernetes + +Примеры кода и примеры конфигурации, которые включают информацию о версии, должны согласовываться с относящемуся к нему тексту. + +Если информация зависит от версии, необходимо определить версию Kubernetes в секции `prerequisites` [шаблона задачи](/ru/docs/contribute/style/page-templates/#шаблон-задачи) или [шаблона руководства](/ru/docs/contribute/style/page-templates/#шаблон-руководства). После сохранения страницы секция `prerequisites` отобразится в отдельном блоке с заголовком **Подготовка к работе**. + +Для указания версии Kubernetes для страницы задачи или руководства в фронтальную часть файла добавьте поле `min-kubernetes-server-version`. + +Если YAML-пример определён в отдельном файле, поищите и просмотрите темы, которые ссылаются на него. +Убедитесь, что темы с подключённым YAML-файлом содержат соответствующую информацию о версии. +Если ни одна из тем не использует какой-либо YAML-файл подумайте над тем, чтобы удалить его вместо того, чтобы обновления. + +Например, если вы пишете руководство, предназначенное для использования с версией Kubernetes 1.8, фронтальная часть вашего Markdown-файла должен выглядеть примерно так: + +```yaml +--- +title: +min-kubernetes-server-version: v1.8 +--- +``` + +В примерах кода и конфигурации не добавляйте комментарии про альтернативные версии. +Убедитесь в том, чтобы в комментариях ваших примеров не содержались некорректные сведения, такие как ниже: + +```yaml +apiVersion: v1 # в более ранних версиях... +kind: Pod +... +``` + +## Словарь Kubernetes.io + +Список специфичных для Kubernetes терминов и слов, которые будут регулярно встречаться по всему сайту. + +{{< table caption = "Словарь Kubernetes.io" >}} +Термин | Пример использования +:--- | :---- +Kubernetes | Kubernetes всегда должен начинаться с заглавной буквы. +Docker | Docker всегда должен начинаться с заглавной буквы. +SIG Docs | SIG Docs, а не SIG-DOCS или другие варианты. +On-premises | On-premises or On-prem rather than On-premise or other variations. +{{< /table >}} + +## Макрокоды + +[Макрокоды Hugo](https://gohugo.io/content-management/shortcodes) помогают создавать разного рода обращений к читателю. Наша документация поддерживает три разных макрокода для этого: **примечание** {{}}, **предостережение** {{}} и **предупреждение** {{}}. + +1. Заключите текст в открывающий и закрывающий макрокод. + +2. Используйте следующий синтаксис для определения стиля: + + ``` + {{}} + Вам не нужно указывать надпись; макрокод автоматически добавит её. (Примечание:, Предостережение:, и т.д.) + {{}} + ``` + +Результат: + +{{< note >}} +Надпись блока будет такой же, как и имя тега. +{{< /note >}} + +### Примечание + +Используйте {{}} для выделения подсказки или части информации, которая может быть полезна для ознакомления. + +Например: + +``` +{{}} +Вы _также_ можете использовать Markdown внутри этих выносок. +{{}} +``` + +Результат: + +{{< note >}} +Вы _также_ можете использовать Markdown внутри этих выносок. +{{< /note >}} + +Вы можете использовать {{}} в списке: + +``` +1. Используйте макрокод примечания в списке + +1. Второй пункт с добавленным блоком примечания + + {{}} + Макрокоды предупреждения, предостережения и примечания, добавленные в списки, должны содержать отступ в четыре пробела. Смотрите раздел [Распространённые проблемы с шорткодами](#распространённые-проблемы-с-шорткодами). + {{}} + +1. Третий пункт в списке + +1. Четвертый пункт в списке +``` + +Результат: + +1. Используйте макрокод примечания в списке + +1. Второй пункт с добавленным блоком примечания + + {{< note >}} + Макрокоды предупреждения, предостережения и примечания, добавленные в списки, должны содержать отступ в четыре пробела. Смотрите раздел [Распространённые проблемы с шорткодами](#распространённые-проблемы-с-шорткодами). + {{< /note >}} + +1. Третий пункт в списке + +1. Четвертый пункт в списке + +### Предостережение + +Используйте {{}}, чтобы обратить внимание к важной информации, которая поможет избежать подводных камней. + +Например: + +``` +{{}} +Оформление выноски применяется только к строке, следующей после тега выше. +{{}} +``` + +Результат: + +{{< caution >}} +Оформление выноски применяется только к строке, следующей после тега выше. +{{< /caution >}} + +### Предупреждение + +Используйте {{}} для обозначения предупреждающей информации или такой, которую чрезвычайно важно соблюдать. + +Например: + +``` +{{}} +Острожно. +{{}} +``` + +Результат: + +{{< warning >}} +Острожно. +{{< /warning >}} + +### Встраиваемая среда выполнения Katacoda + +С помощью этой кнопки пользователи могут запустить Minikube в своём браузере с помощью [терминала Katacoda](https://www.katacoda.com/embed/panel). +Таким образом снижается порог входа, позволяя пользователям попробовать Minikube с помощью одного щелчка мыши, вместо того, чтобы устанавливать Minikube и Kubectl локально. + +Встроенная среда выполнения сконфигурирована для выполнения команды `minikube start` и позволяет пользователям пройти руководство в той же самой вкладке, что и документация. + +{{< caution >}} +Сессия ограничена 15 минутами. +{{< /caution >}} + +Например: + +``` +{{}} +``` + +Результат: + +{{< kat-button >}} + +## Распространённые проблемы с шорткодами + +### Упорядоченные списки + +Макрокоды сбросят нумерацию в нумерованных списках, если вы не добавите отступ в четыре пробела перед уведомлением и тегом. + +Например: + + 1. Разогреть духовку до 350˚F + + 1. Подготовить тесто и вылить её в формочку для выпечки. + {{}}Для лучшего результата смажьте формочку.{{}} + + 1. Выпекать 20-25 minutes или пока тесто не зарумянится. + +Результат: + +1. Разогреть духовку до 350˚F + +1. Подготовить тесто и вылить её в формочку для выпечки. + + {{< note >}}Для лучшего результата смажьте формочку.{{< /note >}} + +1. Выпекать 20-25 minutes или пока тесто не зарумянится. + +### Выражения для вставок + +Макрокоды внутри include-выражений нарушит процесс сборки. Поэтому они должны быть вставлены в родительский документ до и после вызова include. Например: + +``` +{{}} +{{}} +{{}} +``` + + +## Элементы Markdown + +### Переносы строк +Добавляйте одну новую строку для разделения содержимого таких блоков, как заголовки, списки, изображения, многострочный код и т.д. Исключение составляют заголовки второго уровня, которые должны быть разделены двумя переводами строки. Заголовки второго уровня следуют за первым уровнем (или названием страницы). Две пустые строки помогает лучше наглядно представить общую структуру содержимого в редакторе кода. + +### Заголовки +Люди, просматривающие документацию, могут использовать программу чтения с экрана или другую вспомогательную технологию (Assistive technologies, AT). [Программы чтения с экрана](https://ru.wikipedia.org/wiki/%D0%AD%D0%BA%D1%80%D0%B0%D0%BD%D0%BD%D0%BE%D0%B5_%D1%81%D1%87%D0%B8%D1%82%D1%8B%D0%B2%D0%B0%D1%8E%D1%89%D0%B5%D0%B5_%D1%83%D1%81%D1%82%D1%80%D0%BE%D0%B9%D1%81%D1%82%D0%B2%D0%BE) — устройства вывода, которые выводят элементы на странице по очереди. Если на странице много текста, вы можете использовать заголовки, чтобы придать странице внутреннюю структуру. Хорошая структура страницы помогает всем читателям легко перемещаться по странице или выбрать интересующие темы. + +{{< table caption = "Можно делать и нельзя - Заголовки" >}} +Можно | Нельзя +:--| :----- +Обновите заголовок в фронтальной части страницы или записи блога. | Используйте заголовок первого уровня, так как Hugo автоматически преобразует название страницы в фронтальной части в заголовок первого уровня. +Используйте упорядоченные заголовки, чтобы сформировать общее представление о содержании страницы. | Используйте заголовки с уровня 4 по 6, если только это только в этом нет необходимости. Если текст настолько подробный, возможно, его нужно разделить на отдельные статьи. +Используйте знак решётки или хеша (#) для всех видов контента, кроме записей блога. | Используйте подчеркивание (--- или ===) для обозначения заголовков первого уровня. +Начинайте с большой буквы только первое слово в заголовке. Например, **Расширение kubectl с помощью плагинов** | Пишите с заглавной буквы все слова в заголовке. Например, **Расширение Kubectl С Помощью Плагинов** +{{< /table >}} + +### Параграфы + +{{< table caption = "Можно делать и нельзя - Параграфы" >}} +Можно | Нельзя +:--| :----- +Проследите за тем, чтобы в одном абзаце было не более 6 предложений. | Добавить к первом абзацу отступ с пробелами. Например, ⋅⋅⋅Три пробела перед абзацем образуют отступ. +Используйте три дефиса (---) для создания горизонтальной черты. Используйте горизонтальные линии для обозначения конца в содержании абзаца. Например, смена места в истории или переход темы в разделе. | Используйте горизонтальные линии для оформления. +{{< /table >}} + +### Ссылки + +{{< table caption = "Можно делать и нельзя - Ссылки" >}} +Можно | Нельзя +:--| :----- +Указывайте ссылки, которые передают суть содержания, на который они ссылаются. Например: "Некоторые порты открыты на ваших машинах. Смотрите раздел Проверка необходимых портов, чтобы получить дополнительную информацию". | Используйте двусмысленные термины, такие как "нажмите сюда". Например: Некоторые порты открыты на ваших машинах. Смотрите этот раздел, чтобы получить дополнительную информацию". +Указывайте ссылки в стиле Markdown: `[текст ссылки](URL)`. Например: `[Макрокоды Hugo](/docs/contribute/style/hugo-shortcodes/#table-captions)` отобразится как [Макрокоды Hugo](/docs/contribute/style/hugo-shortcodes/#table-captions). | Указывайте ссылки в формате HTML: `Ознакомьтесь с нашим руководством!` или добавляйте ссылки, которые открываются в новых вкладках или окнах. Например: `[example website](https://example.com){target="_blank"}` +{{< /table >}} + + +### Списки +Сгруппируйте пункты в списке так, чтобы они были связаны друг с другом и следовали в определённом порядке, либо чтобы они сохраняли взаимосвязь между несколькими элементами. Когда программа чтения с экрана встречает нумерованный или неупорядоченный список, пользователю будет проинформирован, что существует группа из элементов списка. Затем пользователь может использовать клавиши-стрелки для перемещения между разными элементами в списке. +Навигационные ссылки по сайту также могут быть помечены как элементы списка; в конечном счёте, все они просто группа связанных ссылок. + + - Заканчивайте каждый элемент в списке точкой, если один или несколько элементов в списке являются законченными предложениями. Как правило, для согласованности либо все элементы должны быть целыми предложениями, либо ни один из них. + + {{< note >}} Упорядоченные списки, которые являются частью неполного вступительного предложения, могут быть написаны в нижнем регистре и оканчиваться на точку, как если бы каждый элемент был составляющей вступительного предложения.{{< /note >}} + + - Используйте цифру один (1.) для упорядоченных списков. + + - Используйте (+), (*) или (-) для неупорядоченных списков. + + - Добавьте пустую строку после каждого списка. + + - Во вложенных списках добавьте отступ в четыре пробела (например, ⋅⋅⋅⋅). + + - Элементы списка могут содержать несколько абзацев. Каждый последующий абзац в элементе списка должен иметь отступ в четыре пробела или один символ табуляции. + +### Таблицы + +Семантическая цель таблицы данных состоит в представлении данных в табличном виде. Пользователи с нормальным зрением могут бегло просмотреть таблицу, однако программа для чтения с экрана сканирует таблицу построчно. Заголовок таблицы используется для создания информативного заголовка для табличных данных. Инструменты вспомогательных технологий (Assistive technologies, AT) используют элемент заголовка HTML-таблицы, чтобы идентифицировать для пользователей, какие на странице есть таблицы. + +- Добавьте подписи к таблицам с помощью соответствующих [макрокодов Hugo](/docs/contribute/style/hugo-shortcodes/#table-captions). + +## Рекомендации по написанию контента + +В этом разделе перечислены рекомендации для написания ясного, лаконичного и единообразного текста документации. + +### Используйте настоящее время + +{{< table caption = "Можно делать и нельзя - Используйте настоящее время" >}} +Можно | Нельзя +:--| :----- +Эта команда запускает прокси. | Эта команда запустит прокси. + {{< /table >}} + +Исключение: используйте будущее или прошедшее время, если требуется передать правильный смысл. + +### Используйте действительный залог + +{{< table caption = "Можно делать и нельзя - Используйте действительный залог" >}} +Можно | Нельзя +:--| :----- +Вы можете изучить API с помощью браузера. | API можно изучить с помощью браузера. +В файле YAML определяется количество реплик. | Количество реплик определяется в файле YAML. +{{< /table >}} + +Исключение: используйте страдательный залог, если в действительном залоге получается неудачная формулировка. + +### Используйте простой и понятный язык + +Используйте простой и доступный язык. Избегайте использования ненужных фраз, например, "пожалуйста". + +{{< table caption = "Можно делать и нельзя - Используйте простой и понятный язык" >}} +Можно | Нельзя +:--| :----- +Чтобы создать ReplicaSet, ... | Для того чтобы создать a ReplicaSet, ... +Смотрите конфигурационный файл. | Пожалуйста, смотрите конфигурационный файл. +Посмотрите Pods. | С помощью следующей команды мы посмотрим Pods. +{{< /table >}} + +### Обращайтесь к читателю на "вы" + +{{< table caption = "Можно делать и нельзя - Обращайтесь к читателю на вы" >}} +Можно | Нельзя +:--| :----- +Вы можете создать Deployment с помощью ... | Мы создадим Deployment с помощью ... +В предыдущем выводе вы можете увидеть ... | В предыдущем выводе мы можем увидеть ... +{{< /table >}} + + +### Избегайте использования латинских фраз + +Вместо латинских аббревиатур используйте соответствующие выражения на английском. + +{{< table caption = "Можно делать и нельзя - Избегайте использования латинских фраз" >}} +Можно | Нельзя +:--| :----- +For example, ... | e.g., ... +That is, ...| i.e., ... +{{< /table >}} + + +Исключение: используйте "etc." вместо "et cetera". + +## Ошибки, которые следует избегать + +### Избегайте использования "мы" + +Использование "мы" в предложении может сбить с толку, так так неясно, кто под этим "мы" подразумевается (имеется ли в виду сам читатель при этом). + +{{< table caption = "Можно делать и нельзя - Избегайте использования мы" >}} +Можно | Нельзя +:--| :----- +Версия 1.4 включает в себя ... | В версии 1.4 мы добавили ... +Kubernetes представляет новую возможность для ... | Мы представляем новую возможность ... +На этой странице вы узнаете, как использовать Pods. | На этой странице мы познакомимся с Pods. +{{< /table >}} + + +### Избегайте жаргона и идиомы + +Некоторые читатели говорят на английском как на втором языке. Избегайте жаргона и идиом, чтобы облегчить им понимание. + +{{< table caption = "Можно делать и нельзя - Избегайте жаргона и идиомы" >}} +Можно | Нельзя +:--| :----- +Internally, ... | Under the hood, ... +Create a new cluster. | Turn up a new cluster. +{{< /table >}} + + +### Избегайте выражений о будущем + +Не давайте обещаний или намеков на будущее. Если вам нужно рассказать про функциональность в альфа-версии, под соответствующем заголовком напишите поясняющий текст, что информация относится к альфа-версии. + +### Избегайте выражений, которые могут потерять актуальность + +Избегайте таких слов, как "в настоящее время" и "новый". Новая функциональность в настоящее время не будет таковой через несколько месяцев. + +{{< table caption = "Можно делать и нельзя - Избегайте выражений, которые могут потерять актуальность" >}} +Можно | Нельзя +:--| :----- +В версии 1.4 ... | В текущей версии ... +Функциональность Federation предоставляет ... | Новая функциональность Federation предоставляет ... +{{< /table >}} + + +{{% /capture %}} + +{{% capture whatsnext %}} + +* Подробнее про [написание новой темы](/ru/docs/contribute/style/write-new-topic/). +* Подробнее про [использование шаблонов страниц](/ru/docs/contribute/style/page-templates/). +* Подробнее про [создание пулреквеста](/ru/docs/contribute/start/#отправка-пулреквеста)). + +{{% /capture %}} diff --git a/content/ru/docs/contribute/style/write-new-topic.md b/content/ru/docs/contribute/style/write-new-topic.md new file mode 100644 index 0000000000..d13789e529 --- /dev/null +++ b/content/ru/docs/contribute/style/write-new-topic.md @@ -0,0 +1,119 @@ +--- +title: Написание новой темы +content_template: templates/task +weight: 20 +--- + +{{% capture overview %}} +На этой странице показано, как создать новую тему для документации Kubernetes. +{{% /capture %}} + + +{{% capture prerequisites %}} +Создайте копию репозитория документации Kubernetes, как описано в разделе [Участие для начинающих](/ru/docs/contribute/start/). +{{% capture steps %}} + +## Выбор типы страницы + +Перед написанием новой темы, выберите тип страницы, который бы лучше всего подходил под ваш текст: + +{{< table caption = "Правила выбора типа страницы" >}} +Тип | Описание +:--- | :---------- +Концепция | Страница концепции объясняет некоторые аспекты Kubernetes. Например, страницы концепции может описывать объект Deployment в Kubernetes и разъяснить, какую роль он играет после развертывания, масштабирования и обновления приложения. Как правило, страницы концепций не включают последовательности шагов, а вместо этого содержат ссылки на задачи или руководства. В качестве примера концептуальной темы посмотрите страницу Nodes. +Задача | На странице задачи показывается, как сделать что-то одно конкретное, главным образом с помощью короткой последовательности шагов. Страница задачи может быть короткой или длинной, если она остаётся сконцентрированной на одном аспекте. На странице задач можно сочетать краткие объяснения с необходимыми шагами для выполнения, однако если вам нужно дать подробное пояснение, вам следует сделать это в концептуальной теме. Смежные задачи и концептуальные темы должны быть связаны друг с другом. В качестве примера короткой страницы задачи посмотрите Configure a Pod to Use a Volume for Storage. Пример длинной страницы задачи смотрите Configure Liveness and Readiness Probes +Руководство | На странице руководства показано, как сделать что-то более крупнее одной-единственной задачи. В руководстве может быть несколько последовательностей шагов, которые читатели могут реально выполнить по ходу чтения страницы. Либо на странице руководства могут приведены объяснения связанных частей кода. Например, руководство может содержать разбор примера кода. Руководство может включать в себя краткие объяснения связанной функциональности Kubernetes, но при они этом должны ссылаться на сопутствующие концептуальные темы, где можно узнать подробнее про конкретные возможности. +{{< /table >}} + +Используйте шаблон для каждой новой страницы. Каждый тип страницы использует определённый [шаблон](/docs/contribute/style/page-templates/), поэтому при написании собственных тем вам следует выбрать свой шаблон. Использование шаблонов помогает поддерживать единообразие в темах конкретного типа. + +## Выбор заголовка и имени файла a title and filename + +Подберите заголовок, содержащий такие ключевые слова, по которым вы могли его найти в поисковике. +Имя файла должно создаваться из слов в заголовке, написанных через дефис. +Например, для темы с заголовком [Using an HTTP Proxy to Access the Kubernetes API](/docs/tasks/access-kubernetes-api/http-proxy-access-api/) имя файла будет `http-proxy-access-api.md`. Вам не нужно указывать "kubernetes" в имени файла, потому что слово "kubernetes" уже есть в полном URL-адресе темы, например: + + /docs/tasks/access-kubernetes-api/http-proxy-access-api/ + +## Добавление заголовка темы в фронтальную часть + +В [фронтальную часть](https://gohugo.io/content-management/front-matter/) файла вашей темы поместите поле заголовка `title`. Фронтальная часть — YAML-блок, который находится тремя дефисами в самом верху страницы. Например: + + --- + title: Using an HTTP Proxy to Access the Kubernetes API + --- + +## Выбор директории + +В зависимости от типа вашей страницы поместите новый файл в одну из следующую поддиректорию: + +* /content/en/docs/tasks/ +* /content/en/docs/tutorials/ +* /content/en/docs/concepts/ + +Вы можете поместить файл в имеющуюся поддиректорию либо создать новую. + +## Добавление темы в оглавлении + +Оглавление динамически генерируется исходя из структуры директорий документации. Корневые директории в `/content/en/docs/` создают навигацию с основными ссылками, где у каждой поддиректории есть записи в оглавлении. + +В каждой поддиректории есть файл `_index.md`, представляющий собой "главную" страницу всего содержимого этой поддиректории. В файле `_index.md` не нужно применять шаблон. В нём находится обзор содержания тем в поддиректории. + +Другие файлы в директории по умолчанию сортируются в алфавитном порядке. Такой порядок сортировки редко устраивает. Для управления такой относительной сортировкой тем в поддиректории, определите ключ `weight:` с целым числом в фронтальной части файла. Как правило, мы используем значения, кратные 10, чтобы оставить про запас для будущих страниц. Например, тема с весом `10` будет отображаться перед темой с весом `20`. + +## Вставка кода в тему + +Если вы хотите добавить код в тему, вы можете встроить код из файла напрямую, используя синтаксис блока кода в Markdown. Такой способ рекомендуется использовать в следующих случаев (это не исчерпывающий список): + +- В вашем коде показывается вывод такой команды, как `kubectl get deploy mydeployment -o json | jq '.status'`. +- Ваш код недостаточно универсален, чтобы пользователи могли его попробовать сами. В качестве примера можно привести пример YAML-файла для создания Pod, который зависит от конкретной реализации [FlexVolume](/docs/concepts/storage/volumes#flexvolume). +- Ваш код — это не готовый пример, потому что он предзначен для выделения части большего файла. Например, при описании способов настройки [PodSecurityPolicy](/docs/tasks/administer-cluster/sysctl-cluster/#podsecuritypolicy) по определённым причинам вы можете включить небольшой фрагмент напрямую в файле темы. +- Ваш код по разным причинам не подходит для тестирования пользователями. Например, если вы описываете, как новый атрибут должен добавляться к ресурсу с помощью команды `kubectl edit`, то вы можете добавить короткий пример, показывающий только добавляемый атрибут. + +## Добавление кода из другого файла + +Другой способ добавить код в вашу тему — создать новый полноценный файл с примером (или группу файлов примеров), а затем из вашей темы подключить этот пример. +Используйте этот метод, чтобы включить универсальный и повторно используемый пример YAML-файла, который читатель может проверить сам. + +При добавлении нового отдельного файла примера, например, в формате YAML, поместите код в одну из директорий `/examples/`, где `` — язык темы. В вашем файле темы используйте макрокод `codenew`: + +```none +{{/my-example-yaml>" */>}} +``` + +где `` — это путь к включаемому файлу относительно директории `examples`. Следующий макрокод Hugo ссылается на YAML-файл по пути `/content/en/examples/pods/storage/gce-volume.yaml`. + +```none +{{}} +``` + +{{< note >}} +Чтобы отобразить Hugo-макрокоды в исходном виде, как в приведенном выше примере, поместите их в комментарии в стиле языка Си между `<` и `>`. Для примера посмотрите исходный код этой страницы. +{{< /note >}} + +## Демонстрация создания API-объекта из конфигурационного файла + +Если вам нужно показать, как создать объект API из файла конфигурации, поместите файл конфигурации в одну из директорий в `/examples`. + +В вашей теме укажите эту команду: + +``` +kubectl create -f https://k8s.io/examples/pods/storage/gce-volume.yaml +``` + +{{< note >}} +При добавлении новых YAML-файлов в директорию `/examples`, убедитесь, что этот файл перечислен в файле `/examples_test.go`. Подключённый к сайту Travis CI автоматически выполнит этот тестовый сценарий при отправке PR, чтобы проверить все примеры. +{{< /note >}} + +В качестве примера темы, в которой используется этот метод, смотрите [Running a Single-Instance Stateful Application](/docs/tutorials/stateful-application/run-stateful-application/). + +## Добавление изображений в тему + +Поместите файлы изображений в директорию `/images`. Предпочтительный формат изображения — SVG. + +{{% /capture %}} + +{{% capture whatsnext %}} +* Подробнее про [использование шаблонов страниц](/ru/docs/contribute/style/page-templates/). +* Подробнее про [создание пулреквеста](/ru/docs/contribute/start/#отправка-пулреквеста)). +{{% /capture %}} diff --git a/content/ru/docs/reference/glossary/cluster.md b/content/ru/docs/reference/glossary/cluster.md index 614b42dd98..79e10c8fcc 100644 --- a/content/ru/docs/reference/glossary/cluster.md +++ b/content/ru/docs/reference/glossary/cluster.md @@ -2,16 +2,16 @@ title: Кластер id: cluster date: 2019-06-15 -full_link: +full_link: short_description: > - Набор машин, называемых нодами, которые запускают контейнерные приложения, управляемые Kubernetes. Кластер имеет как минимум одну рабочую ноду и хотя бы одну главную ноду. + Набор машин, так называемые узлы, которые запускают контейнеризированные приложения. Кластер имеет как минимум один рабочий узел. -aka: +aka: tags: - fundamental - operation --- -Набор машин, называемых нодами, которые запускают контейнерные приложения, управляемые Kubernetes. Кластер имеет как минимум одну рабочую ноду и хотя бы одну главную ноду. +Набор машин, так называемые узлы, которые запускают контейнеризированные приложения. Кластер имеет как минимум один рабочий узел. -Родительские ноды содержат дочерние ноды, являющиеся компонентами приложения. Главные ноды управляют родительскими нодами и модулями в кластере. Несколько главных нод используются для обеспечения отказоустойчивости кластера и высокой доступности. +В рабочих узлах размещены поды, являющиеся компонентами приложения. Панель управления управляет рабочими узлами и подами в кластере. В промышленных средах панель управления обычно запускается на нескольких компьютерах, а кластер, как правило, развёртывается на нескольких узлах, гарантируя отказоустойчивость и высокую надёжность. diff --git a/content/ru/docs/reference/glossary/container-runtime.md b/content/ru/docs/reference/glossary/container-runtime.md new file mode 100644 index 0000000000..cea63dfa94 --- /dev/null +++ b/content/ru/docs/reference/glossary/container-runtime.md @@ -0,0 +1,21 @@ +--- +title: Среда выполнения контейнера +id: container-runtime +date: 2019-06-05 +full_link: /docs/reference/generated/container-runtime +short_description: > + Среда выполнения контейнера — это программа, предназначенная для выполнения контейнеров. + +aka: +tags: +- fundamental +- workload +--- + Среда выполнения контейнера — это программа, предназначенная для выполнения контейнеров. + + + +Kubernetes поддерживает несколько сред для запуска контейнеров: {{< glossary_tooltip term_id="docker">}}, +{{< glossary_tooltip term_id="containerd" >}}, {{< glossary_tooltip term_id="cri-o" >}}, +и любая реализация [Kubernetes CRI (Container Runtime +Interface)](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-node/container-runtime-interface.md). diff --git a/content/ru/docs/reference/glossary/container.md b/content/ru/docs/reference/glossary/container.md new file mode 100755 index 0000000000..7c2e66e4d1 --- /dev/null +++ b/content/ru/docs/reference/glossary/container.md @@ -0,0 +1,18 @@ +--- +title: Контейнер +id: container +date: 2018-04-12 +full_link: /docs/concepts/overview/what-is-kubernetes/#why-containers +short_description: > + Переносимый и не требовательный к ресурсам исполняемый экземпляр образа, содержащий приложение вместе со всеми его зависимостями. + +aka: +tags: +- fundamental +- workload +--- + Переносимый и не требовательный к ресурсам исполняемый экземпляр образа, содержащий приложение вместе со всеми его зависимостями. + + + +Контейнеры изолирует приложения от инфраструктуры хост-машины, чтобы обеспечить простое масштабирование и упростить развёртывание в различных средах облачных платформ или операционных систем. diff --git a/content/ru/docs/reference/glossary/containerd.md b/content/ru/docs/reference/glossary/containerd.md new file mode 100644 index 0000000000..251bebcd20 --- /dev/null +++ b/content/ru/docs/reference/glossary/containerd.md @@ -0,0 +1,17 @@ +--- +title: containerd +id: containerd +date: 2019-05-14 +full_link: https://containerd.io/docs/ +short_description: > + Среда выполнения контейнера с упором на простоту, надежность и переносимость + +aka: +tags: +- tool +--- + Среда выполнения контейнера с упором на простоту, надежность и переносимость + + + +containerd — среда выполнения {{< glossary_tooltip text="контейнера" term_id="container" >}}, который представляет собой демон для Linux или Windows. containerd заботится о получении и хранении образов контейнеров, запуске контейнеров, осуществлять доступ по сети и т.д. diff --git a/content/ru/docs/reference/glossary/control-plane.md b/content/ru/docs/reference/glossary/control-plane.md new file mode 100644 index 0000000000..a4565af381 --- /dev/null +++ b/content/ru/docs/reference/glossary/control-plane.md @@ -0,0 +1,13 @@ +--- +title: Плоскость управления (Control Plane) +id: control-plane +date: 2019-05-12 +full_link: +short_description: > + Уровень оркестрации контейнеров с API и интерфейсами для определения, развёртывания и управления жизненным циклом контейнеров. + +aka: +tags: +- fundamental +--- + Уровень оркестрации контейнеров с API и интерфейсами для определения, развёртывания и управления жизненным циклом контейнеров. diff --git a/content/ru/docs/reference/glossary/cri-o.md b/content/ru/docs/reference/glossary/cri-o.md new file mode 100644 index 0000000000..1b99ac947c --- /dev/null +++ b/content/ru/docs/reference/glossary/cri-o.md @@ -0,0 +1,19 @@ +--- +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 +--- +Инструмент, позволяющий использовать среды выполнения контейнеров формата OCI с помощью технологии Kubernetes CRI. + + + +CRI-O — это реализация {{< glossary_tooltip term_id="cri" >}}, позволяющая использовать среды выполнения {{< glossary_tooltip text="контейнеров" term_id="container" >}}, совместимые со [спецификацией исполняемой среды контейнеров](http://www.github.com/opencontainers/runtime-spec) Open Container Initiative (OCI). + +Развертывание CRI-O позволяет Kubernetes использовать любую OCI-совместимую среду выполнения в качестве контейнерной среды выполнения для выполнения {{< glossary_tooltip text="подов" term_id="pod" >}} и загружать образы OCI-контейнера из удаленных реестров. diff --git a/content/ru/docs/reference/glossary/cri.md b/content/ru/docs/reference/glossary/cri.md new file mode 100644 index 0000000000..2f47ddc915 --- /dev/null +++ b/content/ru/docs/reference/glossary/cri.md @@ -0,0 +1,17 @@ +--- +title: Container runtime interface (CRI) +id: cri +date: 2019-03-07 +full_link: /docs/concepts/overview/components/#container-runtime +short_description: > + API сред выполнения контейнеров для интеграции с kubelet + +aka: +tags: +- fundamental +--- +Интерфейс среды выполнения контейнера (Container Runtime Interface, CRI) — это API сред выполнения контейнера, которая интегрируется с kubelet на узле. + + + +Для получения дополнительной информации смотрите API и спефикации [CRI](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-node/container-runtime-interface.md). diff --git a/content/ru/docs/reference/glossary/daemonset.md b/content/ru/docs/reference/glossary/daemonset.md new file mode 100755 index 0000000000..b0e4ca6195 --- /dev/null +++ b/content/ru/docs/reference/glossary/daemonset.md @@ -0,0 +1,19 @@ +--- +title: DaemonSet +id: daemonset +date: 2018-04-12 +full_link: /docs/concepts/workloads/controllers/daemonset +short_description: > + Гарантирует, что копия Pod выполняется в наборе узлов кластера. + +aka: +tags: +- fundamental +- core-object +- workload +--- + Гарантирует, что копия {{< glossary_tooltip text="Pod" term_id="pod" >}} выполняется в наборе узлов {{< glossary_tooltip text="кластера" term_id="cluster" >}}. + + + +Используется для развертывания системных демонов, таких как сборщики логов и агенты мониторинга, которые, как правило, должны работать на каждом {{< glossary_tooltip text="узла" term_id="node" >}}. diff --git a/content/ru/docs/reference/glossary/deployment.md b/content/ru/docs/reference/glossary/deployment.md new file mode 100755 index 0000000000..26c9aedcd8 --- /dev/null +++ b/content/ru/docs/reference/glossary/deployment.md @@ -0,0 +1,20 @@ +--- +title: Deployment +id: deployment +date: 2018-04-12 +full_link: /docs/concepts/workloads/controllers/deployment/ +short_description: > + API-объект, управляющий реплицированным приложением. + +aka: +tags: +- fundamental +- core-object +- workload +--- + API-объект, управляющий реплицированным приложением. + + + +Каждая реплика представляет {{< glossary_tooltip term_id="pod" >}}, а все Pod-объекты распределяются по узлам кластера. + diff --git a/content/ru/docs/reference/glossary/docker.md b/content/ru/docs/reference/glossary/docker.md new file mode 100755 index 0000000000..290b6d3c60 --- /dev/null +++ b/content/ru/docs/reference/glossary/docker.md @@ -0,0 +1,17 @@ +--- +title: Docker +id: docker +date: 2018-04-12 +full_link: https://docs.docker.com/engine/ +short_description: > + Docker — это программное обеспечение для виртуализации на уровне операционной системы, которая известна как контейнеризация. + +aka: +tags: +- fundamental +--- +Docker (в частности, Docker Engine) — это программное обеспечение для виртуализации на уровне операционной системы, которая также известна как {{< glossary_tooltip text="контейнеризация" term_id="container" >}}. + + + +Docker использует возможности изоляции ресурсов ядра Linux, такие как cgroups и пространства имен ядра, а также каскадно-объединённую файловую систему, например, OverlayFS и другие, чтобы независимые друг от друга контейнеры могли работать в одном экземпляре Linux без накладных расходов на запуск и поддержку работы виртуальных машин (VM). diff --git a/content/ru/docs/reference/glossary/etcd.md b/content/ru/docs/reference/glossary/etcd.md new file mode 100755 index 0000000000..cb3ac286d7 --- /dev/null +++ b/content/ru/docs/reference/glossary/etcd.md @@ -0,0 +1,20 @@ +--- +title: etcd +id: etcd +date: 2018-04-12 +full_link: /docs/tasks/administer-cluster/configure-upgrade-etcd/ +short_description: > + Распределённое и высоконадёжное хранилище данных в формате "ключ-значение", которое используется как основное хранилище всех данных кластера в Kubernetes. + +aka: +tags: +- architecture +- storage +--- +Распределённое и высоконадёжное хранилище данных в формате "ключ-значение", которое используется как основное хранилище всех данных кластера в Kubernetes. + + + +Если ваш кластер Kubernetes использует etcd в качестве основного хранилища, убедитесь, что у вас [настроено резервное копирование](/docs/tasks/administer-cluster/configure-upgrade-etcd/#backing-up-an-etcd-cluster) данных. + +Вы можете найти подробную информацию о etcd в [официальной документации](https://etcd.io/docs/). diff --git a/content/ru/docs/reference/glossary/kube-apiserver.md b/content/ru/docs/reference/glossary/kube-apiserver.md new file mode 100755 index 0000000000..24d3a33587 --- /dev/null +++ b/content/ru/docs/reference/glossary/kube-apiserver.md @@ -0,0 +1,23 @@ +--- +title: API-сервер +id: kube-apiserver +date: 2018-04-12 +full_link: /docs/reference/generated/kube-apiserver/ +short_description: > + Компонент панели управления, обслуживающий API Kubernetes. + +aka: +- kube-apiserver +tags: +- architecture +- fundamental +--- + Сервер API — компонент Kubernetes +{{< glossary_tooltip text="панели управления" term_id="control-plane" >}}, который представляет API Kubernetes. +API-сервер — это клиентская часть панели управления Kubernetes + + + +Основной реализацией API-сервера Kubernetes является [kube-apiserver](/docs/reference/generated/kube-apiserver/). +kube-apiserver предназначен для горизонтального масштабирования, то есть развёртывание на несколько экземпляров. +Вы можете запустить несколько экземпляров kube-apiserver и сбалансировать трафик между этими экземплярами. diff --git a/content/ru/docs/reference/glossary/kube-controller-manager.md b/content/ru/docs/reference/glossary/kube-controller-manager.md new file mode 100755 index 0000000000..d1cb711164 --- /dev/null +++ b/content/ru/docs/reference/glossary/kube-controller-manager.md @@ -0,0 +1,18 @@ +--- +title: kube-controller-manager +id: kube-controller-manager +date: 2018-04-12 +full_link: /docs/reference/command-line-tools-reference/kube-controller-manager/ +short_description: > + Компонент Control Plane запускает процессы контроллера. + +aka: +tags: +- architecture +- fundamental +--- + Компонент Control Plane запускает процессы {{< glossary_tooltip text="контроллера" term_id="controller" >}}. + + + +Вполне логично, что каждый {{< glossary_tooltip text="контроллер" term_id="controller" >}} в свою очередь представляет собой отдельный процесс, и для упрощения все такие процессы скомпилированы в один двоичный файл и выполняются в одном процессе. diff --git a/content/ru/docs/reference/glossary/kube-proxy.md b/content/ru/docs/reference/glossary/kube-proxy.md new file mode 100755 index 0000000000..2858f60403 --- /dev/null +++ b/content/ru/docs/reference/glossary/kube-proxy.md @@ -0,0 +1,20 @@ +--- +title: kube-proxy +id: kube-proxy +date: 2018-04-12 +full_link: /docs/reference/command-line-tools-reference/kube-proxy/ +short_description: > + `kube-proxy` — сетевой прокси, работающий на каждом узле в кластере. + +aka: +tags: +- fundamental +- networking +--- + [kube-proxy](/docs/reference/command-line-tools-reference/kube-proxy/) — сетевой прокси, работающий на каждом узле в кластере, и реализующий часть концепции {{< glossary_tooltip text="сервис" term_id="service">}}. + + + +kube-proxy конфигурирует правила сети на узлах. При помощи них разрешаются сетевые подключения к вашими подам изнутри и снаружи кластера. + +kube-proxy использует уровень фильтрации пакетов в операционной системы, если он доступен. В противном случае, kube-proxy сам обрабатывает передачу сетевого трафика. \ No newline at end of file diff --git a/content/ru/docs/reference/glossary/kube-scheduler.md b/content/ru/docs/reference/glossary/kube-scheduler.md new file mode 100755 index 0000000000..4cf084ea0f --- /dev/null +++ b/content/ru/docs/reference/glossary/kube-scheduler.md @@ -0,0 +1,19 @@ +--- +title: kube-scheduler +id: kube-scheduler +date: 2018-04-12 +full_link: /docs/reference/generated/kube-scheduler/ +short_description: > + Компонент плоскости управления, который отслеживает созданные поды без привязанного узла и выбирает узел, на котором они должны работать. + +aka: +tags: +- architecture +--- + Компонент плоскости управления, который отслеживает созданные поды без привязанного узла и выбирает узел, на котором они должны работать. + + + + + +При планировании развёртывания подов на узлах учитываются множество факторов, включая требования к ресурсам, ограничения, связанные с аппаратными/программными политиками, принадлежности (affinity) и непринадлежности (anti-affinity) узлов/подов, местонахождения данных, предельных сроков. diff --git a/content/ru/docs/reference/glossary/kubelet.md b/content/ru/docs/reference/glossary/kubelet.md new file mode 100755 index 0000000000..0aadf8ed29 --- /dev/null +++ b/content/ru/docs/reference/glossary/kubelet.md @@ -0,0 +1,18 @@ +--- +title: Kubelet +id: kubelet +date: 2018-04-12 +full_link: /docs/reference/generated/kubelet +short_description: > + Агент, работающий на каждом узле в кластере. Он следит за тем, чтобы контейнеры были запущены в поде. + +aka: +tags: +- fundamental +- core-object +--- + Агент, работающий на каждом узле в кластере. Он следит за тем, чтобы контейнеры были запущены в поде. + + + +Утилита kubelet принимает набор PodSpecs, и гарантирует работоспособность и исправность определённых в них контейнеров. Агент kubelet не отвечает за контейнеры, не созданные Kubernetes. diff --git a/content/ru/docs/reference/glossary/label.md b/content/ru/docs/reference/glossary/label.md new file mode 100755 index 0000000000..287fd32528 --- /dev/null +++ b/content/ru/docs/reference/glossary/label.md @@ -0,0 +1,17 @@ +--- +title: Метка +id: label +date: 2018-04-12 +full_link: /docs/concepts/overview/working-with-objects/labels +short_description: > + Группирует объекты на основе произвольных критериев, по которым пользователи могут их идентифицировать. + +aka: +tags: +- fundamental +--- + Группирует объекты на основе произвольных критериев, по которым пользователи могут их идентифицировать. + + + +Метки — это пары "ключ-значение", которые прикрепляются к таким объектам, как {{< glossary_tooltip text="Pod" term_id="pod" >}}. Они используются для организации и получения подмножеств объектов. diff --git a/content/ru/docs/reference/glossary/node.md b/content/ru/docs/reference/glossary/node.md new file mode 100755 index 0000000000..0a2cc77e62 --- /dev/null +++ b/content/ru/docs/reference/glossary/node.md @@ -0,0 +1,17 @@ +--- +title: Node +id: node +date: 2018-04-12 +full_link: /docs/concepts/architecture/nodes/ +short_description: > + Узел — рабочая машина в Kubernetes. + +aka: +tags: +- fundamental +--- + Узел — рабочая машина в Kubernetes. + + + +Рабочий узел может быть как виртуальной, так и физической машиной, в зависимости от кластера. У него есть локальные демоны или сервисы, необходимые для запуска {{< glossary_tooltip text="подов" term_id="pod" >}}, а сам он управляется панелью управления. Демоны на узле включают в себя {{< glossary_tooltip text="kubelet" term_id="kubelet" >}}, {{< glossary_tooltip text="kube-proxy" term_id="kube-proxy" >}} и среду выполнения контейнера, основанную на {{< glossary_tooltip text="CRI" term_id="cri" >}}, например {{< glossary_tooltip term_id="docker" >}}. diff --git a/content/ru/docs/reference/glossary/pod.md b/content/ru/docs/reference/glossary/pod.md new file mode 100755 index 0000000000..d00f3225a4 --- /dev/null +++ b/content/ru/docs/reference/glossary/pod.md @@ -0,0 +1,18 @@ +--- +title: Pod +id: pod +date: 2018-04-12 +full_link: /docs/concepts/workloads/pods/pod-overview/ +short_description: > + Самый маленький и простой объект в Kubernetes. Под — это набор запущенных контейнеров в кластере. + +aka: +tags: +- core-object +- fundamental +--- + Самый маленький и простой объект в Kubernetes. Объект Pod — набор запущенных {{< glossary_tooltip text="контейнеров" term_id="container" >}} в кластере. + + + +Как правило, один под предназначен для выполнения одного основного контейнера. Он также может запускать дополнительные "прицепные" (sidecar) контейнеры, добавляющие новые функциональные возможности, например, логирование. Контейнеры обычно управляются {{< glossary_tooltip term_id="deployment" >}}. diff --git a/content/ru/docs/reference/glossary/selector.md b/content/ru/docs/reference/glossary/selector.md new file mode 100755 index 0000000000..4eef4299f0 --- /dev/null +++ b/content/ru/docs/reference/glossary/selector.md @@ -0,0 +1,18 @@ +--- +title: Селектор +id: selector +date: 2018-04-12 +full_link: /docs/concepts/overview/working-with-objects/labels/ +short_description: > + Позволяет пользователям фильтровать список ресурсов по меткам. + +aka: +tags: +- fundamental +--- + Позволяет пользователям фильтровать список ресурсов по меткам. + + + +Селекторы применяются при создании запросов для фильтрации списков ресурсов по {{< glossary_tooltip text="меткам" term_id="label" >}}. + diff --git a/content/ru/docs/reference/glossary/service.md b/content/ru/docs/reference/glossary/service.md new file mode 100755 index 0000000000..1f4d4736c1 --- /dev/null +++ b/content/ru/docs/reference/glossary/service.md @@ -0,0 +1,18 @@ +--- +title: Сервис (Service) +id: service +date: 2018-04-12 +full_link: /docs/concepts/services-networking/service/ +short_description: > + Способ представления приложения, запущенного в наборе подов, в виде сетевого сервиса. + +aka: +tags: +- fundamental +- core-object +--- +Абстрактный способ представления приложения, запущенного в наборе {{< glossary_tooltip text="подов" term_id="pod" >}}, в виде сетевого сервиса. + + + +Набор подов, из которых состоит сервис, определяется (как правило) {{< glossary_tooltip text="селектором" term_id="selector" >}}. При добавлении или удалении подов, набор подов, соответствующий селектору, изменится. Сервис обеспечивает, что сетевой трафик может быть направлен на текущий набор подов для планирования рабочей нагрузки. diff --git a/content/ru/docs/setup/learning-environment/_index.md b/content/ru/docs/setup/learning-environment/_index.md new file mode 100644 index 0000000000..0670a18c50 --- /dev/null +++ b/content/ru/docs/setup/learning-environment/_index.md @@ -0,0 +1,4 @@ +--- +title: Среда обучения +weight: 20 +--- diff --git a/content/ru/docs/setup/learning-environment/kind.md b/content/ru/docs/setup/learning-environment/kind.md new file mode 100644 index 0000000000..d0f775dd22 --- /dev/null +++ b/content/ru/docs/setup/learning-environment/kind.md @@ -0,0 +1,19 @@ +--- +title: Установка Kubernetes с помощью Kind +weight: 40 +content_template: templates/concept +--- + +{{% capture overview %}} + +Kind — это инструмент для запуска локальных кластеров Kubernetes с помощью "узлов" контейнера Docker. + +{{% /capture %}} + +{{% capture body %}} + +## Установка + +Смотрите страницу [по установке Kind](https://kind.sigs.k8s.io/docs/user/quick-start/). + +{{% /capture %}} diff --git a/content/ru/docs/setup/learning-environment/minikube.md b/content/ru/docs/setup/learning-environment/minikube.md new file mode 100644 index 0000000000..1e0cb02673 --- /dev/null +++ b/content/ru/docs/setup/learning-environment/minikube.md @@ -0,0 +1,512 @@ +--- +reviewers: +- dlorenc +- balopat +- aaron-prindle +title: Установка Kubernetes с помощью Minikube +weight: 30 +content_template: templates/concept +--- + +{{% capture overview %}} + +Minikube — это инструмент, позволяющий легко запускать Kubernetes на локальной машине. Для тех, кто хочет попробовать Kubernetes или рассмотреть возможность его использования в повседневной разработке, Minikube станет отличным вариантом, потому что он запускает одноузловой кластер Kubernetes внутри виртуальной машины (VM) на компьютере пользователя. + +{{% /capture %}} + +{{% capture body %}} + +## Возможности Minikube + +Minikube поддерживает следующие возможности Kubernetes: + +* DNS +* Сервисы NodePort +* Словари конфигурации (ConfigMaps) и секреты (Secrets) +* Панель управления (Dashboard) +* Среда выполнения контейнера: Docker, [CRI-O](https://cri-o.io/) и [containerd](https://github.com/containerd/containerd) +* Поддержка CNI (Container Network Interface) +* Ingress + +## Установке + +Посмотрите страницу [Установка Minikube](/ru/docs/tasks/tools/install-minikube/). + +## Краткое руководство + +Эта простая демонстрация поможет запустить, использовать и удалить Minikube на локальной машине. Следуйте перечисленным ниже шагам, чтобы начать знакомство с Minikube. + +1. Запустите Minikube и создайте кластер: + + ```shell + minikube start + ``` + + Вывод будет примерно следующим: + + ``` + Starting local Kubernetes cluster... + Running pre-create checks... + Creating machine... + Starting local Kubernetes cluster... + ``` + + Дополнительную информацию о запуске кластера в определенной версии Kubernetes, виртуальной машине или среде выполнения контейнера смотрите в разделе [Запуск кластера](#запуск-кластера). + +2. Теперь вы можете работать со своим кластером через CLI-инструмент kubectl. Для получения дополнительной информации смотрите раздел [Работа с кластером](#работа-с-кластером). + + Давайте создадим развёртывание (Deployment) в Kubernetes, используя существующий образ `echoserver`, представляющий простой HTTP-сервер, и сделаем его доступным на порту 8080 с помощью `--port`. + + ```shell + kubectl create deployment hello-minikube --image=k8s.gcr.io/echoserver:1.10 + ``` + + Вывод будет примерно следующим: + + ``` + deployment.apps/hello-minikube created + ``` + +3. Чтобы получить доступ к объекту Deployment `hello-minikube` извне, создайте объект сервиса (Service): + + ```shell + kubectl expose deployment hello-minikube --type=NodePort --port=8080 + ``` + + Опция `--type=NodePort` определяет тип сервиса. + + Вывод будет примерно следующим: + + ``` + service/hello-minikube exposed + ``` + +4. Под (Pod) `hello-minikube` теперь запущен, но нужно подождать, пока он начнёт функционировать, прежде чем обращаться к нему. + + Проверьте, что под работает: + + ```shell + kubectl get pod + ``` + + Если в столбце вывода `STATUS` выводится `ContainerCreating`, значит под все еще создается: + + ``` + NAME READY STATUS RESTARTS AGE + hello-minikube-3383150820-vctvh 0/1 ContainerCreating 0 3s + ``` + + Если в столбце `STATUS` указано `Running`, то под теперь в рабочем состоянии: + + ``` + NAME READY STATUS RESTARTS AGE + hello-minikube-3383150820-vctvh 1/1 Running 0 13s + ``` +5. Узнайте URL-адрес открытого (exposed) сервиса, чтобы просмотреть подробные сведения о сервисе: + + ```shell + minikube service hello-minikube --url + ``` +6. Чтобы ознакомиться с подробной информацией о локальном кластере, скопируйте и откройте полученный из вывода команды на предыдущем шаге URL-адрес в браузере. + + Вывод будет примерно следующим: + + ``` + Hostname: hello-minikube-7c77b68cff-8wdzq + + Pod Information: + -no pod information available- + + Server values: + server_version=nginx: 1.13.3 - lua: 10008 + + Request Information: + client_address=172.17.0.1 + method=GET + real path=/ + query= + request_version=1.1 + request_scheme=http + request_uri=http://192.168.99.100:8080/ + + Request Headers: + accept=*/* + host=192.168.99.100:30674 + user-agent=curl/7.47.0 + + Request Body: + -no body in request- + ``` + + Если сервис и кластер вам больше не нужны, их можно удалить. +7. Удалите сервис `hello-minikube`: + + ```shell + kubectl delete services hello-minikube + ``` + + Вывод будет примерно следующим: + + ``` + service "hello-minikube" deleted + ``` +8. Удалите развёртывание `hello-minikube`: + + ```shell + kubectl delete deployment hello-minikube + ``` + + Вывод будет примерно следующим: + + ``` + deployment.extensions "hello-minikube" deleted + ``` +9. Остановите локальный кластер Minikube: + ```shell + minikube stop + ``` + Вывод будет примерно следующим: + ``` + Stopping "minikube"... + "minikube" stopped. + ``` + Подробности смотрите в разделе [Остановка кластера](#остановка-кластера). +10. Удалите локальный кластер Minikube: + ```shell + minikube delete + ``` + + Вывод будет примерно следующим: + + ``` + Deleting "minikube" ... + The "minikube" cluster has been deleted. + ``` + Подробности смотрите в разделе [Удаление кластера](#удаление-кластера). + +## Управление кластером + +### Запуск кластера + +Команда `minikube start` используется для запуска кластера. +Эта команда создаёт и конфигурирует виртуальную машину, которая запускает одноузловой кластер Kubernetes. +Эта команда также настраивает вашу установку [kubectl](/docs/user-guide/kubectl-overview/) для взаимодействия с этим кластером. + +{{< note >}} +Если вы работаете из-под веб-прокси, вам нужно указать данные прокси в команде `minikube start`: + +```shell +https_proxy= minikube start --docker-env http_proxy= --docker-env https_proxy= --docker-env no_proxy=192.168.99.0/24 +``` + +К сожалению, установка переменных окружения не cработает. + +Minikube также создает контекст "minikube" и устанавливает его по умолчанию в kubectl. +Чтобы вернуться к этому контексту, выполните следующую команду: `kubectl config use-context minikube`. +{{< /note >}} + +#### Указание версии Kubernetes + +Вы можете указать используемую версию Kubernetes в Minikube, добавив параметр `--kubernetes-version` в команду `minikube start`. Например, чтобы запустить Minikube из-под версии {{< param "fullversion" >}}, вам нужно выполнить следующую команду: + +```shell +minikube start --kubernetes-version {{< param "fullversion" >}} +``` + +#### Указание драйвера виртуальной машины + +Вы можете изменить драйвер виртуальной машины, добавив флаг `--vm-driver=` в команду `minikube start`. + +Тогда команда будет выглядеть так: + +```shell +minikube start --vm-driver= +``` + +Minikube поддерживает следующие драйверы: + +{{< note >}} +Смотрите файл [DRIVERS](https://git.k8s.io/minikube/docs/drivers.md) для получения подробной информации о поддерживаемых драйверах и как устанавливать плагины. +{{< /note >}} + +* virtualbox +* vmwarefusion +* kvm2 ([установка драйвера](https://git.k8s.io/minikube/docs/drivers.md#kvm2-driver)) +* hyperkit ([установка драйвера](https://git.k8s.io/minikube/docs/drivers.md#hyperkit-driver)) +* hyperv ([установка драйвера](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#hyperv-driver)) +Обратите внимание, что указанный IP-адрес на этой странице является динамическим и может изменяться. Его можно получить с помощью `minikube ip`. +* vmware ([установка драйвера](https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#vmware-unified-driver)) (VMware unified driver) +* none (Запускает компоненты Kubernetes на хосте, а не на виртуальной машине. Использование этого драйвера требует использование Linux и установленного {{< glossary_tooltip term_id="docker" >}}.) + +{{< caution >}} +Если вы используете драйвер `none`, некоторые компоненты Kubernetes запускаются как привилегированные контейнеры, которые имеют побочные эффекты вне окружения Minikube. Эти побочные эффекты означают, что драйвер `none` не рекомендуется использовать в личных рабочих станций. +{{< /caution >}} + +#### Запуск кластера в других средах выполнения контейнеров + +Вы можете запустить Minikube в следующих средах выполнения контейнеров. + +{{< tabs name="container_runtimes" >}} +{{% tab name="containerd" %}} +Чтобы использовать [containerd](https://github.com/containerd/containerd) в качестве среды выполнения контейнера, выполните команду ниже: + +```bash +minikube start \ + --network-plugin=cni \ + --enable-default-cni \ + --container-runtime=containerd \ + --bootstrapper=kubeadm +``` + +Также можете использовать расширенную вариант команды: + +```bash +minikube start \ + --network-plugin=cni \ + --enable-default-cni \ + --extra-config=kubelet.container-runtime=remote \ + --extra-config=kubelet.container-runtime-endpoint=unix:///run/containerd/containerd.sock \ + --extra-config=kubelet.image-service-endpoint=unix:///run/containerd/containerd.sock \ + --bootstrapper=kubeadm +``` +{{% /tab %}} +{{% tab name="CRI-O" %}} +Чтобы использовать [CRI-O](https://cri-o.io/) в качестве среды выполнения контейнера, выполните команду ниже: + +```bash +minikube start \ + --network-plugin=cni \ + --enable-default-cni \ + --container-runtime=cri-o \ + --bootstrapper=kubeadm +``` + +Также можете использовать расширенную вариант команды: + +```bash +minikube start \ + --network-plugin=cni \ + --enable-default-cni \ + --extra-config=kubelet.container-runtime=remote \ + --extra-config=kubelet.container-runtime-endpoint=/var/run/crio.sock \ + --extra-config=kubelet.image-service-endpoint=/var/run/crio.sock \ + --bootstrapper=kubeadm +``` +{{% /tab %}} +{{< /tabs >}} + +#### Использование локальных образов путём повторного использования демона Docker + +При использовании одной виртуальной машины для Kubernetes легко повторно использовать демон Docker, встроенный в Minikube. В этом случае нет необходимости создавать реестр Docker на вашей хост-машине и отправлять образ туда. Вместо этого вы можете создать реестр внутри того же демона Docker, который использует Minikube, что позволит ускорить локальные запуски. + +{{< note >}} +Обязательно пометьте собственным тегом Docker-образ, и затем при получении образа всегда указывайте его. Так как `:latest` — это тег по умолчанию, поэтому наряду с соответствующей стандартной политикой получения образа, равной `Always`, в конечном итоге возникнет ошибка при получении образа (`ErrImagePull`), если Docker-образ не найден в базовом реестре Docker (как правило, в DockerHub). +{{< /note >}} + +Для работы с Docker-демоном на вашем хосте под управлением Mac/Linux, запустите последнюю строку из вывода команды `minikube docker-env`. + +Теперь вы можете использовать Docker в командной строке вашего хост-компьютера на Mac/Linux для взаимодействия с демоном Docker внутри виртуальной машины Minikube: + +```shell +docker ps +``` + +{{< note >}} +На Centos 7 Docker может возникнуть следующая ошибка: + +``` +Could not read CA certificate "/etc/docker/ca.pem": open /etc/docker/ca.pem: no such file or directory +``` + +Для исправления этой ошибки обновите файл `/etc/sysconfig/docker`, чтобы учитывались изменения в среде Minikube: + +```shell +< DOCKER_CERT_PATH=/etc/docker +--- +> if [ -z "${DOCKER_CERT_PATH}" ]; then +> DOCKER_CERT_PATH=/etc/docker +> fi +``` +{{< /note >}} + +### Конфигурация Kubernetes + +Minikube имеет такую возможность как "конфигуратор" ("configurator"), позволяющая пользователям настраивать компоненты Kubernetes произвольными значениями. +Чтобы использовать эту возможность, используйте флаг `--extra-config` в команде `minikube start`. + +Этот флаг можно дублировать, поэтому вы можете указать его несколько раз с несколькими разными значениями, чтобы установить несколько опций. + +Этот флаг принимает строку вида `component.key=value`, где `component` — это одно из значение в приведённом ниже списка, `key` — ключ из структуры конфигурации, а `value` — значение, которое нужно установить. + +Допустимые ключи можно найти в документации по `componentconfigs` в Kubernetes каждого компонента. +Ниже вы найдете документации по каждой поддерживаемой конфигурации: + +* [kubelet](https://godoc.org/k8s.io/kubernetes/pkg/kubelet/apis/config#KubeletConfiguration) +* [apiserver](https://godoc.org/k8s.io/kubernetes/cmd/kube-apiserver/app/options#ServerRunOptions) +* [proxy](https://godoc.org/k8s.io/kubernetes/pkg/proxy/apis/config#KubeProxyConfiguration) +* [controller-manager](https://godoc.org/k8s.io/kubernetes/pkg/controller/apis/config#KubeControllerManagerConfiguration) +* [etcd](https://godoc.org/github.com/coreos/etcd/etcdserver#ServerConfig) +* [scheduler](https://godoc.org/k8s.io/kubernetes/pkg/scheduler/apis/config#KubeSchedulerConfiguration) + +#### Примеры + +Чтобы изменить настройку `MaxPods` на значение 5 в Kubelet, передайте этот флаг `--extra-config=kubelet.MaxPods=5`. + +Эта возможность также поддерживает вложенные структуры. Для изменения настройки `LeaderElection.LeaderElect` на значение `true` в планировщике, передайте флаг `--extra-config=scheduler.LeaderElection.LeaderElect=true`. + +Чтобы изменить настройку `AuthorizationMode` в `apiserver` на значение `RBAC`, используйте флаг `--extra-config=apiserver.authorization-mode=RBAC`. + +### Остановка кластера +Команда `minikube stop` используется для остановки кластера. +Эта команда выключает виртуальную машины Minikube, но сохраняет всё состояние кластера и данные. +Повторный запуск кластера вернет его в прежнее состояние. + +### Удаление кластера +Команда `minikube delete` используется для удаления кластера. +Эта команда выключает и удаляет виртуальную машину Minikube. +Данные или состояние не сохраняются. + +### Обновление minikube +Смотрите [инструкцию по обновлению minikube](https://minikube.sigs.k8s.io/docs/start/macos/). + +## Работа с кластером + +### Kubectl + +Команда `minikube start` создает [контекст kubectl](/docs/reference/generated/kubectl/kubectl-commands#-em-set-context-em-) под именем "minikube". +Этот контекст содержит конфигурацию для взаимодействия с кластером Minikube. + +Minikube автоматически устанавливает этот контекст, но если вам потребуется явно использовать его в будущем, выполните команду ниже: + +```shell +kubectl config use-context minikube +``` + +Либо передайте контекст при выполнении команды следующим образом: `kubectl get pods --context=minikube`. + +### Панель управления + +Чтобы получить доступ к [панели управления Kubernetes](/docs/tasks/access-application-cluster/web-ui-dashboard/), запустите эту команду в командной оболочке после запуска Minikube, чтобы получить адрес: + +```shell +minikube dashboard +``` + +### Сервисы + +Чтобы получить доступ к сервису, открытой через порт узла, выполните команду в командной оболочке после запуска Minikube, чтобы получить адрес: + +```shell +minikube service [-n NAMESPACE] [--url] NAME +``` + +## Организация сети + +Виртуальная машина Minikube доступна только хост-системе через IP-адрес, который можно получить с помощью команды `minikube ip`. +Вы можете использовать IP-адрес для доступа к любому сервису типа `NodePort`. + +Чтобы определить NodePort для вашего сервиса, вы можете использовать такую команду `kubectl`: + +```shell +kubectl get service $SERVICE --output='jsonpath="{.spec.ports[0].nodePort}"' +``` + +## Постоянные тома + +Minikube поддерживает [PersistentVolumes](/docs/concepts/storage/persistent-volumes/) типа `hostPath`. +Эти постоянные тома монтируются в виртуальную машину Minikube. + +Виртуальная машина Minikube загружается в файловую систему tmpfs, поэтому большинство директорий не будет сохранено при перезагрузках (`minikube stop`). +Однако Minikube сконфигурирован на сохранение файлов, хранящихся в перечисленных ниже директорий хоста. + +* `/data` +* `/var/lib/minikube` +* `/var/lib/docker` + +Пример конфигурации PersistentVolume для сохранения данных в директории `/data`: + +```yaml +apiVersion: v1 +kind: PersistentVolume +metadata: + name: pv0001 +spec: + accessModes: + - ReadWriteOnce + capacity: + storage: 5Gi + hostPath: + path: /data/pv0001/ +``` + +## Смонтированные директории хоста +Некоторые драйверы монтируют директорию хоста в виртуальную машину, чтобы можно было легко обмениваться файлами между виртуальной машиной и хостом. В настоящее время это не настраивается и отличается от используемого драйвера и ОС. + +{{< note >}} +Совместное использование директории хоста еще не реализовано в драйвере KVM. +{{< /note >}} + +| Driver | OS | HostFolder | VM | +|---------------|---------|------------|-----------------| +| VirtualBox | Linux | /home | /hosthome | +| VirtualBox | macOS | /Users | /Users | +| VirtualBox | Windows | C://Users | /c/Users | +| VMware Fusion | macOS | /Users | /mnt/hgfs/Users | +| Xhyve | macOS | /Users | /Users | + +## Приватные реестры контейнеров + +Для доступа к реестру приватных контейнеров, выполните шаги, описанные на [этой странице](/docs/concepts/containers/images/). + +Мы рекомендуем использовать `ImagePullSecrets`, но если вам нужно обратиться к нему из виртуальной машины Minikube, нужно поместить файл `.dockercfg` в директорию `/home/docker` или `config.json` в директорию `/home/docker/.docker`. + +## Дополнения + +Для того, чтобы Minikube смог запустить или перезапустить пользовательские дополнения, поместите дополнения, которые вы хотите запускать с помощью Minikube, в директорию `~/.minikube/addons`. Дополнения в этой директории будут перемещены в виртуальную машину Minikube и запускаться каждый раз при запуске или перезапуске Minikube. + +## Использование Minikube с помощью HTTP-прокси + +Minikube создаёт виртуальную машину, включающая в себя Kubernetes и демон Docker. +Когда Kubernetes планирует выполнение контейнеров с использованием Docker, демону Docker может потребоваться доступ к внешней сети для получения контейнеров. + +Если вы работаете через HTTP-прокси, вам нужно сконфигурировать настройки прокси для Docker. +Для этого нужно передать необходимые переменные окружения в флаги перед выполнением команды `minikube start`. + +Например: + +```shell +minikube start --docker-env http_proxy=http://$YOURPROXY:PORT \ + --docker-env https_proxy=https://$YOURPROXY:PORT +``` + +Если адрес вашей виртуальной машины 192.168.99.100, то, скорее всего, настройки прокси помешают `kubectl` обратиться к ней. +Чтобы прокси игнорировал этот IP-адрес, нужно скорректировать настройки no_proxy следующим образом: + +```shell +export no_proxy=$no_proxy,$(minikube ip) +``` + +## Известные проблемы + +Функциональность, для которой требуется несколько узлов, не будет работать в Minikube. + +## Реализация + +Minikube использует [libmachine](https://github.com/docker/machine/tree/master/libmachine) для подготовки виртуальных машин и [kubeadm](https://github.com/kubernetes/kubeadm) для инициализации кластера Kubernetes. + +Для получения дополнительной информации о Minikube посмотрите [статью](https://git.k8s.io/community/contributors/design-proposals/cluster-lifecycle/local-cluster-ux.md). + +## Дополнительные ссылки + +* **Цели**: цели проекта Minikube смотрите в [дорожной карте](https://git.k8s.io/minikube/docs/contributors/roadmap.md). +* **Руководство по разработке**: посмотрите [CONTRIBUTING.md](https://git.k8s.io/minikube/CONTRIBUTING.md), чтобы ознакомиться с тем, как отправлять пулрексты. +* **Сборка Minikube**: инструкции по сборке/тестированию Minikube из исходного кода смотрите в [руководстве по сборке](https://git.k8s.io/minikube/docs/contributors/build_guide.md). +* **Добавление новой зависимости**: инструкции по добавлению новой зависимости в Minikube смотрите в [руководстве по добавлению зависимостей](https://git.k8s.io/minikube/docs/contributors/adding_a_dependency.md). +* **Добавление нового дополнения**: инструкции по добавлению нового дополнения для Minikube смотрите в [руководстве по добавлению дополнений](https://git.k8s.io/minikube/docs/contributors/adding_an_addon.md). +* **MicroK8**: пользователи Linux, которые не хотят использовать виртуальную машину, могут в качестве альтернативы посмотреть в сторону [MicroK8s](https://microk8s.io/). + +## Сообщество + +Помощь, вопросы и комментарии приветствуются и поощряются! Разработчики Minikube проводят время на [Slack](https://kubernetes.slack.com) в канале #minikube (получить приглашение можно [здесь](http://slack.kubernetes.io/)). У нас также есть [список рассылки kubernetes-dev на Google Groups](https://groups.google.com/forum/#!forum/kubernetes-dev). Если вы отправляете сообщение в список, пожалуйста, начните вашу тему с "minikube: ". + +{{% /capture %}} diff --git a/content/ru/docs/tasks/tools/_index.md b/content/ru/docs/tasks/tools/_index.md new file mode 100755 index 0000000000..976aeed7a8 --- /dev/null +++ b/content/ru/docs/tasks/tools/_index.md @@ -0,0 +1,5 @@ +--- +title: "Установка инструментов" +weight: 10 +--- + diff --git a/content/ru/docs/tasks/tools/install-kubectl.md b/content/ru/docs/tasks/tools/install-kubectl.md new file mode 100644 index 0000000000..0e40eec3b3 --- /dev/null +++ b/content/ru/docs/tasks/tools/install-kubectl.md @@ -0,0 +1,485 @@ +--- +reviewers: +- mikedanese +title: Установка и настройка kubectl +content_template: templates/task +weight: 10 +card: + name: tasks + weight: 20 + title: Установка kubectl +--- + +{{% capture overview %}} +Инструмент командной строки Kubernetes [kubectl](/docs/user-guide/kubectl/) позволяет запускать команды для кластеров Kubernetes. Вы можете использовать kubectl для развертывания приложений, проверки и управления ресурсов кластера, а также для просмотра логов. Полный список операций kubectl смотрите в [Overview of kubectl](/docs/reference/kubectl/overview/). +{{% /capture %}} + +{{% capture prerequisites %}} +Используемая вами мажорная версия kubectl не должна отличаться от той, которая используется в кластере. Например, версия v1.2 может работать с версиями v1.1, v1.2 и v1.3. Использование последней версии kubectl поможет избежать непредвиденных проблем. +{{% /capture %}} + +{{% capture steps %}} + +## Установка kubectl в Linux + +### Установка двоичного файла kubectl с помощью curl в Linux + +1. Загрузите последнюю версию с помощью команды: + + ``` + curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl + ``` + + Чтобы загрузить определенную версию, вставьте в фрагмент команды `$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)` нужную версию. + + Например, команда загрузки версии {{< param "fullversion" >}} для Linux будет выглядеть следующим образом: + + ``` + curl -LO https://storage.googleapis.com/kubernetes-release/release/{{< param "fullversion" >}}/bin/linux/amd64/kubectl + ``` + +2. Сделайте двоичный файл kubectl исполняемым: + + ``` + chmod +x ./kubectl + ``` + +3. Переместите двоичный файл в директорию из переменной окружения PATH: + + ``` + sudo mv ./kubectl /usr/local/bin/kubectl + ``` +4. Убедитесь, что установлена последняя версия: + + ``` + kubectl version --client + ``` + +### Установка с помощью встроенного пакетного менеджера + +{{< tabs name="kubectl_install" >}} +{{< tab name="Ubuntu, Debian или HypriotOS" codelang="bash" >}}sudo apt-get update && sudo apt-get install -y apt-transport-https +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 >}} + +### Установка с помощью стороннего пакетного менеджера + +{{< tabs name="other_kubectl_install" >}} +{{% tab name="Snap" %}} +Если вы используйте Ubuntu или другой Linux-дистрибутив, в котором есть пакетный менеджер [snap](https://snapcraft.io/docs/core/install), kubectl доступен в виде приложения [snap](https://snapcraft.io/). + +```shell +snap install kubectl --classic + +kubectl version +``` +{{% /tab %}} +{{% tab name="Homebrew" %}} +Если вы работаете в Linux и используете пакетный менеджер [Homebrew](https://docs.brew.sh/Homebrew-on-Linux), то kubectl можно [установить](https://docs.brew.sh/Homebrew-on-Linux#install) через него. + +```shell +brew install kubectl + +kubectl version +``` +{{% /tab %}} +{{< /tabs >}} + +## Установка kubectl в macOS + +### Установка двоичного файла kubectl с помощью curl в macOS + +1. Загрузите последнюю версию: + + ``` + curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/darwin/amd64/kubectl" + ``` + + Чтобы загрузить определенную версию, вставьте в фрагмент команды `$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)` нужную версию. + + Например, команда загрузки версии {{< param "fullversion" >}} для macOS будет выглядеть следующим образом: + + ``` + curl -LO https://storage.googleapis.com/kubernetes-release/release/{{< param "fullversion" >}}/bin/darwin/amd64/kubectl + ``` + +2. Сделайте двоичный файл kubectl исполняемым: + + ``` + chmod +x ./kubectl + ``` + +3. Переместите двоичный файл в директорию из переменной окружения PATH: + + ``` + sudo mv ./kubectl /usr/local/bin/kubectl + ``` + +4. Убедитесь, что установлена последняя версия: + + ``` + kubectl version --client + ``` + +### Установка с помощью Homebrew в macOS + +Если вы используете macOS и [Homebrew](https://brew.sh/), то kubectl можно установить с помощью пакетного менеджера Homebrew. + +1. Выполните команду установки: + + ``` + brew install kubectl + ``` + + Или: + + ``` + brew install kubernetes-cli + ``` + +2. Убедитесь, что установлена последняя версия: + + ``` + kubectl version --client + ``` + +### Установка с помощью Macports в macOS + +Если вы используйте macOS и [Macports](https://macports.org/), то kubectl можно установить с помощью пакетного менеджера Macports. + +1. Выполните команду установки: + + ``` + sudo port selfupdate + sudo port install kubectl + ``` + +2. Убедитесь, что установлена последняя версия: + + ``` + kubectl version --client + ``` + +## Установка kubectl в Windows + +### Установка двоичного файла kubectl с помощью curl в Windows + +1. Загрузите последнюю версию {{< param "fullversion" >}} по [этой ссылке](https://storage.googleapis.com/kubernetes-release/release/{{< param "fullversion" >}}/bin/windows/amd64/kubectl.exe). + + Либо, если у вас установлен `curl`, выполните команду ниже: + + ``` + curl -LO https://storage.googleapis.com/kubernetes-release/release/{{< param "fullversion" >}}/bin/windows/amd64/kubectl.exe + ``` + + Последнюю стабильную версию (например, при написании скриптов) вы можете узнать из файла по ссылке [https://storage.googleapis.com/kubernetes-release/release/stable.txt](https://storage.googleapis.com/kubernetes-release/release/stable.txt). + +2. Переместите двоичный файл в директорию из переменной окружения PATH: +3. Убедитесь, что версия `kubectl` совпадает загружённой: + + ``` + kubectl version --client + ``` +{{< note >}} + +[Docker Desktop for Windows](https://docs.docker.com/docker-for-windows/#kubernetes) добавляет собственную версию `kubectl` в переменную окружения `PATH`. +Если у вас установлен Docker Desktop, вам придётся поместить путь к установленному двоичному файлу перед записью, добавленной установщиком Docker Desktop, либо же удалить вовсе `kubectl`, поставляемый вместе с Docker Desktop. +{{< /note >}} + +### Установка с помощью Powershell из PSGallery + +Если вы работаете в Windows и используете менеджер пакетов [Powershell Gallery](https://www.powershellgallery.com/), вы можете установить и обновить kubectl с помощью Powershell. + +1. Выполните команды по установке (обязательно укажите `DownloadLocation`): + + ``` + Install-Script -Name install-kubectl -Scope CurrentUser -Force + install-kubectl.ps1 [-DownloadLocation ] + ``` + + {{< note >}}Если вы не укажете `DownloadLocation`, то `kubectl` будет установлен во временную директорию пользователя.{{< /note >}} + + Установщик создаст `$HOME/.kube` вместе с конфигурационным файлом. + +2. Убедитесь, что установлена последняя версия: + + ``` + kubectl version --client + ``` + + {{< note >}}Обновить kubectl можно путём выполнения двух команд, перечисленных в шаге 1.{{< /note >}} + +### Установка в Windows с помощью Chocolatey или Scoop + +Для установки kubectl в Windows вы можете использовать либо менеджер пакетов [Chocolatey](https://chocolatey.org) , либо установщик в командной строке [Scoop](https://scoop.sh). + +{{< tabs name="kubectl_win_install" >}} +{{% tab name="choco" %}} + + choco install kubernetes-cli + +{{% /tab %}} +{{% tab name="scoop" %}} + + scoop install kubectl + +{{% /tab %}} +{{< /tabs >}} +2. Убедитесь, что установлена последняя версия: + + ``` + kubectl version --client + ``` + +3. Перейдите в домашнюю директорию: + + ``` + cd %USERPROFILE% + ``` + +4. Создайте директорию `.kube`: + + ``` + mkdir .kube + ``` + +5. Перейдите в созданную только что директорию `.kube`: + + ``` + cd .kube + ``` + +6. Настройте kubectl, чтобы возможно было использовать удаленный кластер Kubernetes: + + ``` + New-Item config -type file + ``` + + {{< note >}}Отредактируйте конфигурационный файл, используя ваш любимый текстовый редактор или обычный Notepad.{{< /note >}} + +## Установка kubectl из SDK Google Cloud + +Вы можете использовать kubectl из SDK Google Cloud, который использует этот CLI-инструмент. + +1. Установите [Google Cloud SDK](https://cloud.google.com/sdk/). +2. Выполните команду для установки `kubectl`: + + ``` + gcloud components install kubectl + ``` + +3. Убедитесь, что установлена последняя версия: + + ``` + kubectl version --client + ``` + +## Проверка конфигурации kubectl + +Чтобы kubectl мог найти и получить доступ к кластеру Kubernetes, нужен [файл kubeconfig](/docs/tasks/access-application-cluster/configure-access-multiple-clusters/), который создаётся автоматически при создании кластера с помощью скрипта [kube-up.sh](https://github.com/kubernetes/kubernetes/blob/master/cluster/kube-up.sh) или при успешном развертывании кластера Minikube. По умолчанию конфигурация kubectl находится в `~/.kube/config`. + +Посмотрите на состояние кластера, чтобы убедиться, что kubectl правильно сконфигурирован: + +```shell +kubectl cluster-info +``` + +Если вы видите URL-ответ, значит kubectl корректно настроен для работы с вашим кластером. + +Если вы видите сообщение следующего содержания, то значит kubectl настроен некорректно или не может подключиться к кластеру Kubernetes: + +```shell +The connection to the server was refused - did you specify the right host or port? +``` + +Например, если вы собираетесь запустить кластер Kubernetes на своем ноутбуке (локально), вам потребуется сначала установить специальный для этого инструмент, например Minikube, а затем снова выполнить указанные выше команды. + +Если команда `kubectl cluster-info` возвращает URL-ответ, но вы не можете подключиться к своему кластеру, чтобы убедиться, что он правильно настроен, воспользуйтесь этой командой: + +```shell +kubectl cluster-info dump +``` + +## Дополнительная конфигурация kubectl + +### Включение автодополнения ввода shell + +kubectl поддерживает автодополнение (автозаполнение) ввода в Bash и Zsh, которое сэкономит вам много времени на набор команд. + +Ниже приведены инструкции по настройке автодополнения для Bash (для Linux и macOS) и Zsh. + +{{< tabs name="kubectl_autocompletion" >}} + +{{% tab name="Bash в Linux" %}} + +### Основные сведения + +Скрипт дополнения ввода kubectl для Bash может быть сгенерирован с помощью команды `kubectl completion bash`. Подключение скрипта дополнения ввода в вашу оболочку включает поддержку автозаполнения ввода для kubectl. + +Однако скрипт дополнения ввода зависит от [**bash-completion**](https://github.com/scop/bash-completion), поэтому вам нужно сначала установить этот пакет (вы можете выполнить команду `type _init_completion`, чтобы проверить, установлен ли у вас уже bash-completion). + +### Установка bash-completion + +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`. + +Чтобы убедиться, что этот скрипт выполняется, перезагрузите оболочку и выполните команду `type _init_completion`. Если команда отработала успешно, установка сделана правильно, в противном случае добавьте следующее содержимое в файл `~/.bashrc`: + +```shell +source /usr/share/bash-completion/bash_completion +``` + +Перезагрузите вашу оболочку и убедитесь, что bash-completion правильно установлен, напечатав в терминале `type _init_completion`. + +### Включение автодополнения ввода kubectl + +Теперь нужно убедиться, что скрипт дополнения ввода kubectl выполняется во всех сессиях командной оболочки. Есть два способа сделать это: + +- Добавьте запуск скрипта дополнения ввода в файл `~/.bashrc`: + + ```shell + echo 'source <(kubectl completion bash)' >>~/.bashrc + ``` + +- Добавьте скрипт дополнения ввода в директорию `/etc/bash_completion.d`: + + ```shell + kubectl completion bash >/etc/bash_completion.d/kubectl + ``` + +- Если у вас определён псевдоним для kubectl, вы можете интегрировать его с автодополнением оболочки: + + ```shell + echo 'alias k=kubectl' >>~/.bashrc + echo 'complete -F __start_kubectl k' >>~/.bashrc + ``` + +{{< note >}} +Все скрипты дополнения ввода bash-completion находятся в `/etc/bash_completion.d`. +{{< /note >}} + +Оба подхода эквивалентны. После перезагрузки вашей оболочки, должны появляться дополнения ввода kubectl. + +{{% /tab %}} + + +{{% tab name="Bash в macOS" %}} + + +### Основные сведения + +Скрипт дополнения ввода kubectl для Bash может быть сгенерирован с помощью команды `kubectl completion bash`. Подключение скрипта дополнения ввода в вашей оболочке включает поддержку автозаполнения ввода для kubectl. + +Однако скрипт дополнения ввода kubectl зависит от пакета [**bash-completion**](https://github.com/scop/bash-completion), который первым делом нужно установить. + +{{< warning>}} +Есть две версии bash-completion: первая (v1) и вторая (v2). Первая предназначена для Bash 3.2 (который используется по умолчанию в macOS), а вторая — для Bash 4.1+. Скрипт дополнения ввода kubectl **не работает** корректно с bash-completion v1 и Bash 3.2. Требуется **bash-completion v2** и **Bash 4.1+**. Таким образом, чтобы правильно использовать дополнение kubectl в macOS, вам нужно установить и использовать Bash 4.1+ ([*инструкции по обновлению*](https://itnext.io/upgrading-bash-on-macos-7138bd1066ba)). Последующие шаги предполагают, что вы используете Bash 4.1+ (то есть любую версию Bash 4.1 или более новую). +{{< /warning >}} + + +### Установка bash-completion + +{{< note >}} +Как уже упоминалось, в этих инструкциях предполагается, что вы используете Bash 4.1+, поэтому вы устанавливаете bash-completion v2 (а не Bash 3.2 и bash-completion v1, в таком случае дополнение ввода kubectl не будет работать). +{{< /note >}} + +Вы можете проверить, установлен ли у вас bash-completion v2, набрав команду `type _init_completion`. Если он не установлен, вы можете сделать это с помощью Homebrew: + +```shell +brew install bash-completion@2 +``` + +Как указано в выводе этой команды, добавьте следующий код в файл `~/.bashrc`: + +```shell +export BASH_COMPLETION_COMPAT_DIR="/usr/local/etc/bash_completion.d" +[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh" +``` + +Перезагрузите вашу командную оболочку и убедитесь, что bash-completion v2 корректно установлен, напечатав в терминале `type _init_completion`. + +### Включение автодополнения ввода kubectl + +Теперь нужно убедиться, что скрипт дополнения ввода kubectl выполняется во всех сессиях командной оболочки. Есть два способа сделать это: + +- Добавьте запуск скрипта дополнения ввода в файл `~/.bashrc`: + + ```shell + echo 'source <(kubectl completion bash)' >>~/.bashrc + ``` + +- Добавьте скрипт дополнения ввода в директорию `/etc/bash_completion.d`: + + ```shell + kubectl completion bash >/usr/local/etc/bash_completion.d/kubectl + ``` + +- Если у вас определён псевдоним для kubectl, вы можете интегрировать его с автодополнением оболочки: + + ```shell + echo 'alias k=kubectl' >>~/.bashrc + echo 'complete -F __start_kubectl k' >>~/.bashrc + ``` + +Если вы установили kubectl с помощью Homebrew (как описано [выше](#install-with-homebrew-on-macos)), то скрипт дополнения ввода kubectl уже должен быть находится в `/usr/local/etc/bash_completion.d/kubectl`. В этом случае вам не нужно ничего делать. + +{{< note >}} +Homebrew устанавливает bash-completion v2 в директорию `BASH_COMPLETION_COMPAT_DIR`, что делает рабочими два метода. +{{< /note >}} + +Какой вариант бы вы не выбрали, после перезагрузки командной оболочки, дополнение ввода kubectl должно заработать. +{{% /tab %}} + +{{% tab name="Zsh" %}} + +Скрипт дополнения ввода kubectl для Zsh может быть сгенерирован с помощью команды `kubectl completion zsh`. Подключение скрипта дополнения ввода в вашу оболочку включает поддержку автозаполнения ввода для kubectl. + +Чтобы подключить его во все сессии командной оболочки, добавьте следующую строчку в файл `~/.zshrc`: + +```shell +source <(kubectl completion zsh) +``` + +Если у вас определён псевдоним для kubectl, вы можете интегрировать его с автодополнением оболочки: + +```shell +echo 'alias k=kubectl' >>~/.zshrc +echo 'complete -F __start_kubectl k' >>~/.zshrc +``` + +После перезагрузки командной оболочки должны появляться дополнения ввода kubectl. + +Если появляется такая ошибка как `complete:13: command not found: compdef`, то добавьте следующее содержимое в начало вашего файла `~/.zshrc`: + +```shell +autoload -Uz compinit +compinit +``` +{{% /tab %}} +{{< /tabs >}} + +{{% /capture %}} + +{{% capture whatsnext %}} +* [Установка Minikube](/ru/docs/tasks/tools/install-minikube/) +* Смотрите [руководства по установке](/docs/setup/), чтобы узнать больше про создание кластеров. +* [Learn how to launch and expose your application.](/docs/tasks/access-application-cluster/service-access-application-cluster/) +* Если у вас нет доступа к кластеру, который не создавали, посмотрите страницу [Совместный доступ к кластеру](/docs/tasks/access-application-cluster/configure-access-multiple-clusters/). +* Read the [kubectl reference docs](/docs/reference/kubectl/kubectl/) +{{% /capture %}} diff --git a/content/ru/docs/tasks/tools/install-minikube.md b/content/ru/docs/tasks/tools/install-minikube.md new file mode 100644 index 0000000000..64fca93399 --- /dev/null +++ b/content/ru/docs/tasks/tools/install-minikube.md @@ -0,0 +1,255 @@ +--- +title: Установка Minikube +content_template: templates/task +weight: 20 +card: + name: tasks + weight: 10 +--- + +{{% capture overview %}} + +На этой странице рассказано, как установить [Minikube](/ru/docs/tutorials/hello-minikube), инструмент для запуска одноузлового кластера Kubernetes на виртуальной машине в персональном компьютере. + +{{% /capture %}} + +{{% capture prerequisites %}} + +{{< tabs name="minikube_before_you_begin" >}} +{{% tab name="Linux" %}} +Чтобы проверить, поддерживается ли виртуализация в Linux, выполните следующую команду и проверьте, что вывод не пустой: +``` +grep -E --color 'vmx|svm' /proc/cpuinfo +``` +{{% /tab %}} + +{{% tab name="macOS" %}} +Чтобы проверить, поддерживается ли виртуализация в macOS, выполните следующую команду в терминале: +``` +sysctl -a | grep -E --color 'machdep.cpu.features|VMX' +``` +Если вы видите `VMX` в выводе (должен быть окрашенным), значит в вашем компьютере поддерживается виртуализация VT-x. +{{% /tab %}} + +{{% tab name="Windows" %}} +Чтобы проверить, поддерживается ли виртуализация в Windows 8 и выше, выполните следующую команду в Windows Terminal или в командной строке. +``` +systeminfo +``` +Если вы видите следующий вывод, значит виртуализация поддерживается в Windows. +``` +Hyper-V Requirements: VM Monitor Mode Extensions: Yes + Virtualization Enabled In Firmware: Yes + Second Level Address Translation: Yes + Data Execution Prevention Available: Yes +``` +Если вы видите следующий вывод, значит системе уже установлен гипервизор, значит вы можете пропустить следующий шаг установке гипервизора. +``` +Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed. +``` + +{{% /tab %}} +{{< /tabs >}} + +{{% /capture %}} + +{{% capture steps %}} + +# Установка minikube + +{{< tabs name="tab_with_md" >}} +{{% tab name="Linux" %}} + +### Установка kubectl + +Убедитесь, что у вас установлен kubectl. Вы можете установить kubectl согласно инструкциям в разделе [Установка и настройка kubectl](/docs/tasks/tools/install-kubectl/#install-kubectl-on-linux). + +### Установка Hypervisor + +Если у вас ещё не установлен гипервизор, установите один из них: + +• [KVM](https://www.linux-kvm.org/), который также использует QEMU + +• [VirtualBox](https://www.virtualbox.org/wiki/Downloads) + +Minikube также поддерживает опцию `--vm-driver=none`, которая запускает компоненты Kubernetes на хосте, а не на виртуальной машине. +Для использования этого драйвера требуется только [Docker](https://www.docker.com/products/docker-desktop) и Linux, но не гипервизор. + +Если вы используете драйвер `none` в Debian и его производных, используйте пакеты `.deb` для Docker, а не snap-пакет, который не работает с Minikube. +Вы можете скачать `.deb`-пакеты с сайта [Docker](https://www.docker.com/products/docker-desktop). + +{{< caution >}} +Драйвера виртуальной машины `none` может привести к проблемам безопасности и потери данных. Перед использованием `--vm-driver=none` обратитесь к [этой документации](https://minikube.sigs.k8s.io/docs/reference/drivers/none/) для получения дополнительной информации. +{{< /caution >}} + +Minikube также поддерживает `vm-driver=podman`, похожий на драйвер Docker. Podman, работающий с правами суперпользователя (пользователь root) — это лучший способ гарантировать вашим контейнерам полный доступ ко всем возможностям в системе. + +{{< caution >}} +Драйвер `podman` должен запускать контейнеры от имени суперпользователя, поскольку у обычных аккаунтов нет полного доступа ко всем возможностям операционной системы, которые могут понадобиться контейнерам для работы. +{{< /caution >}} + +### Установка Minikube через пакет + +Доступны *экспериментальные* пакеты для Minikube; Вы можете загрузить пакеты для Linux (AMD64) со страницы [релизов](https://github.com/kubernetes/minikube/releases) Minikube на GitHub. + +Используйте пакетный менеджер в вашем дистрибутиве Linux для установки нужного пакета. + +### Установка Minikube с помощью прямой ссылки + +Вы также можете загрузить двоичный файл и использовать его вместо установки пакета: + +```shell +curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 \ + && chmod +x minikube +``` + +Чтобы исполняемый файл Minikube был доступен из любой директории выполните следующие команды: + +```shell +sudo mkdir -p /usr/local/bin/ +sudo install minikube /usr/local/bin/ +``` + +### Установка Minikube через Homebrew + +В качестве ещё одной альтернативы вы можете установить Minikube с помощью Linux [Homebrew](https://docs.brew.sh/Homebrew-on-Linux): + +```shell +brew install minikube +``` + +{{% /tab %}} +{{% tab name="macOS" %}} +### Установка kubectl + +Убедитесь, что у вас установлен kubectl. Вы можете установить kubectl согласно инструкциям в разделе [Установка и настройка kubectl](/docs/tasks/tools/install-kubectl/#install-kubectl-on-macos). + +### Установка Hypervisor + +Если у вас ещё не установлен гипервизор, установите один из них: + +• [HyperKit](https://github.com/moby/hyperkit) + +• [VirtualBox](https://www.virtualbox.org/wiki/Downloads) + +• [VMware Fusion](https://www.vmware.com/products/fusion) + +### Установка Minikube +Простейший способ установить Minikube в macOS — использовать [Homebrew](https://brew.sh): + +```shell +brew install minikube +``` + +Вы также можете установить его в macOS, загрузив двоичный файл: + +```shell +curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-darwin-amd64 \ + && chmod +x minikube +``` + +Чтобы исполняемый файл Minikube был доступен из любой директории выполните следующие команды: + +```shell +sudo mv minikube /usr/local/bin +``` + +{{% /tab %}} +{{% tab name="Windows" %}} +### Установка kubectl + +Убедитесь, что у вас установлен kubectl. Вы можете установить kubectl согласно инструкциям в разделе [Установка и настройка kubectl](/docs/tasks/tools/install-kubectl/#install-kubectl-on-windows). + +### Установка Hypervisor + +Если у вас ещё не установлен гипервизор, установите один из них: + +• [Hyper-V](https://msdn.microsoft.com/en-us/virtualization/hyperv_on_windows/quick_start/walkthrough_install) + +• [VirtualBox](https://www.virtualbox.org/wiki/Downloads) + +{{< note >}} +Hyper-V может работать в трёх версиях Windows 10: Windows 10 Enterprise, Windows 10 Professional и Windows 10 Education. +{{< /note >}} + +### Установка Minikube с помощью Chocolatey + +Простейший способ установить Minikube в Windows — использовать [Chocolatey](https://chocolatey.org/) (запущенный с правами администратора): + +```shell +choco install minikube +``` + +После установки Minikube нужно перезапустить терминал. Minikube должен быть автоматически добавлен в директорию с исполняемыми файлами. + +### Установка Minikube с помощью исполняемого файла установки + +Для ручной установки Minikube в Windows с помощью [установщика Windows](https://docs.microsoft.com/en-us/windows/desktop/msi/windows-installer-portal), загрузите и запустите установщик [`minikube-installer.exe`](https://github.com/kubernetes/minikube/releases/latest/download/minikube-installer.exe). + +### Установка Minikube с помощью прямой ссылки + +Для ручной установки Minikube в Windows, загрузите [`minikube-windows-amd64`](https://github.com/kubernetes/minikube/releases/latest), переименуйте его в `minikube.exe` и добавьте его в директорию исполняемых файлов. + +{{% /tab %}} +{{< /tabs >}} + + +{{% /capture %}} + +{{% capture whatsnext %}} + +* [Running Kubernetes Locally via Minikube](/docs/setup/learning-environment/minikube/) + +{{% /capture %}} + +## Проверка установки + +Чтобы убедиться в том, что гипервизор и Minikube были установлены корректно, выполните следующую команду, которая запускает локальный кластер Kubernetes: + +{{< note >}} + +Для использования опции `--vm-driver` с командой `minikube start` укажите имя установленного вами гипервизора в нижнем регистре в заполнителе `` команды ниже. Полный список значений для опции `--vm-driver` перечислен в разделе по [указанию драйвера виртуальной машины](/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, то выполните следующую команду: +```shell +minikube start +``` + +В таком случае команда `minikube start` вернёт ошибку: +``` +machine does not exist +``` + +Чтобы исправить это, нужно очистить локальное состояние: +```shell +minikube delete +``` diff --git a/content/vi/community/_index.html b/content/vi/community/_index.html new file mode 100644 index 0000000000..142ee6477a --- /dev/null +++ b/content/vi/community/_index.html @@ -0,0 +1,236 @@ +--- +title: Community +layout: basic +cid: community +--- + +
    +
    + Thư viện ảnh hội nghị Kubernetes + Thư viện ảnh hội nghị Kubernetes +
    + +
    +
    +

    Cộng đồng Kubernetes -- người dùng, người đóng góp, và văn hóa chúng ta xây dựng cùng nhau -- là một trong những lý do lớn nhất cho sự gia tăng nhanh chóng của dự án nguồn mở này. Văn hóa và giá trị của chúng ta tiếp tục phát triển và thay đổi khi dự án thay đổi và phát triển. Chúng ta làm việc cùng nhau hướng tới việc cải tiến liên tục dự án và cách chúng ta làm việc với nó. +

    Chúng ta là những người phát hiện các vấn đề, và xử lý các yêu cầu, tham dự các buổi họp SIG, các Kubernetes meetup, và KubeCon, ủng hộ việc áp dụng và đổi mới, chạy kubectl get pods, và đóng góp trong một ngàn cách quan trọng khác nhau. Đọc để tìm hiểu làm thế nào bạn có thể tham gia và trở thành một phần của cộng đồng tuyệt vời này.

    +
    +
    + + +

    +
    +
    +
    + Thư viện ảnh hội nghị Kubernetes +
    + +
    + Thư viện ảnh hội nghị Kubernetes +
    + +
    + Thư viện ảnh hội nghị Kubernetes +
    + Thư viện ảnh hội nghị Kubernetes + + +
    + + + +
    +
    +

    +

    +

    Quy tắc ứng xử

    +Cộng đồng Kubernetes coi trọng sự tôn trọng và thực thi Quy tắc ứng xử trong tất cả các tương tác. Nếu bạn nhận thấy vi phạm Quy tắc ứng xử tại một sự kiện hoặc cuộc họp, trong Slack hoặc trong một cơ chế giao tiếp khác, hãy liên hệ với Ủy ban Quy tắc ứng xử Kubernetes tại conduct@kubernetes.io. Tất cả các báo cáo được giữ bí mật. Bạn có thể đọc về ủy ban ở đây. +
    + +

    + + +ĐỌC TIẾP + +
    +
    +
    +
    + + + +
    +

    +

    +

    Videos

    + +
    Chúng tôi đang ở trên YouTube, rất nhiều video. Đăng ký cho một loạt các chủ đề.
    + + +
    + + +
    +

    +

    +

    Thảo luận

    + +
    Chúng ta thảo luận rất nhiều. Tìm chúng tôi và tham gia cuộc trò chuyện trên bất kỳ  những nền tảng này.
    + +
    + +
    +Forum" + +forum ▶ + +
    +Các cuộc thảo luận kỹ thuật theo chủ đề có tài liệu kết nối, StackOverflow và  hơn nữa +
    +
    + +
    +Twitter + +twitter ▶ + +
    Thông báo thời gian thực của bài viết trên blog, sự kiện, tin tức, ý tưởng +
    +
    + +
    +GitHub + +github ▶ + +
    +Tất cả các dự án và theo dõi vấn đề, thêm cả mã khóa học +
    +
    + +
    +Stack Overflow + +stack overflow ▶ + +
    + Xử lý kỹ thuật for mọi  tình huống + +
    +
    + + + +
    +
    +
    +

    +

    +
    +

    Các sự kiện sắp tới

    + {{< upcoming-events >}} +
    +
    + +
    +
    +
    +

    Cộng đồng toàn cầu

    +Với hơn 150 meetup trên thế giới và đang phát triển, hãy đi tìm tại địa phương của bạn. Nếu không ở gần đó, hãy nhận chi phí và tạo của riêng bạn. +
    + +
    +TÌM MEETUP +
    +
    + +
    +
    + + + + +
    +

    +

    +

    Bản tin gần đây

    + +
    + + +
    +



    +
    + +
    diff --git a/content/vi/community/code-of-conduct.md b/content/vi/community/code-of-conduct.md new file mode 100644 index 0000000000..7dfdf3364e --- /dev/null +++ b/content/vi/community/code-of-conduct.md @@ -0,0 +1,26 @@ +--- +title: Community +layout: basic +cid: community +css: /css/community.css +--- + +
    +

    Quy tắc ứng xử cộng đồng Kubernetes

    + +Kubernetes tuân theo +quy tắc ứng xử CNCF. +Văn bản của CNCF CoC được sao chép dưới đây, kể từ +commit 214585e. +Nếu bạn nhận thấy rằng điều này đã lỗi thời, xin vui lòng +gửi một vấn đề. + +Nếu bạn nhận thấy vi phạm Quy tắc ứng xử tại một sự kiện hoặc cuộc họp, trong +Slack, hoặc trong một cơ chế giao tiếp khác, hãy liên lạc với Ủy ban Quy tắc ứng xử Kubernetes. +Bạn có thể liên hệ với chúng tôi qua email tại conduct@kubernetes.io. +Sự ẩn danh của bạn sẽ được bảo vệ. + +
    +{{< include "/static/cncf-code-of-conduct.md" >}} +
    +
    diff --git a/content/vi/community/static/README.md b/content/vi/community/static/README.md new file mode 100644 index 0000000000..94f742e750 --- /dev/null +++ b/content/vi/community/static/README.md @@ -0,0 +1 @@ +Tài liệu trong thư mục này được lấy từ nguồn khác. Vui lòng không trực tiếp sửa chúng, ngoại trừ việc thay thế chúng với phiên bản khác. \ No newline at end of file diff --git a/content/vi/community/static/cncf-code-of-conduct.md b/content/vi/community/static/cncf-code-of-conduct.md new file mode 100644 index 0000000000..9d7008e902 --- /dev/null +++ b/content/vi/community/static/cncf-code-of-conduct.md @@ -0,0 +1,31 @@ + +## Quy tắc ứng xử cộng đồng CNCF v1.0 + +### Quy tắc ứng xử người đóng góp + +Là người đóng góp và duy trì dự án này, và vì lợi ích thúc đẩy một cộng đồng mở, chúng tôi cam kết tôn trọng tất cả những người đóng góp thông qua việc báo cáo các vấn đề, các tính năng yêu cầu, cập nhật tài liệu, gửi PRs hay patches, và các hoạt động khác. + +Chúng tôi cam kết tham gia dự án này là một trải nghiệm tốt cho mọi người, bất kể mức độ kinh nghiệm, giới tính, khuynh hướng tình dục, khuyết tật, ngoại hình cá nhân, chủng tộc, dân tộc, tuổi tác, tôn giáo, hoặc quốc tịch. + +Ví dụ về hành vi không được chấp nhận của người tham gia bao gồm: + +* Việc sử dụng ngôn ngữ hoặc hình ảnh tình dục +* Tấn công cá nhân +* Trêu đùa hoặc bình luận lăng mạ, xúc phạm +* Quấy rối công khai hoặc riêng tư +* Xuất bản thông tin cá nhân của người khác, chẳng hạn như địa chỉ vật lý hoặc điện tử, mà không có sự cho phép rõ ràng +* Hành vi phi đạo đức hoặc không chuyên nghiệp khác. + +Người duy trì dự án có quyền và trách nhiệm xóa, chỉnh sửa hoặc từ chối comments, commits, code, chỉnh sửa wiki, issues và các đóng góp khác không phù hợp với Quy tắc ứng xử này. Bằng cách áp dụng Quy tắc ứng xử này, những người duy trì dự án cam kết áp dụng một cách công bằng và nhất quán các nguyên tắc này cho mọi khía cạnh của việc quản lý dự án này. Những người duy trì dự án không tuân theo hoặc thực thi Quy tắc ứng xử có thể bị xóa vĩnh viễn khỏi nhóm dự án. + +Quy tắc ứng xử này áp dụng cả trong không gian dự án và trong không gian công cộng khi một cá nhân đại diện cho dự án hoặc cộng đồng của dự án. + +Các trường hợp lạm dụng, quấy rối hoặc hành vi không thể chấp nhận được trong Kubernetes có thể được báo cáo bằng cách liên hệ với [Ủy ban Quy tắc ứng xử Kubernetes](https://git.k8s.io/community/committee-code-of-conduct) thông qua . Đối với các dự án khác, vui lòng liên hệ với người bảo trì dự án CNCF hoặc hòa giải viên của chúng tôi, Mishi Choudhary . + +Quy tắc ứng xử này được điều chỉnh từ Giao ước cộng tác viên (http://contributor-covenant.org), phiên bản 1.2.0, có sẵn tại +http://contributor-covenant.org/version/1/2/0/ + +### Quy tắc ứng xử sự kiện CNCF + +Các sự kiện CNCF được điều hành bởi Linux Foundation [Quy tắc ứng xử] (https://events.linuxfoundation.org/code-of-conduct/) có sẵn trên trang sự kiện. Điều này được thiết kế để tương thích với chính sách trên và cũng bao gồm nhiều chi tiết hơn về cách ứng phó với các sự cố. \ No newline at end of file diff --git a/content/vi/docs/reference/glossary/cluster.md b/content/vi/docs/reference/glossary/cluster.md new file mode 100644 index 0000000000..1aeafc54b2 --- /dev/null +++ b/content/vi/docs/reference/glossary/cluster.md @@ -0,0 +1,18 @@ +--- +title: Cluster +id: cluster +date: 2020-02-26 +full_link: +short_description: > + Một tập các worker machine, được gọi là node, dùng để chạy các các ứng dụng được đóng gói (containerized application). Mỗi cụm (cluster) có ít nhất một worker node. + +aka: +tags: +- fundamental +- operation +--- +Một tập các worker machine, được gọi là node, dùng để chạy các containerized application. Mỗi cụm (cluster) có ít nhất một worker node. + + +Các worker node chứa các pod (là những thành phần của ứng dụng). Control Plane quản lý các worker node và pod trong cluster. +Trong môi trường sản phẩm (production environment), Control Plane thường chạy trên nhiều máy tính và một cluster thường chạy trên nhiều node, cung cấp khả năng chịu lỗi (fault-tolerance) và tính sẵn sàng cao (high availability). \ No newline at end of file diff --git a/content/vi/docs/reference/glossary/containerd.md b/content/vi/docs/reference/glossary/containerd.md new file mode 100644 index 0000000000..b14971032a --- /dev/null +++ b/content/vi/docs/reference/glossary/containerd.md @@ -0,0 +1,15 @@ +--- +title: containerd +id: containerd +date: 2020-03-04 +full_link: https://containerd.io/docs/ +short_description: > + Một container runtime tập trung vào sự đơn giản, mạnh mẽ và linh động. +aka: +tags: +- tool +--- + Một container runtime tập trung vào sự đơn giản, mạnh mẽ và linh động. + + +containerd là một {{< glossary_tooltip text="container" term_id="container" >}} runtime cái mà chạy như một daemon trên Linux hoặc Windows. containerd quan tâm tới việc lấy và lưu trữ các container image, thực thi các container, cung cấp truy cập mạng, và nhiều hơn nữa. \ No newline at end of file diff --git a/content/vi/docs/reference/glossary/control-plane.md b/content/vi/docs/reference/glossary/control-plane.md new file mode 100644 index 0000000000..b8f9b0e7f8 --- /dev/null +++ b/content/vi/docs/reference/glossary/control-plane.md @@ -0,0 +1,15 @@ +--- +title: Control Plane +id: control-plane +date: 2020-03-04 +full_link: +short_description: > + Tầng điều khiển container, được dùng để đưa ra API và các interface để định nghĩa, triển khai, và quản lý vòng đời của các container. + +aka: +tags: +- fundamental +--- + Tầng điều khiển container, được dùng để đưa ra API và các interface để định nghĩa, triển khai, và quản lý vòng đời của các container. + + diff --git a/content/vi/docs/reference/glossary/cri-o.md b/content/vi/docs/reference/glossary/cri-o.md new file mode 100644 index 0000000000..be8dde10ac --- /dev/null +++ b/content/vi/docs/reference/glossary/cri-o.md @@ -0,0 +1,19 @@ +--- +title: CRI-O +id: cri-o +date: 2020-03-05 +full_link: https://cri-o.io/#what-is-cri-o +short_description: > + Một container runtime nhẹ dành riêng cho Kubernetes +aka: +tags: +- tool +--- +Một công cụ giúp bạn sử dụng các OCI container runtime với Kubernetes CRI. + + + +CRI-O là một thực thi của {{< glossary_tooltip term_id="cri" >}} để cho phép sử dụng các {{< glossary_tooltip text="container" term_id="container" >}} runtime cái mà tương thích với Open Container Initiative (OCI) +[runtime spec](http://www.github.com/opencontainers/runtime-spec). + +Triển khai CRI-O cho phép Kuberentes sử dụng bất kì OCI-compliant runtime như container runtime để chạy {{< glossary_tooltip text="Pods" term_id="pod" >}}, và để lấy CRI container image từ các remote registry. \ No newline at end of file diff --git a/content/vi/docs/reference/glossary/daemonset.md b/content/vi/docs/reference/glossary/daemonset.md new file mode 100644 index 0000000000..1039514a62 --- /dev/null +++ b/content/vi/docs/reference/glossary/daemonset.md @@ -0,0 +1,19 @@ +--- +title: DaemonSet +id: daemonset +date: 2020-03-05 +full_link: /docs/concepts/workloads/controllers/daemonset +short_description: > + Đảm bảo một bản sao của Pod đang chạy trên một tập các node của cluster. +aka: +tags: +- fundamental +- core-object +- workload +--- + Đảm bảo một bản sao của {{< glossary_tooltip text="Pod" term_id="pod" >}} đang chạy trên một tập các node của {{< glossary_tooltip text="cluster" term_id="cluster" >}}. + + + +Được sử dụng để deploy những system daemon ví dụ như log collector, monitoring agent, những cái thường phải chạy trên mọi {{< glossary_tooltip term_id="node" >}}. + diff --git a/content/vi/docs/reference/glossary/etcd.md b/content/vi/docs/reference/glossary/etcd.md new file mode 100644 index 0000000000..d52a91fdbd --- /dev/null +++ b/content/vi/docs/reference/glossary/etcd.md @@ -0,0 +1,20 @@ +--- +title: etcd +id: etcd +date: 2020-27-02 +full_link: /docs/tasks/administer-cluster/configure-upgrade-etcd/ +short_description: > + Key value store nhất quán (consistent) và sẵn sàng cao (highly-available) được sử dụng như một kho lưu trữ của Kubernetes cho tất cả dữ liệu của cluster. + +aka: +tags: +- architecture +- storage +--- + Key value store nhất quán (consistent) và sẵn sàng cao (highly-available) được sử dụng như một kho lưu trữ của Kubernetes cho tất cả dữ liệu của cluster. + + + +Nếu Kubernetes cluster của bạn sử dụng etcd như kho lưu trữ của nó, chắc chắn bạn có một kế hoạch [back up](/docs/tasks/administer-cluster/configure-upgrade-etcd/#backing-up-an-etcd-cluster) cho những dữ liệu này. + +Bạn có thể tìm thêm thông tin chi tiết về etcd tại [documentation](https://etcd.io/docs/). \ No newline at end of file diff --git a/content/vi/docs/reference/glossary/kube-apiserver.md b/content/vi/docs/reference/glossary/kube-apiserver.md new file mode 100644 index 0000000000..94b0aa2183 --- /dev/null +++ b/content/vi/docs/reference/glossary/kube-apiserver.md @@ -0,0 +1,22 @@ +--- +title: API server +id: kube-apiserver +date: 2020-02-26 +full_link: /docs/reference/generated/kube-apiserver/ +short_description: > + Thành phần tầng điểu khiển (control plane), được dùng để phục vụ Kubernetes API. + +aka: +- kube-apiserver +tags: +- architecture +- fundamental +--- + API server là một thành phần của Kubernetes {{< glossary_tooltip text="control plane" term_id="control-plane" >}}, được dùng để đưa ra Kubernetes API. +API server là front end của Kubernetes control plane. + + + +Thực thi chính của API server là [kube-apiserver](/docs/reference/generated/kube-apiserver/). +kube-apiserver được thiết kế để co giãn theo chiều ngang — có nghĩa là nó co giãn bằng cách triển khai thêm các thực thể. +Bạn có thể chạy một vài thực thể của kube-apiserver và cân bằng lưu lượng giữa các thực thể này. \ No newline at end of file diff --git a/content/vi/docs/reference/glossary/kube-scheduler.md b/content/vi/docs/reference/glossary/kube-scheduler.md new file mode 100644 index 0000000000..dc7c63a31f --- /dev/null +++ b/content/vi/docs/reference/glossary/kube-scheduler.md @@ -0,0 +1,17 @@ +--- +title: kube-scheduler +id: kube-scheduler +date: 2020-03-05 +full_link: /docs/reference/generated/kube-scheduler/ +short_description: > + Thành phần của Control Plane, được dùng để giám sát việc tạo những pod mới mà chưa được chỉ định vào node nào, và chọn một node để chúng chạy trên đó. + +aka: +tags: +- architecture +--- + Thành phần của Control Plane, được dùng để giám sát việc tạo những pod mới mà chưa được chỉ định vào node nào, và chọn một node để chúng chạy trên đó. + + + +Những yếu tố trong những quyết định lập lịch bao gồm những yêu cầu về tài nguyên, những đòi hỏi về phần cứng/phần mềm/chính sách, những thông số về affinity và anti-affinity, dữ liệu tại chỗ (data locality), nhiễu inter-workload và thời hạn (deadline). diff --git a/content/vi/partners/_index.html b/content/vi/partners/_index.html new file mode 100644 index 0000000000..f5b44d5e94 --- /dev/null +++ b/content/vi/partners/_index.html @@ -0,0 +1,91 @@ +--- +title: Các đối tác +bigheader: Các đối tác của Kubernetes +abstract: Phát triển hệ sinh thái Kubernetes. +class: gridPage +cid: partners +--- + +
    +
    +
    Kubernetes phối hợp làm việc với các đối tác để tạo ra một codebase mạnh mẽ hỗ trợ một loạt các nền tảng bổ sung.
    +
    +
    +
    +
    + Các nhà cung cấp dịch vụ được chứng nhận bởi Kubernetes (KCSP) +
    +
    Các nhà cung cấp dịch vụ được chứng nhận với bề dày kinh nghiệm sẽ trợ giúp các tổ chức kinh doanh, các công ty ứng dụng Kubernetes nhanh chóng. +


    + +

    Bạn muốn trở thành một KCSP? +
    +
    +
    +
    +
    + Các nhà phân phối Kubernetes, dịch vụ hosting, dịch vụ cài đặt +
    Tiêu chuẩn tương thích về phần mềm bảo đảm rằng các phiên bản Kubernetes từ các nhà cung cấp sẽ hỗ trợ các bộ API được yêu cầu bởi khách hàng. +


    + +

    Bạn muốn trở thành một Kubernetes Certified? +
    +
    +
    +
    +
    Các đối tác đào tạo Kubernetes (KTP)
    +
    Các đối tác đào tạo được chứng nhận đã và đang sở hữu bề dày kinh nghiệm trong lĩnh vực đám mây. +



    + +

    Bạn muốn trở thành một KTP? +
    +
    +
    + + + +
    + + +
    + +
    +
    + + + + diff --git a/content/zh/blog/_posts/2015-03-00-Kubernetes-Gathering-Videos.md b/content/zh/blog/_posts/2015-03-00-Kubernetes-Gathering-Videos.md index 2576296c64..c53ea68585 100644 --- a/content/zh/blog/_posts/2015-03-00-Kubernetes-Gathering-Videos.md +++ b/content/zh/blog/_posts/2015-03-00-Kubernetes-Gathering-Videos.md @@ -3,7 +3,6 @@ title: " Kubernetes 采集视频 " date: 2015-03-23 slug: kubernetes-gathering-videos -url: /blog/2015/03/Kubernetes-Gathering-Videos --- * kubectl exec -p $POD -- $CMD @@ -116,7 +115,7 @@ Notes from meeting: * want to inject a binary under control of the host, similar to pre-start hooks * socat, nsenter, whatever the pre-start hook needs - + --> * 想要在主机的控制下注入二进制文件,类似于预启动钩子 diff --git a/content/zh/blog/_posts/2015-03-00-Welcome-To-Kubernetes-Blog.md b/content/zh/blog/_posts/2015-03-00-Welcome-To-Kubernetes-Blog.md index 3e3b5f6d3d..3b35b0b21a 100644 --- a/content/zh/blog/_posts/2015-03-00-Welcome-To-Kubernetes-Blog.md +++ b/content/zh/blog/_posts/2015-03-00-Welcome-To-Kubernetes-Blog.md @@ -2,12 +2,11 @@ title: 欢迎来到 Kubernetes 博客! date: 2015-03-20 slug: welcome-to-kubernetes-blog -url: /blog/2015/03/Welcome-To-Kubernetes-Blog --- 每个星期,Kubernetes 贡献者社区几乎都会在谷歌 Hangouts 上聚会。我们希望任何对此感兴趣的人都能了解这个论坛的讨论内容。 -议程 +议程 * Mesos 集成 * 高可用性(HA) @@ -36,7 +35,7 @@ Agenda * 客户端版本化 笔记 @@ -71,7 +70,7 @@ Notes * Load-balance apiserver. * Cold standby for controller manager and other master components. - + --> * HA @@ -95,7 +94,7 @@ Notes * See * Justin working on multi-platform e2e dashboard - + --> * 向 e2e 添加性能和分析详细信息以跟踪回归 @@ -123,7 +122,7 @@ Notes * Structured types are useful in the client. Versioned structs would be ok. * If start with json/yaml (kubectl), shouldn’t convert to structured types. Use swagger. - + --> * 客户端版本化 diff --git a/content/zh/blog/_posts/2015-04-00-Weekly-Kubernetes-Community-Hangout_29.md b/content/zh/blog/_posts/2015-04-00-Weekly-Kubernetes-Community-Hangout_29.md index c451022671..399d926792 100644 --- a/content/zh/blog/_posts/2015-04-00-Weekly-Kubernetes-Community-Hangout_29.md +++ b/content/zh/blog/_posts/2015-04-00-Weekly-Kubernetes-Community-Hangout_29.md @@ -2,7 +2,6 @@ title: " Kubernetes 社区每周聚会笔记- 2015年4月24日 " date: 2015-04-30 slug: weekly-kubernetes-community-hangout_29 -url: /blog/2015/04/Weekly-Kubernetes-Community-Hangout_29 --- 每个星期,Kubernetes 贡献者社区几乎都会在谷歌 Hangouts 上聚会。我们希望任何对此感兴趣的人都能了解这个论坛的讨论内容。 @@ -85,7 +84,7 @@ Notes: * Brendan: 请求,它如何查找重复请求?Cassandra 希望在底层复制数据。向上和向下扩缩是有效的。根据负载动态地创建存储。它的步骤不仅仅是快照——通过编程使用预分配创建副本。 * Tim: 帮助自动配置。 - + +--> * 简单的滚动更新 - Brendan @@ -58,7 +57,7 @@ Every week the Kubernetes contributing community meet virtually over Google Hang * Can run AppContainer and docker containers in same pod. * Changes are close to merged. - + --> * Rocket 演示 - CoreOS 的伙计们 @@ -88,7 +87,7 @@ Every week the Kubernetes contributing community meet virtually over Google Hang * * Can create new service account with ServiceAccountToken. Controller will create token for it. * Can create a pod with service account, pods will have service account secret mounted at /var/run/secrets/kubernetes.io/… - + --> * 演示 service accounts 和 secrets 被添加到 pod - Jordan @@ -106,16 +105,16 @@ Every week the Kubernetes contributing community meet virtually over Google Hang * * 可以使用 ServiceAccountToken 创建新的 service account。控制器将为它创建令牌。 * 可以创建一个带有 service account 的 pod, pod 将在 /var/run/secrets/kubernets.io/… - - - + * Kubelet 在容器中运行 - Paul * Kubelet 成功地运行了带有 secret 的 pod。 - + diff --git a/content/zh/blog/_posts/2015-06-00-Slides-Cluster-Management-With.md b/content/zh/blog/_posts/2015-06-00-Slides-Cluster-Management-With.md index 8e1c001d65..e2937cd16e 100644 --- a/content/zh/blog/_posts/2015-06-00-Slides-Cluster-Management-With.md +++ b/content/zh/blog/_posts/2015-06-00-Slides-Cluster-Management-With.md @@ -2,7 +2,6 @@ title: "幻灯片:Kubernetes 集群管理,爱丁堡大学演讲" date: 2015-06-26 slug: slides-cluster-management-with -url: /blog/2015/06/Slides-Cluster-Management-With --- _今天的嘉宾帖子是由 IT 自动化领域的领导者 Puppet Labs 的高级软件工程师 Gareth Rushgrove 撰写的。Gareth告诉我们一个新的 Puppet 模块,它帮助管理 Kubernetes 中的资源。_ @@ -27,7 +26,7 @@ _今天的嘉宾帖子是由 IT 自动化领域的领导者 Puppet Labs 的高 ### Puppet Kubernetes 模块 @@ -48,7 +47,7 @@ kubernetes_pod { 'sample-pod': }] }, ``` -} +} --> ``` @@ -63,10 +62,10 @@ kubernetes_pod { 'sample-pod': image => 'nginx', }] }, -} +} ``` @@ -91,7 +90,7 @@ Kubernetes has several resources, from Pods and Services to Replication Controll Kubernetes 有很多资源,来自 Pods、 Services、 Replication Controllers 和 Service Accounts。您可以在[Puppet 中的 kubernetes 留言簿示例](https://puppetlabs.com/blog/kubernetes-guestbook-example-puppet)文章中看到管理这些资源的模块示例。这演示了如何将规范的 hello-world 示例转换为使用 Puppet代码。 @@ -113,17 +112,17 @@ guestbook { 'myguestbook': frontend_replicas => 3, redis_master_image => 'redis', redis_slave_image => 'gcr.io/google_samples/gb-redisslave:v1', - frontend_image => 'gcr.io/google_samples/gb-frontend:v3', + frontend_image => 'gcr.io/google_samples/gb-frontend:v3', } ``` 您可以在Puppet博客文章[在 Puppet 中为 Kubernetes 构建自己的抽象](https://puppetlabs.com/blog/building-your-own-abstractions-kubernetes-puppet)中阅读更多关于使用 Puppet 定义的类型的信息,并看到更多的代码示例。 @@ -146,13 +145,13 @@ The advantages of using Puppet rather than just the standard YAML files and kube - 能够针对 Kubernetes API 重复运行相同的代码,以检测任何更改或修正配置。 值得注意的是,大多数大型组织都将拥有非常异构的环境,运行各种各样的软件和操作系统。拥有统一这些离散系统的单一工具链可以使采用 Kubernetes 等新技术变得更加容易。 diff --git a/content/zh/blog/_posts/2016-01-00-Simple-Leader-Election-With-Kubernetes.md b/content/zh/blog/_posts/2016-01-00-Simple-Leader-Election-With-Kubernetes.md index bcea1c026e..a1c9bb3c3b 100644 --- a/content/zh/blog/_posts/2016-01-00-Simple-Leader-Election-With-Kubernetes.md +++ b/content/zh/blog/_posts/2016-01-00-Simple-Leader-Election-With-Kubernetes.md @@ -3,7 +3,6 @@ title: " Simple leader election with Kubernetes and Docker " date: 2016-01-11 slug: simple-leader-election-with-kubernetes -url: /blog/2016/01/Simple-Leader-Election-With-Kubernetes --- #### Overview @@ -59,13 +58,13 @@ Given these primitives, the code to use master election is relatively straightfo 给定这些原语,使用 master election 的代码相对简单,您可以在这里找到[here][1]。我们自己来做吧。 -``` +``` $ kubectl run leader-elector --image=gcr.io/google_containers/leader-elector:0.4 --replicas=3 -- --election=example ``` 这将创建一个包含3个副本的 leader election 集合: -``` +``` $ kubectl get pods NAME READY STATUS RESTARTS AGE leader-elector-inmr1 1/1 Running 0 13s @@ -91,7 +90,7 @@ leader-elector-sgwcq 1/1 Running 0 13s @@ -127,7 +126,7 @@ _'example' 是上面 kubectl run … 命令_中候选集的名称 $ kubectl get endpoints example -o yaml ``` 现在,要验证 leader election 是否实际有效,请在另一个终端运行: -``` +``` $ kubectl delete pods (leader-pod-name) ``` @@ -142,7 +141,7 @@ The leader-election container provides a simple webserver that can serve on any Leader-election container 提供了一个简单的 web 服务器,可以服务于任何地址(e.g. http://localhost:4040)。您可以通过删除现有的 leader election 组并创建一个新的 leader elector 组来测试这一点,在该组中,您还可以向 leader elector 映像传递--http=(host):(port) 规范。这将导致集合中的每个成员通过 webhook 提供有关领导者的信息。 -``` +``` # delete the old leader elector group $ kubectl delete rc leader-elector @@ -174,7 +173,7 @@ http://localhost:8001/api/v1/proxy/namespaces/default/pods/(leader-pod-name):404 And you will see: -``` +``` {"name":"(name-of-leader-here)"} ``` #### Leader election with sidecars @@ -192,7 +191,7 @@ http://localhost:8001/api/v1/proxy/namespaces/default/pods/(leader-pod-name):404 你会看到: -``` +``` {"name":"(name-of-leader-here)"} ``` #### 有副手的 leader election @@ -209,7 +208,7 @@ Leader-election container 可以作为一个 sidecar,您可以从自己的应 -* “Kubernetes 硬件黑客:通过旋钮、推杆和滑块探索 Kubernetes API” 演讲者 Ian Lewis 和 Brian Dorsey,谷歌开发布道师* [http://sched.co/6Bl3](http://sched.co/6Bl3) +* “Kubernetes 硬件黑客:通过旋钮、推杆和滑块探索 Kubernetes API” 演讲者 Ian Lewis 和 Brian Dorsey,谷歌开发布道师* [http://sched.co/6Bl3](http://sched.co/6Bl3) * “rktnetes: 容器运行时和 Kubernetes 的新功能” 演讲者 Jonathan Boulle, CoreOS 的主程 -* [http://sched.co/6BY7](http://sched.co/6BY7) * “Kubernetes 文档:贡献、修复问题、收集奖金” 作者:John Mulhausen,首席技术作家,谷歌 -* [http://sched.co/6BUP](http://sched.co/6BUP)  * “[OpenStack 在 Kubernetes 的世界中扮演什么角色?](https://kubeconeurope2016.sched.org/event/6BYC/what-is-openstacks-role-in-a-kubernetes-world?iframe=yes&w=i:0;&sidebar=yes&bg=no#?iframe=yes&w=i:100;&sidebar=yes&bg=no)” 作者:Thierry carez, OpenStack 基金会工程总监 -* http://sched.co/6BYC -* “容器调度的实用指南” 作者:Mandy Waite,开发者倡导者,谷歌 -* [http://sched.co/6BZa](http://sched.co/6BZa) +* “容器调度的实用指南” 作者:Mandy Waite,开发者倡导者,谷歌 -* [http://sched.co/6BZa](http://sched.co/6BZa) * “[《纽约时报》编辑部正在制作 Kubernetes](https://kubeconeurope2016.sched.org/event/67f2/kubernetes-in-production-in-the-new-york-times-newsroom?iframe=yes&w=i:0;&sidebar=yes&bg=no#?iframe=yes&w=i:100;&sidebar=yes&bg=no)” Eric Lewis,《纽约时报》网站开发人员 -* [http://sched.co/67f2](http://sched.co/67f2) * “[使用 NGINX 为 Kubernetes 创建一个高级负载均衡解决方案](https://kubeconeurope2016.sched.org/event/6Bc9/creating-an-advanced-load-balancing-solution-for-kubernetes-with-nginx?iframe=yes&w=i:0;&sidebar=yes&bg=no#?iframe=yes&w=i:100;&sidebar=yes&bg=no)” 作者:Andrew Hutchings, NGINX 技术产品经理 -* http://sched.co/6Bc9 @@ -61,11 +60,11 @@ Get your KubeCon EU [tickets here](https://ti.to/kubecon/kubecon-eu-2016). [在这里](https://ti.to/kubecon/kubecon-eu-2016)获取您的 KubeCon EU 门票。 会场地址:CodeNode * 英国伦敦南广场 10 号 酒店住宿:[酒店](https://skillsmatter.com/contact-us) @@ -74,9 +73,9 @@ Google is a proud Diamond sponsor of KubeCon EU 2016. Come to London next month, 谷歌是 KubeCon EU 2016 的钻石赞助商。下个月 3 月 10 - 11 号来伦敦,参观 13 号展位,了解 Kubernetes,Google Container Engine(GKE),Google Cloud Platform 的所有信息! _KubeCon 是由 KubeAcademy、LLC 组织的,这是一个由社区驱动的开发者团体,专注于开发人员的教育和 kubernet.com 的推广 diff --git a/content/zh/blog/_posts/2016-02-00-Kubernetes-Community-Meeting-Notes.md b/content/zh/blog/_posts/2016-02-00-Kubernetes-Community-Meeting-Notes.md index 5d1037f747..608a5bbd33 100644 --- a/content/zh/blog/_posts/2016-02-00-Kubernetes-Community-Meeting-Notes.md +++ b/content/zh/blog/_posts/2016-02-00-Kubernetes-Community-Meeting-Notes.md @@ -2,7 +2,6 @@ title: " Kubernetes 社区会议记录 - 20160204 " date: 2016-02-09 slug: kubernetes-community-meeting-notes -url: /blog/2016/02/Kubernetes-Community-Meeting-Notes --- * 书记员:Rob Hirschfeld * 演示视频(20分钟):CoreOS rkt + Kubernetes[Shaya Potter] - * 期待在未来几个月内看到与rkt和k8s的整合(“rkt-netes”)。 还没有集成到 v1.2版本中。 + * 期待在未来几个月内看到与rkt和k8s的整合(“rkt-netes”)。 还没有集成到 v1.2版本中。 * Shaya 做了一个演示(8分钟的会议视频参考) * rkt的CLI显示了旋转容器 * [注意:音频在点数上是乱码] @@ -46,11 +45,11 @@ Kubernetes 贡献社区在每周四 10:00 PT 开会,通过视频会议讨论项 * Dawn Chen: * 将 rkt 与 kubernetes 集成的其余问题:1)cadivsor 2) DNS 3)与日志记录相关的错误 * 但是需要在 e2e 测试套件上做更多的工作 - * 用例(10分钟):在 OpenStack 上的 eBay k8s 和 k8s 上的 OpenStack [Ashwin Raveendran] @@ -90,7 +89,7 @@ Kubernetes 贡献社区在每周四 10:00 PT 开会,通过视频会议讨论项 * 我们希望在多个平台上进行测试的共识。 * 为测试报告提供一个全面转储会很有帮助 * 可以使用"phone-home"收集异常 - + 要参与 Kubernetes 社区,请考虑加入我们的[Slack 频道][2],查看 GitHub上的 [Kubernetes 项目][3],或加入[Kubernetes-dev Google 小组][4]。如果你真的很兴奋,你可以完成上述所有工作并加入我们的下一次社区对话-2016年2月11日。请将您自己或您想要了解的主题添加到[议程][5]并通过加入[此组][6]来获取日历邀请。 diff --git a/content/zh/blog/_posts/2016-07-00-Citrix-Netscaler-And-Kubernetes.md b/content/zh/blog/_posts/2016-07-00-Citrix-Netscaler-And-Kubernetes.md index b0a27044dc..45ab59e3af 100644 --- a/content/zh/blog/_posts/2016-07-00-Citrix-Netscaler-And-Kubernetes.md +++ b/content/zh/blog/_posts/2016-07-00-Citrix-Netscaler-And-Kubernetes.md @@ -2,7 +2,6 @@ title: " Citrix + Kubernetes = 全垒打 " date: 2016-07-14 slug: citrix-netscaler-and-kubernetes -url: /blog/2016/07/Citrix-Netscaler-And-Kubernetes --- -编者按:今天的客座文章来自 Citrix Systems 的产品管理总监 Mikko Disini,他分享了他们在 Kubernetes 集成上的合作经验。 _ +编者按:今天的客座文章来自 Citrix Systems 的产品管理总监 Mikko Disini,他分享了他们在 Kubernetes 集成上的合作经验。 _ 技术合作就像体育运动。如果你能像一个团队一样合作,你就能在最后关头取得胜利。这就是我们对谷歌云平台团队的经验。 -最近,我们与 Google 云平台(GCP)联系,代表 Citrix 客户以及更广泛的企业市场,希望就工作负载的迁移进行协作。此迁移需要将 [NetScaler Docker 负载均衡器]https://www.citrix.com/blogs/2016/06/20/the-best-docker-load-balancer-at-dockercon-in-seattle-this-week/) CPX 包含到 Kubernetes 节点中,并解决将流量引入 CPX 代理的任何问题。 +最近,我们与 Google 云平台(GCP)联系,代表 Citrix 客户以及更广泛的企业市场,希望就工作负载的迁移进行协作。此迁移需要将 [NetScaler Docker 负载均衡器]https://www.citrix.com/blogs/2016/06/20/the-best-docker-load-balancer-at-dockercon-in-seattle-this-week/) CPX 包含到 Kubernetes 节点中,并解决将流量引入 CPX 代理的任何问题。 **为什么是 NetScaler 和 Kubernetes** @@ -42,16 +41,16 @@ Recently, we approached Google Cloud Platform (GCP) to collaborate on behalf of --> 1. Citrix 的客户希望他们开始使用 Kubernetes 部署他们的容器和微服务体系结构时,能够像当初迁移到云计算时一样,享有 NetScaler 所提供的第 4 层到第 7 层能力  -2. Kubernetes 提供了一套经过验证的基础设施,可用来运行容器和虚拟机,并自动交付工作负载; +2. Kubernetes 提供了一套经过验证的基础设施,可用来运行容器和虚拟机,并自动交付工作负载; 3. NetScaler CPX 提供第 4 层到第 7 层的服务,并为日志和分析平台 [NetScaler 管理和分析系统](https://www.citrix.com/blogs/2016/05/24/introducing-the-next-generation-netscaler-management-and-analytics-system/) 提供高效的度量数据。 我希望我们所有与技术合作伙伴一起工作的经验都能像与 GCP 一起工作一样好。我们有一个列表,包含支持我们的用例所需要解决的问题。我们能够快速协作形成解决方案。为了解决这些问题,GCP 团队提供了深入的技术支持,与 Citrix 合作,从而使得 NetScaler CPX 能够在每台主机上作为客户端代理启动运行。 接下来,需要在 GCP 入口负载均衡器的数据路径中插入 NetScaler CPX,使 NetScaler CPX 能够将流量分散到前端 web 服务器。NetScaler 团队进行了修改,以便 NetScaler CPX 监听 API 服务器事件,并配置自己来创建 VIP、IP 表规则和服务器规则,以便跨前端应用程序接收流量和负载均衡。谷歌云平台团队提供反馈和帮助,验证为克服技术障碍所做的修改。完成了! @@ -61,7 +60,7 @@ NetScaler CPX use case is supported in [Kubernetes 1.3](https://kubernetes.io/bl NetScaler CPX 用例在 [Kubernetes 1.3](https://kubernetes.io/blog/2016/07/kubernetes-1-3-bridging-cloud-native-and-enterprise-workloads/) 中提供支持。Citrix 的客户和更广泛的企业市场将有机会基于 Kubernetes 享用 NetScaler 服务,从而降低将工作负载转移到云平台的阻力。  您可以在[此处](https://www.citrix.com/networking/microservices.html)了解有关 NetScaler CPX 的更多信息。 diff --git a/content/zh/blog/_posts/2016-07-00-Dashboard-Web-Interface-For-Kubernetes.md b/content/zh/blog/_posts/2016-07-00-Dashboard-Web-Interface-For-Kubernetes.md index 935cbcf325..dd0533def3 100644 --- a/content/zh/blog/_posts/2016-07-00-Dashboard-Web-Interface-For-Kubernetes.md +++ b/content/zh/blog/_posts/2016-07-00-Dashboard-Web-Interface-For-Kubernetes.md @@ -2,7 +2,6 @@ title: " Dashboard - Kubernetes 的全功能 Web 界面 " date: 2016-07-15 slug: dashboard-web-interface-for-kubernetes -url: /blog/2016/07/Dashboard-Web-Interface-For-Kubernetes --- _编者按:这篇文章是[一系列深入的文章](https://kubernetes.io/blog/2016/07/five-days-of-kubernetes-1-3) 中关于Kubernetes 1.3的新内容的一部分_ [Kubernetes Dashboard](http://github.com/kubernetes/dashboard)是一个旨在为 Kubernetes 世界带来通用监控和操作 Web 界面的项目。三个月前,我们[发布](https://kubernetes.io/blog/2016/04/building-awesome-user-interfaces-for-kubernetes)第一个面向生产的版本,从那时起 dashboard 已经做了大量的改进。在一个 UI 中,您可以在不离开浏览器的情况下,与 Kubernetes 集群执行大多数可能的交互。这篇博客文章分解了最新版本中引入的新功能,并概述了未来的路线图。 -**全功能的 Dashboard** +**全功能的 Dashboard** 由于社区和项目成员的大量贡献,我们能够为[Kubernetes 1.3发行版](https://kubernetes.io/blog/2016/07/kubernetes-1-3-bridging-cloud-native-and-enterprise-workloads/)提供许多新功能。我们一直在认真听取用户的反馈(参见[摘要信息图表](http://static.lwy.io/img/kubernetes_dashboard_infographic.png)),并解决了最高优先级的请求和难点。 --> -_编者按,今天的嘉宾帖子来自一位独立的 kubernetes 撰稿人 Justin Santa Barbara,分享了他对项目从一开始到未来发展的思考。_ +_编者按,今天的嘉宾帖子来自一位独立的 kubernetes 撰稿人 Justin Santa Barbara,分享了他对项目从一开始到未来发展的思考。_ -**亲爱的 K8s,** +**亲爱的 K8s,** -_很难相信你是唯一的一个 - 成长这么快的。在你一岁生日的时候,我想我可以写一个小纸条,告诉你为什么我在你出生的时候那么兴奋,为什么我觉得很幸运能成为抚养你长大的一员,为什么我渴望看到你继续成长!_ +_很难相信你是唯一的一个 - 成长这么快的。在你一岁生日的时候,我想我可以写一个小纸条,告诉你为什么我在你出生的时候那么兴奋,为什么我觉得很幸运能成为抚养你长大的一员,为什么我渴望看到你继续成长!_ -_--Justin_ +_--Justin_ 你从一个优秀的基础 - 良好的声明性功能开始,它是围绕一个具有良好定义的模式和机制的坚实的 API 构建的,这样我们就可以向前发展了。果然,在你的第一年里,你增长得如此之快:autoscaling、HTTP load-balancing support (Ingress)、support for persistent workloads including clustered databases (PetSets)。你已经和更多的云交了朋友(欢迎 azure 和 openstack 加入家庭),甚至开始跨越区域和集群(Federation)。这些只是一些最明显的变化 - 在你的大脑里发生了太多的变化! 我觉得你一直保持开放的态度真是太好了 - 你好像把所有的东西都写在 github 上 - 不管是好是坏。我想我们在这方面都学到了很多,比如让工程师做缩放声明的风险,然后在没有完全相同的精确性和严谨性框架的情况下,将这些声明与索赔进行权衡。但我很自豪你选择了不降低你的标准,而是上升到挑战,只是跑得更快 - 这可能不是最现实的办法,但这是唯一的方式能移动山! 然而,不知何故,你已经设法避免了许多其他开源软件陷入的共同死胡同,特别是当那些项目越来越大,开发人员最终要做的比直接使用它更多的时候。你是怎么做到的?有一个很可能是虚构的故事,讲的是 IBM 的一名员工犯了一个巨大的错误,被传唤去见大老板,希望被解雇,却被告知“我们刚刚花了几百万美元培训你。我们为什么要解雇你?“。尽管谷歌对你进行了大量的投资(包括 redhat 和其他公司),但我有时想知道,我们正在避免的错误是否更有价值。有一个非常开放的开发过程,但也有一个“oracle”,它有时会通过告诉我们两年后如果我们做一个特定的设计决策会发生什么来纠正错误。这是你应该听的父母! 所以,尽管你只有一岁,你真的有一个[旧灵魂](http://queue.acm.org/detail.cfm?ID=2898444)。我只是[很多人抚养你](https://kubernetes.io/blog/2016/07/happy-k8sbday-1)中的一员,但对我来说,能够与那些建立了这些令人难以置信的系统并拥有所有这些领域知识的人一起工作是一次极好的学习经历。然而,因为我们是白手起家(而不是采用现有的 Borg 代码),我们处于同一水平,仍然可以就如何培养你进行真正的讨论。好吧,至少和我们的水平一样接近,但值得称赞的是,他们都太好了,从来没提过! @@ -67,9 +66,9 @@ If I would pick just two of the wise decisions those brilliant people made: - 控制器是状态同步器:我们指定目标,您的控制器将不遗余力地工作,使系统达到该状态。它们工作在强类型 API 基础上,并且贯穿整个代码,因此 Kubernetes 比一个大的程序多一百个小程序。仅仅从技术上扩展到数千个节点是不够的;这个项目还必须扩展到数千个开发人员和特性;控制器帮助我们达到目的。 等等我们就走!我们将取代那些控制器,建立更多,API 基金会让我们构建任何我们可以用这种方式表达的东西 - 大多数东西只是标签或注释远离!但你的思想不会由语言来定义:有了第三方资源,你可以表达任何你选择的东西。现在我们可以不用在 Kubernetes 建造Kubernetes 了,创造出与其他任何东西一样感觉是 Kubernetes 的一部分的东西。最近添加的许多功能,如ingress、DNS integration、autoscaling and network policies ,都已经完成或可以通过这种方式完成。最终,在这些事情发生之前很难想象你会是怎样的一个人,但是明天的标准功能可以从今天开始,没有任何障碍或看门人,甚至对一个听众来说也是这样。 @@ -77,13 +76,13 @@ So I’m looking forward to seeing more and more growth happen further and furth 所以我期待着看到越来越多的增长发生在离 Kubernetes 核心越来越远的地方。我们必须通过这些阶段来工作;从需要在 kubernetes 内核中发生的事情开始——比如用部署替换复制控制器。现在我们开始构建不需要核心更改的东西。但我们仍然在讨论基础设施和应用程序。接下来真正有趣的是:当我们开始构建依赖于 kubernetes api 的应用程序时。我们一直有使用 kubernetes api 进行自组装的 cassandra 示例,但我们还没有真正开始更广泛地探讨这个问题。正如 S3 APIs 改变了我们构建记忆事物的方式一样,我认为 k8s APIs 也将改变我们构建思考事物的方式。 所以我很期待你的二岁生日:我可以试着预测你那时的样子,但我知道你会超越我所能想象的最大胆的东西。哦,这是你要去的地方! -_-- Justin Santa Barbara, 独立的 Kubernetes 贡献者_ +_-- Justin Santa Barbara, 独立的 Kubernetes 贡献者_ diff --git a/content/zh/blog/_posts/2017-10-00-Five-Days-Of-Kubernetes-18.md b/content/zh/blog/_posts/2017-10-00-Five-Days-Of-Kubernetes-18.md index 979d5cd931..eee16d7a49 100644 --- a/content/zh/blog/_posts/2017-10-00-Five-Days-Of-Kubernetes-18.md +++ b/content/zh/blog/_posts/2017-10-00-Five-Days-Of-Kubernetes-18.md @@ -2,7 +2,6 @@ title: " Kubernetes 1.8 的五天 " date: 2017-10-24 slug: five-days-of-kubernetes-18 -url: /blog/2017/10/Five-Days-Of-Kubernetes-18 --- Kubernetes 允许开发人员根据当前的流量和负载自动调整集群大小和 pod 副本的数量。这些调整减少了未使用节点的数量,节省了资金和资源。 在这次演讲中,谷歌的 Marcin Wielgus 将带领您了解 Kubernetes 中 pod 和 node 自动调焦的当前状态:它是如何工作的,以及如何使用它,包括在生产应用程序中部署的最佳实践。 喜欢这个演讲吗? 12 月 6 日至 8 日,在 Austin 参加 KubeCon 关于扩展和自动化您的 Kubernetes 集群的更令人兴奋的会议。[现在注册](https://www.eventbrite.com/e/kubecon-cloudnativecon-north-america-registration-37824050754?_ga=2.9666039.317115486.1510003873-1623727562.1496428006)。 diff --git a/content/zh/blog/_posts/2019-12-09-kubernetes-1.17-release-announcement.md b/content/zh/blog/_posts/2019-12-09-kubernetes-1.17-release-announcement.md new file mode 100644 index 0000000000..0505d24542 --- /dev/null +++ b/content/zh/blog/_posts/2019-12-09-kubernetes-1.17-release-announcement.md @@ -0,0 +1,274 @@ +--- +layout: blog +title: "Kubernetes 1.17:稳定" +date: 2019-12-09T13:00:00-08:00 +slug: kubernetes-1-17-release-announcement +--- + + +**作者:** [Kubernetes 1.17发布团队](https://github.com/kubernetes/sig-release/blob/master/releases/release-1.17/release_team.md) + + +我们高兴的宣布Kubernetes 1.17版本的交付,它是我们2019年的第四个也是最后一个发布版本。Kubernetes v1.17包含22个增强功能:有14个增强已经逐步稳定(stable),4个增强功能已经进入公开测试版(beta),4个增强功能刚刚进入内部测试版(alpha)。 + +## 主要的主题 + +### 云服务提供商标签基本可用 + +作为公开测试版特性添加到v1.2,v1.7中可以看到云提供商标签达到基本可用。 + +### 卷快照进入公开测试版 + +在v1.7中,Kubernetes卷快照特性是公开测试版。这个特性是在v1.12中以内部测试版引入的,第二个有重大变化的内部测试版是v1.13。 + +## 容器存储接口迁移公开测试版 + +在v1.7中,Kubernetes树内存储插件到容器存储接口(CSI)的迁移基础架构是公开测试版。容器存储接口迁移最初是在Kubernetes v1.14中以内部测试版引入的。 + +## 云服务提供商标签基本可用 + +当节点和卷被创建,会基于基础云提供商的Kubernetes集群打上一系列标准标签。节点会获得一个实例类型标签。节点和卷都会得到两个描述资源在云提供商拓扑的位置标签,通常是以区域和地区的方式组织。 + + +Kubernetes组件使用标准标签来支持一些特性。例如,调度者会保证pods和它们所声明的卷放置在相同的区域;当调度部署的pods时,调度器会优先将它们分布在不同的区域。你还可以在自己的pods标准中利用标签来配置,如节点亲和性,之类的事。标准标签使得你写的pod规范在不同的云提供商之间是可移植的。 + + +在这个版本中,标签已经达到基本可用。Kubernetes组件都已经更新,可以填充基本可用和公开测试版标签,并对两者做出反应。然而,如果你的pod规范或自定义的控制器正在使用公开测试版标签,如节点亲和性,我们建议你可以将它们迁移到新的基本可用标签中。你可以从如下地方找到新标签的文档: + + +- [实例类型](https://kubernetes.io/docs/reference/kubernetes-api/labels-annotations-taints/#nodekubernetesioinstance-type) +- [地区](https://kubernetes.io/docs/reference/kubernetes-api/labels-annotations-taints/#topologykubernetesioregion) +- [区域](https://kubernetes.io/docs/reference/kubernetes-api/labels-annotations-taints/#topologykubernetesiozone) + + +## 卷快照进入公开测试版 + +在v1.7中,Kubernetes卷快照是是公开测试版。最初是在v1.12中以内部测试版引入的,第二个有重大变化的内部测试版是v1.13。这篇文章总结它在公开版本中的变化。 + +### 卷快照是什么? + +许多的存储系统(如谷歌云持久化磁盘,亚马逊弹性块存储和许多的内部存储系统)支持为持久卷创建快照。快照代表卷在一个时间点的复制。它可用于配置新卷(使用快照数据提前填充)或恢复卷到一个之前的状态(用快照表示)。 + +### 为什么给Kubernetes加入卷快照? + +Kubernetes卷插件系统已经提供了功能强大的抽象用于自动配置、附加和挂载块文件系统。 + + +支持所有这些特性是Kubernets负载可移植的目标:Kubernetes旨在分布式系统应用和底层集群之间创建一个抽象层,使得应用可以不感知其运行集群的具体信息并且部署也不需特定集群的知识。 + + +Kubernetes存储特别兴趣组(SIG)将快照操作确定为对很多有状态负载的关键功能。如数据库管理员希望在操作数据库前保存数据库卷快照。 + + +在Kubernetes接口中提供一种标准的方式触发快照操作,Kubernetes用户可以处理这种用户场景,而不必使用Kubernetes API(并手动执行存储系统的具体操作)。 + + +取而代之的是,Kubernetes用户现在被授权以与集群无关的方式将快照操作放进他们的工具和策略中,并且确信它将对任意的Kubernetes集群有效,而与底层存储无关。 + + +此外,Kubernetes 快照原语作为基础构建能力解锁了为Kubernetes开发高级、企业级、存储管理特性的能力:包括应用或集群级别的备份方案。 + + +你可以阅读更多关于[发布容器存储接口卷快照公开测试版](https://kubernetes.io/blog/2019/12/09/kubernetes-1-17-feature-cis-volume-snapshot-beta/) + +## 容器存储接口迁移公测版 + +### 为什么我们迁移内建树插件到容器存储接口? + +在容器存储接口之前,Kubernetes提供功能强大的卷插件系统。这些卷插件是树内的意味着它们的代码是核心Kubernetes代码的一部分并附带在核心Kubernetes二进制中。然而,为Kubernetes添加插件支持新卷是非常有挑战的。希望在Kubernetes上为自己存储系统添加支持(或修复现有卷插件的bug)的供应商被迫与Kubernetes发行进程对齐。此外,第三方存储代码在核心Kubernetes二进制中会造成可靠性和安全问题,并且这些代码对于Kubernetes的维护者来说是难以(一些场景是不可能)测试和维护的。在Kubernetes上采用容器存储接口可以解决大部分问题。 + + +随着更多容器存储接口驱动变成生产环境可用,我们希望所有的Kubernetes用户从容器存储接口模型中获益。然而,我们不希望强制用户以破坏现有基本可用的存储接口的方式去改变负载和配置。道路很明确,我们将不得不用CSI替换树内插件接口。什么是容器存储接口迁移? + + +在容器存储接口迁移上所做的努力使得替换现有的树内存储插件,如`kubernetes.io/gce-pd`或`kubernetes.io/aws-ebs`,为相应的容器存储接口驱动成为可能。如果容器存储接口迁移正常工作,Kubernetes终端用户不会注意到任何差别。迁移过后,Kubernetes用户可以继续使用现有接口来依赖树内存储插件的功能。 + + +当Kubernetes集群管理者更新集群使得CSI迁移可用,现有的有状态部署和工作负载照常工作;然而,在幕后Kubernetes将存储管理操作交给了(以前是交给树内驱动)CSI驱动。 + + +Kubernetes组非常努力地保证存储接口的稳定性和平滑升级体验的承诺。这需要细致的考虑现有特性和行为来确保后向兼容和接口稳定性。你可以想像成在加速行驶的直线上给赛车换轮胎。 + + +你可以在这篇博客中阅读更多关于[容器存储接口迁移成为公开测试版](https://kubernetes.io/blog/2019/12/09/kubernetes-1-17-feature-csi-migration-beta/). + +## 其它更新 + +### 稳定💯 + +- [按条件污染节点](https://github.com/kubernetes/enhancements/issues/382) +- [可配置的Pod进程共享命名空间](https://github.com/kubernetes/enhancements/issues/495) +- [采用kube-scheduler调度DaemonSet Pods](https://github.com/kubernetes/enhancements/issues/548) +- [动态卷最大值](https://github.com/kubernetes/enhancements/issues/554) +- [Kubernetes容器存储接口支持拓扑](https://github.com/kubernetes/enhancements/issues/557) +- [在SubPath挂载提供环境变量扩展](https://github.com/kubernetes/enhancements/issues/559) +- [为Custom Resources提供默认值](https://github.com/kubernetes/enhancements/issues/575) +- [从频繁的Kublet心跳到租约接口](https://github.com/kubernetes/enhancements/issues/589) +- [拆分Kubernetes测试Tarball](https://github.com/kubernetes/enhancements/issues/714) +- [添加Watch书签支持](https://github.com/kubernetes/enhancements/issues/956) +- [行为驱动一致性测试](https://github.com/kubernetes/enhancements/issues/960) +- [服务负载均衡终结保护](https://github.com/kubernetes/enhancements/issues/980) +- [避免每一个Watcher独立序列化相同的对象](https://github.com/kubernetes/enhancements/issues/1152) + + +### 主要变化 + +- [添加IPv4/IPv6双栈支持](https://github.com/kubernetes/enhancements/issues/563) + + +### 其它显著特性 + +- [拓扑感知路由服务(内部测试版)](https://github.com/kubernetes/enhancements/issues/536) +- [为Windows添加RunAsUserName](https://github.com/kubernetes/enhancements/issues/1043) + + +### 可用性 + +Kubernetes 1.17 可以[在GitHub下载](https://github.com/kubernetes/kubernetes/releases/tag/v1.17.0)。开始使用Kubernetes,看看这些[交互教学](https://kubernetes.io/docs/tutorials/)。你可以非常容易使用[kubeadm](https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm/)安装1.17。 + +### 发布团队 + +正是因为有上千人参与技术或非技术内容的贡献才使这个版本成为可能。特别感谢由Guinevere Saenger领导的[发布团队](https://github.com/kubernetes/sig-release/blob/master/releases/release-1.17/release_team.md)。发布团队的35名成员在发布版本的多方面进行了协调,从文档到测试,校验和特性的完善。 + +随着Kubernetes社区的成长,我们的发布流程是在开源软件协作方面惊人的示例。Kubernetes快速并持续获得新用户。这一成长产生了良性的反馈循环,更多的贡献者贡献代码创造了更加活跃的生态。Kubernetes已经有超过[39000位贡献者](https://k8s.devstats.cncf.io/d/24/overall-project-statistics?orgId=1)和一个超过66000人的活跃社区。 + +### 网络研讨会 + +2020年1月7号,加入Kubernetes 1.17发布团队,学习关于这次发布的主要特性。[这里](https://zoom.us/webinar/register/9315759188139/WN_kPOZA_6RTjeGdXTG7YFO3A)注册。 + +### 参与其中 + +最简单的参与Kubernetes的方式是加入其中一个与你兴趣相同的[特别兴趣组](https://github.com/kubernetes/community/blob/master/sig-list.md)(SIGs)。有什么想要广播到Kubernetes社区吗?通过如下的频道,在每周的[社区会议](https://github.com/kubernetes/community/tree/master/communication)分享你的声音。感谢你的贡献和支持。 + + +- 在Twitter上关注我们[@Kubernetesio](https://twitter.com/kubernetesio)获取最新的更新 +- 在[Discuss](https://discuss.kubernetes.io/)参与社区的讨论 +- 在[Slack](http://slack.k8s.io/)加入社区 +- 在[Stack Overflow](http://stackoverflow.com/questions/tagged/kubernetes)发布问题(或回答问题) +- 分享你的Kubernetes[故事](https://docs.google.com/a/linuxfoundation.org/forms/d/e/1FAIpQLScuI7Ye3VQHQTwBASrgkjQDSS5TP0g3AXfFhwSM9YpHgxRKFA/viewform) + + diff --git a/content/zh/docs/concepts/architecture/cloud-controller.md b/content/zh/docs/concepts/architecture/cloud-controller.md index f3bdc03e1f..f313808371 100644 --- a/content/zh/docs/concepts/architecture/cloud-controller.md +++ b/content/zh/docs/concepts/architecture/cloud-controller.md @@ -235,19 +235,19 @@ The Service controller is responsible for listening to service create, update, a The Node controller contains the cloud-dependent functionality of the kubelet. Prior to the introduction of the CCM, the kubelet was responsible for initializing a node with cloud-specific details such as IP addresses, region/zone labels and instance type information. The introduction of the CCM has moved this initialization operation from the kubelet into the CCM. --> -节点控制器包含 kubelet 中依赖于云的功能,在引入 CCM 之前,kubelet 负责使用特定于云的详细信息(如 IP 地址,域/区标签和实例类型信息)初始化节点。CCM 的引入已将此初始化操作从 kubelet 转移到 CCM 中。 +节点控制器包含 kubelet 中云依赖的功能,在引入 CCM 之前,kubelet 负责使用特定于云平台的功能特性(如 IP 地址,域/区标签和实例类型信息)初始化节点。CCM 的引入已将此初始化操作从 kubelet 转移到 CCM 中。 -在这个新模型中,kubelet 初始化一个没有特定于云的信息的节点。但是,它会为新创建的节点添加污点,使节点不可调度,直到 CCM 使用特定于云的信息初始化节点后,才会清除这种污点,便得该节点可被调度。 +在这个新模型中,kubelet 初始化一个没有特定于云平台的功能特性的节点。但是,它会为新创建的节点添加污点,使节点不可调度,直到 CCM 使用云的规格信息初始化节点后,才会清除这种污点,便得该节点可被调度。 -在这个新模型中,kubelet 初始化一个没有特定于云的信息的节点。但是,它会为新创建的节点添加污点,使节点不可调度,直到 CCM 使用特定于云的信息初始化节点后,才会清除这种污点,便得该节点可被调度。 +在这个新模型中,kubelet 初始化一个没有特定于云平台的功能特性的节点。但是,它会为新创建的节点添加污点,使节点不可调度,直到 CCM 使用云的规格信息初始化节点后,才会清除这种污点,便得该节点可被调度。 ## 控制器模式 {#controller-pattern} -一个控制器至少追踪一种类型的 Kubernetes 资源。这些[对象](/docs/concepts/overview/working-with-objects/kubernetes-objects/)有一个代表期望状态的指定字段。正对这种资源的控制器就是要使他的当前状态接近与期望状态。 +一个控制器至少追踪一种类型的 Kubernetes 资源。这些[对象](/docs/concepts/overview/working-with-objects/kubernetes-objects/)有一个代表期望状态的指定字段。控制器负责确保其追踪的资源对象的当前状态接近期望状态。 控制器可能会自行执行操作;在 Kubernetes 中更常见的是一个控制器会发送信息给 {{< glossary_tooltip text="API 服务器" term_id="kube-apiserver" >}},这会有副作用。看下面这个例子。 diff --git a/content/zh/docs/concepts/configuration/manage-compute-resources-container.md b/content/zh/docs/concepts/configuration/manage-compute-resources-container.md index 627e27a2ad..c3e6b6af4d 100644 --- a/content/zh/docs/concepts/configuration/manage-compute-resources-container.md +++ b/content/zh/docs/concepts/configuration/manage-compute-resources-container.md @@ -275,7 +275,7 @@ resource limits, see the The resource usage of a Pod is reported as part of the Pod status. -If [optional monitoring](http://releases.k8s.io/{{< param "githubbranch" >}}/cluster/addons/cluster-monitoring/README.md) +If [optional monitoring](/docs/tasks/debug-application-cluster/resource-metrics-pipeline/) is configured for your cluster, then Pod resource usage can be retrieved from the monitoring system. --> @@ -284,7 +284,7 @@ the monitoring system. Pod 的资源使用情况被报告为 Pod 状态的一部分。 -如果为集群配置了 [可选监控](http://releases.k8s.io/{{< param "githubbranch" >}}/cluster/addons/cluster-monitoring/README.md),则可以从监控系统检索 Pod 资源的使用情况。 +如果为集群配置了 [可选监控](/docs/tasks/debug-application-cluster/resource-metrics-pipeline/),则可以从监控系统检索 Pod 资源的使用情况。 + +{{% capture overview %}} + + + +Operator 是 Kubernetes 的扩展软件,它利用[自定义资源](/docs/concepts/extend-kubernetes/api-extension/custom-resources/)管理应用及其组件。 +Operator 遵循 Kubernetes 的理念,特别是在[控制环](/docs/concepts/#kubernetes-control-plane)方面。 + +{{% /capture %}} + +{{% capture body %}} + + + +## 初衷 + +Operator 模式旨在捕获(正在管理一个或一组服务的)运维人员的关键目标。 +负责特定应用和 service 的运维人员,在系统应该如何运行、如何部署以及出现问题时如何处理等方面有深入的了解。 + +在 Kubernetes 上运行工作负载的人们都喜欢通过自动化来处理重复的任务。Operator 模式会封装您编写的(Kubernetes 本身提供功能以外的)任务自动化代码。 + + + +## Kubernetes 上的 Operator + +Kubernetes 为自动化而生。无需任何修改,您即可以从 Kubernetes 核心中获得许多内置的自动化功能。 +您可以使用 Kubernetes 自动化部署和运行工作负载, *甚至* 可以自动化 Kubernetes 自身。 + +Kubernetes {{< glossary_tooltip text="控制器" term_id="controller" >}} 使您无需修改 Kubernetes 自身的代码,即可以扩展集群的行为。 +Operator 是 Kubernetes API 的客户端,充当[自定义资源](/docs/concepts/api-extension/custom-resources/)的控制器。 + + + +## Operator 示例 {#example} + +使用 Operator 可以自动化的事情包括: + +* 按需部署应用 +* 获取/还原应用状态的备份 +* 处理应用代码的升级以及相关改动。例如,数据库 schema 或额外的配置设置 +* 发布一个 service,要求不支持 Kubernetes API 的应用也能发现它 +* 模拟整个或部分集群中的故障以测试其稳定性 +* 在没有内部成员选举程序的情况下,为分布式应用选择首领角色 + + + +想要更详细的了解 Operator?这儿有一个详细的示例: + +1. 有一个名为 SampleDB 的自定义资源,您可以将其配置到集群中。 +2. 一个包含 Operator 控制器部分的 Deployment,用来确保 Pod 处于运行状态。 +3. Operator 代码的容器镜像。 +4. 控制器代码,负责查询控制平面以找出已配置的 SampleDB 资源。 +5. Operator 的核心是告诉 API 服务器,如何使现实与代码里配置的资源匹配。 + * 如果添加新的 SampleDB,Operator 将设置 PersistentVolumeClaims 以提供持久化的数据库存储,设置 StatefulSet 以运行 SampleDB,并设置 Job 来处理初始配置。 + * 如果您删除它,Operator 将建立快照,然后确保 StatefulSet 和 Volume 已被删除。 +6. Operator 也可以管理常规数据库的备份。对于每个 SampleDB 资源,Operator 会确定何时创建(可以连接到数据库并进行备份的)Pod。这些 Pod 将依赖于 ConfigMap 和/或 具有数据库连接详细信息和凭据的 Secret。 +7. 由于 Operator 旨在为其管理的资源提供强大的自动化功能,因此它还需要一些额外的支持性代码。在这个示例中,代码将检查数据库是否正运行在旧版本上,如果是,则创建 Job 对象为您升级数据库。 + + + +## 部署 Operator + +部署 Operator 最常见的方法是将自定义资源及其关联的控制器添加到您的集群中。跟运行容器化应用一样,Controller 通常会运行在 {{< glossary_tooltip text="控制平面" term_id="control-plane" >}} 之外。例如,您可以在集群中将控制器作为 Deployment 运行。 + + + +## 使用 Operator {#using-operators} + +部署 Operator 后,您可以对 Operator 所使用的资源执行添加、修改或删除操作。按照上面的示例,您将为 Operator 本身建立一个 Deployment,然后: + +```shell +kubectl get SampleDB # 查找所配置的数据库 + +kubectl edit SampleDB/example-database # 手动修改某些配置 +``` + + + +可以了!Operator 会负责应用所作的更改并保持现有服务处于良好的状态 + +## 编写你自己的 Operator {#writing-operator} + + + +如果生态系统中没可以实现您目标的 Operator,您可以自己编写代码。在[接下来](#what-s-next)一节中,您会找到编写自己的云原生 Operator 需要的库和工具的链接。 + +您还可以使用任何支持 [Kubernetes API 客户端](/docs/reference/using-api/client-libraries/)的语言或运行时来实现 Operator(即控制器)。 + +{{% /capture %}} + +{{% capture whatsnext %}} + + + +* 详细了解[自定义资源](/docs/concepts/extend-kubernetes/api-extension/custom-resources/) +* 在 [OperatorHub.io](https://operatorhub.io/) 上找到现成的、适合您的 Operator +* 借助已有的工具来编写您自己的 Operator,例如: + * [KUDO](https://kudo.dev/) (Kubernetes 通用声明式 Operator) + * [kubebuilder](https://book.kubebuilder.io/) + * [Metacontroller](https://metacontroller.app/),可与 Webhook 结合使用,以实现自己的功能。 + * [Operator 框架](https://github.com/operator-framework/getting-started) +* [发布](https://operatorhub.io/)您的 Operator,让别人也可以使用 +* 阅读 [CoreOS 原文](https://coreos.com/blog/introducing-operators.html),其介绍了 Operator 介绍 +* 阅读这篇来自谷歌云的关于构建 Operator 最佳实践的[文章](https://cloud.google.com/blog/products/containers-kubernetes/best-practices-for-building-kubernetes-operators-and-stateful-apps) + +{{% /capture %}} diff --git a/content/zh/docs/concepts/overview/working-with-objects/kubernetes-objects.md b/content/zh/docs/concepts/overview/working-with-objects/kubernetes-objects.md index 0015553467..156fa61d56 100644 --- a/content/zh/docs/concepts/overview/working-with-objects/kubernetes-objects.md +++ b/content/zh/docs/concepts/overview/working-with-objects/kubernetes-objects.md @@ -1,12 +1,21 @@ --- title: 理解 Kubernetes 对象 - -redirect_from: -- "/docs/concepts/abstractions/overview/" -- "/docs/concepts/abstractions/overview.html" content_template: templates/concept +weight: 10 +card: + name: 概念 + weight: 40 --- + + {{% capture overview %}} -也需要提供对象的 `spec` 字段。对象 `spec` 的精确格式对每个 Kubernetes 对象来说是不同的,包含了特定于该对象的嵌套字段。[Kubernetes API 参考](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/)能够帮助我们找到任何我们想创建的对象的 spec 格式。 +您也需要提供对象的 `spec` 字段。对象 `spec` 的精确格式对每个 Kubernetes 对象来说是不同的,包含了特定于该对象的嵌套字段。[Kubernetes API 参考](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/)能够帮助我们找到任何我们想创建的对象的 spec 格式。 例如,可以从 [这里](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#podspec-v1-core) 查看 `Pod` 的 `spec` 格式, @@ -150,10 +159,13 @@ and the `spec` format for a `Deployment` can be found {{% capture whatsnext %}} - -* 了解最重要的基本 Kubernetes 对象,例如 [Pod](/docs/concepts/workloads/pods/pod-overview/)。 +* [Kubernetes API 概述](/docs/reference/using-api/api-overview/) 提供关于 API 概念的进一步阐述 +* 了解最重要的 Kubernetes 基本对象,例如 [Pod](/docs/concepts/workloads/pods/pod-overview/)。 +* 了解 Kubernetes 中的[控制器](/docs/concepts/architecture/controller/)。 {{% /capture %}} diff --git a/content/zh/docs/concepts/policy/pod-security-policy.md b/content/zh/docs/concepts/policy/pod-security-policy.md index 3f2717ac44..1573ff7af2 100644 --- a/content/zh/docs/concepts/policy/pod-security-policy.md +++ b/content/zh/docs/concepts/policy/pod-security-policy.md @@ -2,9 +2,6 @@ approvers: - pweil- title: Pod 安全策略 -redirect_from: -- "/docs/user-guide/pod-security-policy/" -- "/docs/user-guide/pod-security-policy/index.html" --- diff --git a/content/zh/docs/concepts/storage/storage-classes.md b/content/zh/docs/concepts/storage/storage-classes.md index 3c7dc98bc8..b1d8becc60 100644 --- a/content/zh/docs/concepts/storage/storage-classes.md +++ b/content/zh/docs/concepts/storage/storage-classes.md @@ -36,7 +36,7 @@ systems. ## 介绍 `StorageClass` 为管理员提供了描述存储 `"类"` 的方法。 -不同的`类型`可能会映射到不同的服务质量等级或备份策略,或是由群集管理员制定的任意策略。 +不同的`类型`可能会映射到不同的服务质量等级或备份策略,或是由集群管理员制定的任意策略。 Kubernetes 本身并不清楚各种`类`代表的什么。这个`类`的概念在其他存储系统中有时被称为"配置文件"。 -管理员可以为没有申请绑定到特定 `StorageClass` 的 PVC 指定一个默认的`类` : -更多详情请参阅 [`PersistentVolumeClaim` 章节](#persistentvolumeclaims)。 +管理员可以为没有申请绑定到特定 `StorageClass` 的 PVC 指定一个默认的存储`类` : +更多详情请参阅 [`PersistentVolumeClaim` 章节](/docs/concepts/storage/persistent-volumes/#class-1)。 ```yaml apiVersion: storage.k8s.io/v1 @@ -92,13 +92,13 @@ for provisioning PVs. This field must be specified. --> ### 存储分配器 -`StorageClass` 有一个分配器,用来决定使用哪个`卷插件`分配`持久化卷申领`。该字段必须指定。 +`StorageClass` 有一个分配器,用来决定使用哪个`卷插件`分配`PV`。该字段必须指定。 -| 卷插件 | 提供厂商 | 配置例子 | +| 卷插件 | 内置分配器 | 配置例子 | | :--- | :---: | :---: | | AWSElasticBlockStore | ✓ | [AWS EBS](#aws-ebs) | | AzureFile | ✓ | [Azure File](#azure-file) | diff --git a/content/zh/docs/concepts/storage/volume-pvc-datasource.md b/content/zh/docs/concepts/storage/volume-pvc-datasource.md index d39e7128eb..a8e1a51175 100644 --- a/content/zh/docs/concepts/storage/volume-pvc-datasource.md +++ b/content/zh/docs/concepts/storage/volume-pvc-datasource.md @@ -24,18 +24,7 @@ weight: 30 This document describes the concept of cloning existing CSI Volumes in Kubernetes. Familiarity with [Volumes](/docs/concepts/storage/volumes) is suggested. --> -本文档描述 Kubernetes 中克隆现有 CSI 卷的概念。建议先熟悉[卷](/docs/concepts/storage/volumes)。 - - - -此功能需要启动 VolumePVCDataSource 功能门: - -``` ---feature-gates=VolumePVCDataSource=true -``` - +本文档介绍 Kubernetes 中克隆现有 CSI 卷的概念。阅读前建议先熟悉[卷](/docs/concepts/storage/volumes)。 {{% /capture %}} @@ -52,13 +41,13 @@ This feature requires VolumePVCDataSource feature gate to be enabled: The {{< glossary_tooltip text="CSI" term_id="csi" >}} Volume Cloning feature adds support for specifying existing {{< glossary_tooltip text="PVC" term_id="persistent-volume-claim" >}}s in the `dataSource` field to indicate a user would like to clone a {{< glossary_tooltip term_id="volume" >}}. --> -{{< glossary_tooltip text="CSI" term_id="csi" >}} 卷克隆功能增加了在 `dataSource` 字段指定现有的 {{< glossary_tooltip text="PVC" term_id="persistent-volume-claim" >}}s,来表示用户想要克隆的 {{< glossary_tooltip term_id="volume" >}}。 +{{< glossary_tooltip text="CSI" term_id="csi" >}} 卷克隆功能增加了通过在 `dataSource` 字段中指定存在的 {{< glossary_tooltip text="PVC" term_id="persistent-volume-claim" >}}s,来表示用户想要克隆的 {{< glossary_tooltip term_id="volume" >}}。 -克隆定义为已有 Kubernetes 卷的副本,可以像任何标准卷一样被使用。唯一的区别就是配置后,后端设备将创建指定卷的精确副本,而不是创建一个“新的”空卷。 +克隆,意思是为已有的 Kubernetes 卷创建副本,它可以像任何其它标准卷一样被使用。唯一的区别就是配置后,后端设备将创建指定完全相同的副本,而不是创建一个“新的”空卷。 + +{{< note >}} +你必须为 `spec.resources.requests.storage` 指定一个值,并且你指定的值必须大于或等于源卷的值。 +{{< /note >}} + diff --git a/content/zh/docs/concepts/storage/volumes.md b/content/zh/docs/concepts/storage/volumes.md index 6a46296cbb..797352e61b 100644 --- a/content/zh/docs/concepts/storage/volumes.md +++ b/content/zh/docs/concepts/storage/volumes.md @@ -988,6 +988,39 @@ spec: type: Directory ``` +{{< caution >}} + +应当注意,`FileOrCreate` 类型不会负责创建文件的父目录。如果挂载挂载文件的父目录不存在,pod 启动会失败。为了确保这种 `type` 能够工作,可以尝试把文件和它对应的目录分开挂载,如下所示: +{{< /caution >}} + +#### FileOrCreate pod 示例 + +```yaml +apiVersion: v1 +kind: Pod +metadata: + name: test-webserver +spec: + containers: + - name: test-webserver + image: k8s.gcr.io/test-webserver:latest + volumeMounts: + - mountPath: /var/local/aaa + name: mydir + - mountPath: /var/local/aaa/1.txt + name: myfile + volumes: + - name: mydir + hostPath: + # 确保文件所在目录成功创建。 + path: /var/local/aaa + type: DirectoryOrCreate + - name: myfile + hostPath: + path: /var/local/aaa/1.txt + type: FileOrCreate +``` + ### iscsi {#iscsi} -* TOC -{:toc} + +{{% capture overview %}} + +此页面概述了准入控制器。 +{{% /capture %}} + +{{% capture body %}} + ## 什么是准入控制插件? -一个准入控制插件是一段代码,它会在请求通过认证和授权之后、对象被持久化之前拦截到达 API server 的请求。插件代码运行在 API server 进程中,必须将其编译为二进制文件,以便在此时使用。 + +准入控制器是一段代码,它会在请求通过认证和授权之后、对象被持久化之前拦截到达 API 服务器的请求。控制器由下面的[列表](#what-does-each-admission-controller-do)组成,并编译进 `kube-apiserver` 二进制文件,并且只能由集群管理员配置。在该列表中,有两个特殊的控制器:MutatingAdmissionWebhook 和 ValidatingAdmissionWebhook。它们根据 API 中的配置,分别执行变更和验证[准入控制 webhook](/docs/reference/access-authn-authz/extensible-admission-controllers/#admission-webhooks)。 + -在每个请求被集群接受之前,准入控制插件依次执行。如果插件序列中任何一个拒绝了该请求,则整个请求将立即被拒绝并且返回一个错误给终端用户。 + +准入控制器可以执行 “验证” 和/或 “变更” 操作。变更(mutating)控制器可以修改被其接受的对象;验证(validating)控制器则不行。 + +准入控制过程分为两个阶段。第一阶段,运行变更准入控制器。第二阶段,运行验证准入控制器。 +再次提醒,某些控制器既是变更准入控制器又是验证准入控制器。 + +如果任何一个阶段的任何控制器拒绝了该请求,则整个请求将立即被拒绝,并向终端用户返回一个错误。 -准入控制插件可能会在某些情况下改变传入的对象,从而应用系统配置的默认值。另外,作为请求处理的一部分,准入控制插件可能会对相关的资源进行变更,以实现类似增加配额使用量这样的功能。 + +最后,除了对对象进行变更外,准入控制器还可以有其它作用:将相关资源作为请求处理的一部分进行变更。 +增加使用配额就是一个典型的示例,说明了这样做的必要性。 +此类用法都需要相应的回收或回调过程,因为任一准入控制器都无法确定某个请能否通过所有其它准入控制器。 -## 为什么需要准入控制插件? +## 为什么需要准入控制器? -Kubernetes 的许多高级功能都要求启用一个准入控制插件,以便正确地支持该特性。因此,一个没有正确配置准入控制插件的 Kubernetes API server 是不完整的,它不会支持您所期望的所有特性。 +Kubernetes 的许多高级功能都要求启用一个准入控制器,以便正确地支持该特性。因此,没有正确配置准入控制器的 Kubernetes API 服务器是不完整的,它无法支持您期望的所有特性。 -## 如何启用一个准入控制插件? + +## 如何启用一个准入控制器? -Kubernetes API server 支持一个标志参数 `admission-control` ,它指定了一个用于在集群修改对象之前调用的以逗号分隔的准入控制插件顺序列表。 +Kubernetes API 服务器的 `enable-admission-plugins` 标志,它指定了一个用于在集群修改对象之前调用的(以逗号分隔的)准入控制插件顺序列表。 +例如,下面的命令就启用了 `NamespaceLifecycle` 和 `LimitRanger` 准入控制插件: + +```shell +kube-apiserver --enable-admission-plugins=NamespaceLifecycle,LimitRanger ... +``` + +{{< note >}} -## 每个插件的功能是什么? - -### AlwaysAdmit +根据您 Kubernetes 集群的部署方式以及 API 服务器的启动方式的不同,您可能需要以不同的方式应用设置。 +例如,如果将 API 服务器部署为 systemd 服务,你可能需要修改 systemd 单元文件; +如果以自托管方式部署 Kubernetes,你可能需要修改 API 服务器的清单文件。 +{{< /note >}} -使用这个插件自行通过所有的请求。 -### AlwaysPullImages +## 怎么关闭准入控制器? + +Kubernetes API 服务器的 `disable-admission-plugins` 标志,会将传入的(以逗号分隔的)准入控制插件列表禁用,即使是默认启用的插件也会被禁用。 + +```shell +kube-apiserver --disable-admission-plugins=PodNodeSelector,AlwaysDeny ... +``` + +## 哪些插件是默认启用的? + +下面的命令可以查看哪些插件是默认启用的: + +```shell +kube-apiserver -h | grep enable-admission-plugins +``` + + + +在 1.16 中,它们是: + +```shell +NamespaceLifecycle, LimitRanger, ServiceAccount, TaintNodesByCondition, Priority, DefaultTolerationSeconds, DefaultStorageClass, StorageObjectInUseProtection, PersistentVolumeClaimResize, MutatingAdmissionWebhook, ValidatingAdmissionWebhook, RuntimeClass, ResourceQuota +``` + + + +## 每个准入控制器的作用是什么? + +### AlwaysAdmit {#alwaysadmit} {{< feature-state for_k8s_version="v1.13" state="deprecated" >}} + +该准入控制器会允许所有的 pod 接入集群。已废弃,因为它的行为根本就和没有准入控制器一样。 + +### AlwaysPullImages {#alwayspullimages} + + -这个插件修改每一个新创建的 Pod 的镜像拉取策略为 Always 。这在多租户集群中是有用的,这样用户就可以放心,他们的私有镜像只能被那些有凭证的人使用。没有这个插件,一旦镜像被拉取到节点上,任何用户的 pod 都可以通过已了解到的镜像的名称(假设 pod 被调度到正确的节点上)来使用它,而不需要对镜像进行任何授权检查。当启用这个插件时,总是在启动容器之前拉取镜像,这意味着需要有效的凭证。 +该准入控制器会修改每一个新创建的 Pod 的镜像拉取策略为 Always 。 +这在多租户集群中是有用的,这样用户就可以放心,他们的私有镜像只能被那些有凭证的人使用。 +如果没有这个准入控制器,一旦镜像被拉取到节点上,任何用户的 pod 都可以通过已了解到的镜像的名称(假设 pod 被调度到正确的节点上)来使用它,而不需要对镜像进行任何授权检查。 +当启用这个准入控制器时,总是在启动容器之前拉取镜像,这意味着需要有效的凭证。 -### AlwaysDeny +### AlwaysDeny {#alwaysdeny} {{< feature-state for_k8s_version="v1.13" state="deprecated" >}} -拒绝所有的请求。用于测试。 +拒绝所有的请求。由于没有实际意义,已废弃。 + +### DefaultStorageClass {#defaultstorageclass} -### DenyExecOnPrivileged (已废弃) + +该准入控制器监测没有请求任何特定存储类的 `PersistentVolumeClaim` 对象的创建,并自动向其添加默认存储类。 +这样,没有任何特殊存储类需求的用户根本不需要关心它们,它们将获得默认存储类。 -如果一个 pod 拥有一个特权容器,这个插件将拦截所有在该 pod 中执行 exec 命令的请求。 + +当未配置默认存储类时,此准入控制器不执行任何操作。如果将多个存储类标记为默认存储类,它将拒绝任何创建 `PersistentVolumeClaim` 的操作,并显示错误。此时准入控制器会忽略任何 `PersistentVolumeClaim` 更新操作,仅响应创建操作。要修复此错误,管理员必须重新访问其 `StorageClass` 对象,并仅将其中一个标记为默认。 -如果集群支持特权容器,并且希望限制最终用户在这些容器中执行 exec 命令的能力,我们强烈建议启用这个插件。 + +关于持久化卷和存储类,以及如何将存储类标记为默认,请参见[持久化卷](/docs/concepts/storage/persistent-volumes/)。 + +### DefaultTolerationSeconds {#defaulttolerationseconds} + + + +该准入控制器为 Pod 设置默认的容忍度,在 5 分钟内容忍 `notready:NoExecute` 和 `unreachable:NoExecute` 污点。(如果 Pod 尚未容忍 `node.kubernetes.io/not-ready:NoExecute` 和 `node.alpha.kubernetes.io/unreachable:NoExecute` 污点的话) + +### DenyExecOnPrivileged {#denyexeconprivileged} {{< feature-state for_k8s_version="v1.13" state="deprecated" >}} + + +如果一个 pod 拥有一个特权容器,该准入控制器将拦截所有在该 pod 中执行 exec 命令的请求。 -此功能已合并到 [DenyEscalatingExec](#denyescalatingexec)。 -### DenyEscalatingExec +此功能已合并至 [DenyEscalatingExec](#denyescalatingexec)。 +而 DenyExecOnPrivileged 准入插件已被废弃,并将在 v1.18 被移除。 + +建议使用基于策略的准入插件(例如 [PodSecurityPolicy](#podsecuritypolicy) 和自定义准入插件), +该插件可以针对特定用户或命名空间,还可以防止创建权限过高的 Pod。 + +### DenyEscalatingExec {#denyescalatingexec} {{< feature-state for_k8s_version="v1.13" state="deprecated" >}} + + -这个插件将拒绝在拥有衍生特权而具备访问宿主机能力的 pod 中执行 exec 和 attach 命令。这包括在特权模式运行的 pod ,可以访问主机 IPC 命名空间的 pod ,和访问主机 PID 命名空间的 pod 。 + +该准入控制器将拒绝在由于拥有升级特权,而具备访问宿主机能力的 pod 中执行 exec 和 attach 命令。这包括在特权模式运行的 pod ,可以访问主机 IPC 命名空间的 pod ,和访问主机 PID 命名空间的 pod 。 -如果集群支持使用以衍生特权运行的容器,并且希望限制最终用户在这些容器中执行 exec 命令的能力,我们强烈建议启用这个插件。 +The DenyEscalatingExec admission plugin is deprecated and will be removed in v1.18. -### ImagePolicyWebhook +Use of a policy-based admission plugin (like [PodSecurityPolicy](#podsecuritypolicy) or a custom admission plugin) +which can be targeted at specific users or Namespaces and also protects against creation of overly privileged Pods +is recommended instead. +--> + +DenyExecOnPrivileged 准入插件已被废弃,并将在 v1.18 被移除。 + +建议使用基于策略的准入插件(例如 [PodSecurityPolicy](#podsecuritypolicy) 和自定义准入插件), +该插件可以针对特定用户或命名空间,还可以防止创建权限过高的 Pod。 + +### EventRateLimit {#eventratelimit} {{< feature-state for_k8s_version="v1.13" state="alpha" >}} -ImagePolicyWebhook 插件允许使用一个后端的 webhook 做出准入决策。您可以按照如下配置 admission-control 选项来启用这个插件: -```shell ---admission-control=ImagePolicyWebhook +该准入控制器缓解了事件请求淹没 API 服务器的问题。集群管理员可以通过以下方式指定事件速率限制: + + + + * 确保 API 服务器的 `--runtime-config` 标志中包含了 `eventratelimit.admission.k8s.io/v1alpha1=true`; + * 启用 `EventRateLimit` 准入控制器; + * 从文件中引用 `EventRateLimit` 配置文件,并提供给 API 服务器命令的 `--admission-control-config-file` 标志: + +{{< tabs name="eventratelimit_example" >}} +{{% tab name="apiserver.config.k8s.io/v1" %}} +```yaml +apiVersion: apiserver.config.k8s.io/v1 +kind: AdmissionConfiguration +plugins: +- name: EventRateLimit + path: eventconfig.yaml +... ``` +{{% /tab %}} +{{% tab name="apiserver.k8s.io/v1alpha1" %}} +```yaml +# Deprecated in v1.17 in favor of apiserver.config.k8s.io/v1 +apiVersion: apiserver.k8s.io/v1alpha1 +kind: AdmissionConfiguration +plugins: +- name: EventRateLimit + path: eventconfig.yaml +... +``` +{{% /tab %}} +{{< /tabs >}} + + + +可以在配置中指定四种类型的限制: + + + + * `Server`: API 服务器收到的所有事件请求共享一个桶。 + * `Namespace`: 每个命名空间都有一个专用的桶。 + * `User`: 给每个用户都分配一个桶。 + * `SourceAndObject`: 根据事件的源和涉及对象的每种组合分配桶。 + + + +下面是一个配置示例 `eventconfig.yaml`: + +```yaml +apiVersion: eventratelimit.admission.k8s.io/v1alpha1 +kind: Configuration +limits: +- type: Namespace + qps: 50 + burst: 100 + cacheSize: 2000 +- type: User + qps: 10 + burst: 50 +``` + + + +详情请参见[事件速率限制提案](https://git.k8s.io/community/contributors/design-proposals/api-machinery/admission_control_event_rate_limit.md)。 + +### ExtendedResourceToleration {#extendedresourcetoleration} + + + +该插件有助于创建可扩展资源的专用节点。 +如果运营商想创建可扩展资源的专用节点(如 GPU、FPGA 等), +那他们应该以扩展资源名称作为键名,[为节点设置污点](/docs/concepts/configuration/taint-and-toleration/#example-use-cases)。 +如果启用了该准入控制器,会将此类污点的容忍自动添加到请求扩展资源的 Pod 中,用户不必再手动添加这些容忍。 + +### ImagePolicyWebhook {#imagepolicywebhook} + + + +ImagePolicyWebhook 准入控制器允许使用一个后端的 webhook 做出准入决策。 -#### 配置文件格式 - -ImagePolicyWebhook 插件使用了admission config 文件 `--admission-control-config-file` 来为后端行为设置配置选项。该文件可以是 json 或 yaml ,并具有以下格式: -```javascript -{ - "imagePolicy": { - "kubeConfigFile": "path/to/kubeconfig/for/backend", - "allowTTL": 50, // time in s to cache approval - "denyTTL": 50, // time in s to cache denial - "retryBackoff": 500, // time in ms to wait between retries - "defaultAllow": true // determines behavior if the webhook backend fails - } -} +#### 配置文件格式 + + + +ImagePolicyWebhook 使用配置文件来为后端行为设置配置选项。该文件可以是 json 或 yaml ,并具有以下格式: + +```yaml +imagePolicy: + kubeConfigFile: /path/to/kubeconfig/for/backend + # time in s to cache approval + allowTTL: 50 + # time in s to cache denial + denyTTL: 50 + # time in ms to wait between retries + retryBackoff: 500 + # determines behavior if the webhook backend fails + defaultAllow: true ``` -这个配置文件必须引用一个 [kubeconfig](/docs/concepts/cluster-administration/authenticate-across-clusters-kubeconfig/) 格式的文件,并在其中配置指向后端的连接。且需要在 TLS 上与后端进行通信。 +从文件中引用 ImagePolicyWebhook 的配置文件,并将其提供给 API 服务器命令 `--admission-control-config-file` 标志: + +{{< tabs name="imagepolicywebhook_example1" >}} +{{% tab name="apiserver.config.k8s.io/v1" %}} +```yaml +apiVersion: apiserver.config.k8s.io/v1 +kind: AdmissionConfiguration +plugins: +- name: ImagePolicyWebhook + path: imagepolicyconfig.yaml +... +``` +{{% /tab %}} +{{% tab name="apiserver.k8s.io/v1alpha1" %}} +```yaml +# Deprecated in v1.17 in favor of apiserver.config.k8s.io/v1 +apiVersion: apiserver.k8s.io/v1alpha1 +kind: AdmissionConfiguration +plugins: +- name: ImagePolicyWebhook + path: imagepolicyconfig.yaml +... +``` +{{% /tab %}} +{{< /tabs >}} + + + +或者,您也可以直接将配置嵌入到文件中: + +{{< tabs name="imagepolicywebhook_example2" >}} +{{% tab name="apiserver.config.k8s.io/v1" %}} +```yaml +apiVersion: apiserver.config.k8s.io/v1 +kind: AdmissionConfiguration +plugins: +- name: ImagePolicyWebhook + configuration: + imagePolicy: + kubeConfigFile: + allowTTL: 50 + denyTTL: 50 + retryBackoff: 500 + defaultAllow: true +``` +{{% /tab %}} +{{% tab name="apiserver.k8s.io/v1alpha1" %}} +```yaml +# Deprecated in v1.17 in favor of apiserver.config.k8s.io/v1 +apiVersion: apiserver.k8s.io/v1alpha1 +kind: AdmissionConfiguration +plugins: +- name: ImagePolicyWebhook + configuration: + imagePolicy: + kubeConfigFile: + allowTTL: 50 + denyTTL: 50 + retryBackoff: 500 + defaultAllow: true +``` +{{% /tab %}} +{{< /tabs >}} + + + +ImagePolicyWebhook 的配置文件必须引用 [kubeconfig](/docs/concepts/cluster-administration/authenticate-across-clusters-kubeconfig/) 格式的文件,该文件设置了到后端的连接,要求后端使用 TLS 进行通信。 kubeconfig 文件的 cluster 字段需要指向远端服务,user 字段需要包含已返回的授权者。 + + +```yaml +# clusters 指的是远程服务。 +clusters: +- name: name-of-remote-imagepolicy-service + cluster: + certificate-authority: /path/to/ca.pem # CA 用于验证远程服务 + server: https://images.example.com/policy # 要查询的远程服务的 URL。必须是 'https' 。 + +# users 指的是 API 服务器的 Webhook 配置。 +users: +- name: name-of-api-server + user: + client-certificate: /path/to/cert.pem # webhook 准入控制器使用的证书 + client-key: /path/to/key.pem # 证书匹配的密钥 +``` + -对于更多的 HTTP 配置,请参阅 [kubeconfig](/docs/concepts/cluster-administration/authenticate-across-clusters-kubeconfig/) 文档。 + +HTTP 更多的配置,请参阅 [kubeconfig](/docs/concepts/cluster-administration/authenticate-across-clusters-kubeconfig/) 文档。 -当面对一个准入决策时,API server 发送一个描述操作的 JSON 序列化的 api.imagepolicy.v1alpha1.ImageReview 对象。该对象包含描述被审核容器的字段,以及所有匹配 `*.image-policy.k8s.io/*` 的 pod 注释。 +当面对一个准入决策时,API server 发送一个描述操作的 JSON 序列化的 `imagepolicy.k8s.io/v1alpha1` `ImageReview` 对象。该对象包含描述被审核容器的字段,以及所有匹配 `*.image-policy.k8s.io/*` 的 pod 注释。 -请求载荷例子: +请求载荷示例: -``` +```json { "apiVersion":"imagepolicy.k8s.io/v1alpha1", "kind":"ImageReview", @@ -241,20 +585,20 @@ An example request body: "image":"myrepo/myimage@sha256:beb6bd6a68f114c1dc2ea4b28db81bdf91de202a9014972bec5e4d9171d90ed" } ], - "annotations":[ + "annotations":{ "mycluster.image-policy.k8s.io/ticket-1234": "break-glass" - ], + }, "namespace":"mynamespace" } } ``` -远程服务将填充请求的 ImageReviewStatus 字段,并返回允许或不允许访问。响应主体的 "spec" 字段会被忽略,并且可以省略。一个允许访问应答会返回: +远程服务将填充请求的 `ImageReviewStatus` 字段,并返回允许或不允许访问的响应。响应体的 "spec" 字段会被忽略,并且可以省略。一个允许访问应答会返回: -``` +```json { "apiVersion": "imagepolicy.k8s.io/v1alpha1", "kind": "ImageReview", @@ -269,7 +613,7 @@ To disallow access, the service would return: --> 不允许访问,服务将返回: -``` +```json { "apiVersion": "imagepolicy.k8s.io/v1alpha1", "kind": "ImageReview", @@ -288,12 +632,12 @@ For further documentation refer to the `imagepolicy.v1alpha1` API objects and `p -使用注解进行扩展 +#### 使用注解进行扩展 -一个 pod 中匹配 `*.image-policy.k8s.io/*` 的注解都会被发送给 webhook。这允许了解镜像策略后端的用户向它发送额外的信息,并为不同的后端实现接收不同的信息。 +一个 pod 中匹配 `*.image-policy.k8s.io/*` 的注解都会被发送给 webhook。这允许了解后端镜像策略的用户向它发送额外的信息,并为不同的后端实现接收不同的信息。 - * 在紧急情况下,请求 "break glass" 覆盖一个策略。 - - * 从一个记录了 break-glass 的请求的票证系统得到的一个票证编号 - - * 向策略服务器提供一个提示,用于提供镜像的 imageID,以方便它进行查找 + + * 在紧急情况下,请求 "break glass" 覆盖一个策略。 + * 从一个记录了 break-glass 的请求的 ticket 系统得到的一个 ticket 号号码。 + * 向策略服务器提供一个提示,用于提供镜像的 imageID,以方便它进行查找。 在任何情况下,注解都是由用户提供的,并不会被 Kubernetes 以任何方式进行验证。在将来,如果一个注解确定将被广泛使用,它可能会被提升为 ImageReviewSpec 的一个命名字段。 -### ServiceAccount +### LimitPodHardAntiAffinityTopology {#limitpodhardantiaffinitytopology} -这个插件实现了 [serviceAccounts](/docs/user-guide/service-accounts) 的自动化。 -如果您打算使用 Kubernetes 的 ServiceAccount 对象,我们强烈建议您使用这个插件。 +该准入控制器拒绝(定义了 `Anti Affinity` 拓扑键的)任何 Pod(`requiredDuringSchedulingRequiredDuringExecution` 中的 `kubernetes.io/hostname` 除外) -### SecurityContextDeny +### LimitRanger {#limitranger} -该插件将拒绝任何试图设置特定扩展 [SecurityContext](/docs/user-guide/security-context) 字段的 pod。如果集群没有使用 [ pod 安全策略](/docs/user-guide/pod-security-policy) 来限制安全上下文所能获取的值集,那么应该启用这个功能。 - -### ResourceQuota - - -此插件将观察传入的请求,并确保它不违反任何一个 `Namespace` 中的 `ResourceQuota` 对象中枚举出来的约束。如果您在 Kubernetes 部署中使用了 `ResourceQuota` -,您必须使用这个插件来强制执行配额限制。 - - -请查看 [resourceQuota 设计文档](https://git.k8s.io/community/contributors/design-proposals/admission_control_resource_quota.md) 和 [Resource Quota 例子](/docs/concepts/policy/resource-quotas/) 了解更多细节。 - - -强烈建议将这个插件配置在准入控制插件序列的末尾。这样配额就不会过早地增加,只会在稍后的准入控制中被拒绝。 - -### LimitRanger - - -这个插件将观察传入的请求,并确保它不会违反 `Namespace` 中 `LimitRange` 对象枚举的任何约束。如果您在 Kubernetes 部署中使用了 `LimitRange` 对象,则必须使用此插件来执行这些约束。LimitRanger 插件还可以用于将默认资源请求应用到没有指定任何内容的 Pod ;当前,默认的 LimitRanger 对 `default` 命名空间中的所有 pod 应用了0.1 CPU 的需求。 + +该准入控制器会观察传入的请求,并确保它不会违反 `Namespace` 中 `LimitRange` 对象枚举的任何约束。如果您在 Kubernetes 部署中使用了 `LimitRange` 对象,则必须使用此准入控制器来执行这些约束。LimitRanger 还可以用于将默认资源请求应用到没有指定任何内容的 Pod;当前,默认的 LimitRanger 对 `default` 命名空间中的所有 pod 都应用了 0.1 CPU 的需求。 -请查看 [limitRange 设计文档](https://git.k8s.io/community/contributors/design-proposals/admission_control_limit_range.md) 和 [Limit Range 例子](/docs/tasks/configure-pod-container/limit-range/) 了解更多细节。 + +请查看 [limitRange 设计文档](https://git.k8s.io/community/contributors/design-proposals/resource-management/admission_control_limit_range.md) 和 [Limit Range 例子](/docs/tasks/configure-pod-container/limit-range/)了解更多细节。 + +### MutatingAdmissionWebhook {#mutatingadmissionwebhook} {{< feature-state for_k8s_version="v1.13" state="beta" >}} -### InitialResources (试验) +该准入控制器调用任何与请求匹配的变更 webhook。匹配的 webhook 将被串行调用。每一个 webhook 都可以根据需要修改对象。 + +`MutatingAdmissionWebhook` ,顾名思义,仅在变更阶段运行。 -此插件观察 pod 创建请求。如果容器忽略了 requests 和 limits 计算资源,那么插件就会根据运行相同镜像的容器的历史使用记录来自动填充计算资源请求。如果没有足够的数据进行决策,则请求将保持不变。当插件设置了一个计算资源请求时,它会用它自动填充的计算资源对 pod 进行注解。 +如果由此准入控制器调用的 Webhook 有副作用(如降低配额), +则它 *必须* 具有协调系统,因为不能保证后续的 Webhook 和验证准入控制器都会允许完成请求。 -请查看 [InitialResouces 建议书](https://git.k8s.io/community/contributors/design-proposals/initial-resources.md) 了解更多细节。 - -### NamespaceLifecycle +如果你禁用了 MutatingAdmissionWebhook,那么还必须使用 `--runtime-config` 标志禁止 `admissionregistration.k8s.io/v1beta1` 组/版本中的 `MutatingWebhookConfiguration` 对象(版本 >=1.9 时,这两个对象都是默认启用的)。 -这个插件强制不能在一个正在被终止的 `Namespace` 中创建新对象,和确保使用不存在 `Namespace` 的请求被拒绝。 +#### 谨慎编写和安装变更 webhook + + + + * 当用户尝试创建的对象与返回的对象不同时,用户可能会感到困惑。 + * 当它们回读的对象与尝试创建的对象不同,内建的控制环可能会出问题。 + * 与覆盖原始请求中设置的字段相比,使用原始请求未设置的字段会引起问题的可能性较小。应尽量避免前面那种方式。 + * 这是一个 beta 特性。Kubernetes 未来的版本可能会限制这些 webhook 可以进行的变更类型。 + * 内建资源和第三方资源的控制环,未来可能会受到破坏性的更改,使现在运行良好的 Webhook 无法再正常运行。即使完成了 webhook API 安装,也不代表会为该 webhook 提供无限期的支持。 + +### NamespaceAutoProvision {#namespaceautoprovision} + + +该准入控制器会检查命名空间资源上的所有传入请求,并检查所引用的命名空间是否确实存在。如果找不到,它将创建一个命名空间。 +此准入控制器对于不想要求命名空间必须先创建后使用的集群部署中很有用。 + +### NamespaceExists {#namespaceexists} + + +该准入控制器检查除自身 `Namespace` 以外的命名空间资源上的所有请求。如果请求引用的命名空间不存在,则拒绝该请求。 + +### NamespaceLifecycle {#namespacelifecycle} + + +该准入控制器禁止在一个正在被终止的 `Namespace` 中创建新对象,并确保使用不存在的 `Namespace` 的请求被拒绝。 +该准入控制器还会禁止删除三个系统保留的命名空间,即 `default`、`kube-system` 和 `kube-public`。 -删除 `Namespace` 触发了在该命名空间中删除所有对象( pod 、 services 等)的一系列操作。为了确保这个过程的完整性,我们强烈建议启用这个插件。 +删除 `Namespace` 会触发删除该命名空间中所有对象(pod、services 等)的一系列操作。为了确保这个过程的完整性,我们强烈建议启用这个准入控制器。 -### DefaultStorageClass +### NodeRestriction {#noderestriction} -这个插件观察不指定 storage class 字段的 `PersistentVolumeClaim` 对象的创建,并自动向它们添加默认的 storage class 。这样,不指定 storage class 字段的用户根本无需关心它们,它们将得到默认的 storage class 。 +该准入控制器限制了 kubelet 可以修改的 `Node` 和 `Pod` 对象。 为了受到这个准入控制器的限制,kubelet 必须使用在 `system:nodes` 组中的凭证,并使用 `system:node:` 形式的用户名。这样,kubelet 只可修改自己的 `Node` API 对象,只能修改绑定到节点本身的 `Pod` 对象。 -当没有配置默认 storage class 时,这个插件不会执行任何操作。当一个以上的 storage class 被标记为默认时,它拒绝 `PersistentVolumeClaim` 创建并返回一个错误,管理员必须重新检查 `StorageClass` 对象,并且只标记一个作为默认值。这个插件忽略了任何 `PersistentVolumeClaim` 更新,它只对创建起作用。 +在 Kubernetes 1.11+ 的版本中,不允许 kubelet 从 `Node` API 对象中更新或删除污点。 + +在 Kubernetes 1.13+ 的版本中,`NodeRestriction` 准入插件可防止 kubelet 删除 `Node` API 对象,并对 `kubernetes.io/` 或 `k8s.io/` 前缀标签的 kubelet 强制进行如下修改: -查看 [persistent volume](/docs/user-guide/persistent-volumes) 文档了解 persistent volume claims 和 storage classes 并了解如何将一个 storage classes 标志为默认。 -### DefaultTolerationSeconds +* **防止** kubelets 添加/删除/更新带有 `node-restriction.kubernetes.io/` 前缀的标签。保留此前缀的标签,供管理员用来标记 `Node` 对象以隔离工作负载,并且不允许 kubelet 修改带有该前缀的标签。 +* **允许** kubelet 添加/删除/更新这些和这些前缀的标签: + * `kubernetes.io/hostname` + * `kubernetes.io/arch` + * `kubernetes.io/os` + * `beta.kubernetes.io/instance-type` + * `node.kubernetes.io/instance-type` + * `failure-domain.beta.kubernetes.io/region` + * `failure-domain.beta.kubernetes.io/zone` + * `topology.kubernetes.io/region` + * `topology.kubernetes.io/zone` + * `kubelet.kubernetes.io/`-prefixed labels + * `node.kubernetes.io/`-prefixed labels -这个插件设置了 pod 默认的宽恕容忍时间,对于那些没有设置宽恕容忍时间的 pod ,可以容忍 `notready:NoExecute` 和 `unreachable:NoExecute` 这些 taint 5分钟。 +Use of any other labels under the `kubernetes.io` or `k8s.io` prefixes by kubelets is reserved, and may be disallowed or allowed by the `NodeRestriction` admission plugin in the future. -### PodNodeSelector +Future versions may add additional restrictions to ensure kubelets have the minimal set of permissions required to operate correctly. +--> +kubelet 保留 `kubernetes.io` 或 `k8s.io` 前缀的所有标签,并且将来可能会被 `NodeRestriction` 准入插件允许或禁止。 + +将来的版本可能会增加其他限制,以确保 kubelet 具有正常运行所需的最小权限集。 + +### OwnerReferencesPermissionEnforcement {#ownerreferencespermissionenforcement} -通过读取命名空间注释和全局配置,这个插件默认并限制了在一个命名空间中使用什么节点选择器。 + +该准入控制器保护对 `metadata.ownerReferences` 对象的访问,以便只有对该对象具有 “删除” 权限的用户才能对其进行更改。该准入控制器还保护对 `metadata.ownerReferences[x].blockOwnerDeletion` 对象的访问,以便只有对所引用的 **属主(owner)** 的 `finalizers` 子资源具有 “更新” 权限的用户才能对其进行更改。 + +### PersistentVolumeLabel {#persistentvolumelabel} {{< feature-state for_k8s_version="v1.13" state="deprecated" >}} + + +该准入控制器会自动将区(region)或区域(zone)标签附加到由云提供商(如 GCE、AWS)定义的 PersistentVolumes 中。 +这有助于确保 Pod 和 PersistentVolume 位于相同的区或区域。 +如果准入控制器不支持为 PersistentVolumes 自动添加标签,那你可能需要手动添加标签,以防止 Pod 挂载其他区域的卷。 +PersistentVolumeLabel 已被废弃,标记持久卷已由[云管理控制器](/docs/tasks/administer-cluster/running-cloud-controller/)接管。 +从 1.11 开始,默认情况下禁用此准入控制器。 + +### PodNodeSelector {#podnodeselector} + + +该准入控制器通过读取命名空间注解和全局配置,来为命名空间中可以可以使用的节点选择器设置默认值并实施限制。 -#### 配置文件格式 - -PodNodeSelector 插件使用准入配置文件 `--admission-control-config-file` 来设置后端行为的配置选项。 - -请注意,配置文件格式将在未来版本中移至版本化文件。 - - -这个文件可能是 json 或 yaml ,格式如下: + +#### 配置文件格式 + +`PodNodeSelector` 使用配置文件来设置后端行为的选项。 +请注意,配置文件格式将在将来某个版本中迁移为版本化文件。 +该文件可以是 json 或 yaml,格式如下: ```yaml podNodeSelectorPluginConfig: - clusterDefaultNodeSelector: - namespace1: - namespace2: + clusterDefaultNodeSelector: name-of-node-selector + namespace1: name-of-node-selector + namespace2: name-of-node-selector ``` + +从文件中引用 `PodNodeSelector` 配置文件,提供给 API 服务器命令行标志 `--admission-control-config-file`: + +{{< tabs name="podnodeselector_example1" >}} +{{% tab name="apiserver.config.k8s.io/v1" %}} +```yaml +apiVersion: apiserver.config.k8s.io/v1 +kind: AdmissionConfiguration +plugins: +- name: PodNodeSelector + path: podnodeselector.yaml +... +``` +{{% /tab %}} +{{% tab name="apiserver.k8s.io/v1alpha1" %}} +```yaml +# Deprecated in v1.17 in favor of apiserver.config.k8s.io/v1 +apiVersion: apiserver.k8s.io/v1alpha1 +kind: AdmissionConfiguration +plugins: +- name: PodNodeSelector + path: podnodeselector.yaml +... +``` +{{% /tab %}} +{{< /tabs >}} + #### 配置注解格式 - -PodNodeSelector 插件使用键为 `scheduler.alpha.kubernetes.io/node-selector` 的注解将节点选择器分配给 namespace 。 + +`PodNodeSelector` 使用键为 `scheduler.alpha.kubernetes.io/node-selector` 的注解将节点选择器分配给命名空间。 ```yaml apiVersion: v1 kind: Namespace metadata: annotations: - scheduler.alpha.kubernetes.io/node-selector: + scheduler.alpha.kubernetes.io/node-selector: name-of-node-selector name: namespace3 ``` -### PodSecurityPolicy + + +#### 内部行为 + +该准入控制器行为如下: +1. 如果 `Namespace` 的注解带有键 `scheduler.alpha.kubernetes.io/node-selector` ,则将其值用作节点选择器。 +2. 如果命名空间缺少此类注解,则使用 `PodNodeSelector` 插件配置文件中定义的 `clusterDefaultNodeSelector` 作为节点选择器。 +3. 评估 pod 节点选择器和命名空间节点选择器是否存在冲突。存在冲突将导致拒绝。 +4. 评估 pod 节点选择器和命名空间的白名单定义的插件配置文件是否存在冲突。存在冲突将导致拒绝。 + +{{< note >}} + +PodNodeSelector 允许 Pod 强制在特定标签的节点上运行。另请参阅 PodTolerationRestriction 准入插件,该插件可防止 Pod 在特定污点的节点上运行。 +{{< /note >}} + +### PersistentVolumeClaimResize {#persistentvolumeclaimresize} + + +该准入控制器检查传入的 `PersistentVolumeClaim` 调整大小请求,对其执行额外的验证操作。 + +{{< note >}} + +对调整卷大小的支持是一种 Alpha 特性。管理员必须将特性门控 `ExpandPersistentVolumes` 设置为 `true` 才能启用调整大小。 +{{< /note >}} + + +启用 `ExpandPersistentVolumes` 特性门控之后,建议将 `PersistentVolumeClaimResize` 准入控制器也启用。除非 PVC 的 `StorageClass` 明确地将 `allowVolumeExpansion` 设置为 `true` 来显式启用调整大小。否则,默认情况下该准入控制器会阻止所有对 PVC 大小的调整。 + +例如:由以下 `StorageClass` 创建的所有 `PersistentVolumeClaim` 都支持卷容量扩充: + +```yaml +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: gluster-vol-default +provisioner: kubernetes.io/glusterfs +parameters: + resturl: "http://192.168.10.100:8080" + restuser: "" + secretNamespace: "" + secretName: "" +allowVolumeExpansion: true +``` + + + +关于持久化卷申领的更多信息,请参见 [PersistentVolumeClaims](/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims)。 + +### PodPreset {#podpreset} + + + +该准入控制器根据与 PodPreset 中条件的匹配情况,将指定字段注入一个 pod。 +另请参见 [PodPreset 概念](/docs/concepts/workloads/pods/podpreset/)和[使用 PodPreset 将信息注入 Pod](/docs/tasks/inject-data-application/podpreset) 获取详情。 + +### PodSecurityPolicy {#podsecuritypolicy} + + -此插件负责在创建和修改 pod 时根据请求的安全上下文和可用的 pod 安全策略确定是否应该通过 pod。 +此准入控制器负责在创建和修改 pod 时根据请求的安全上下文和可用的 pod 安全策略确定是否可以执行请求。 -查看 [Pod 安全策略文档](/docs/concepts/policy/pod-security-policy/) 了解更多细节。 +查看 [Pod 安全策略文档](/docs/concepts/policy/pod-security-policy/)了解更多细节。 -### NodeRestriction +### PodTolerationRestriction {#podtolerationrestriction} -这个插件限制了 kubelet 可以修改的 `Node` 和 `Pod` 对象。 为了受到这个入场插件的限制,kubelet 必须在 `system:nodes` 组中使用凭证,并使用 `system:node:` 形式的用户名。这样的 kubelet 只允许修改自己的 `Node` API 对象,只能修改绑定到节点本身的 `Pod` 对象。 - -未来的版本可能会添加额外的限制,以确保 kubelet 具有正确操作所需的最小权限集。 + +该准入控制器首先验证 Pod 的容忍度与其命名空间的容忍度之间的冲突。如果存在冲突,则拒绝 Pod 请求。 +然后,它将命名空间的容忍度合并到 pod 的容忍度中,之后根据命名空间的容忍度白名单检查所得到的容忍度结果。 +如果检查成功,则将接受 pod 请求,否则拒绝该请求。 -## 是否有推荐的一组插件可供使用? + +如果 pod 的命名空间没有任何关联的默认容忍度或容忍度白名单,则使用集群级别的默认容忍度或容忍度白名单(如果有的话)。 -有。 -对于 Kubernetes >= 1.6.0 版本,我们强烈建议运行以下一系列准入控制插件(顺序也很重要) +命名空间的容忍度通过注解健 `scheduler.alpha.kubernetes.io/defaultTolerations` 和 `scheduler.alpha.kubernetes.io/tolerationsWhitelist` 设置。 -```shell ---admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,ResourceQuota,DefaultTolerationSeconds -``` -对于 Kubernetes >= 1.4.0 版本,我们强烈建议运行以下一系列准入控制插件(顺序也很重要) +### Priority {#priority} -```shell ---admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota -``` +The priority admission controller uses the `priorityClassName` field and populates the integer value of the priority. If the priority class is not found, the Pod is rejected. +--> + +### 优先级 {#priority} + +优先级准入控制器使用 `priorityClassName` 字段并用整型值填充优先级。如果找不到优先级,则拒绝 Pod。 + +### ResourceQuota {#resourcequota} -对于 Kubernetes >= 1.2.0 版本,我们强烈建议运行以下一系列准入控制插件(顺序也很重要) - -```shell ---admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,ResourceQuota -``` +该准入控制器会监测传入的请求,并确保它不违反任何一个 `Namespace` 中的 `ResourceQuota` 对象中枚举出来的约束。 +如果您在 Kubernetes 部署中使用了 `ResourceQuota` ,您必须使用这个准入控制器来强制执行配额限制。 -对于 Kubernetes >= 1.0.0 版本,我们强烈建议运行以下一系列准入控制插件(顺序也很重要) +请查看 [resourceQuota 设计文档](https://git.k8s.io/community/contributors/design-proposals/admission_control_resource_quota.md)和 [Resource Quota 例子](/docs/concepts/policy/resource-quotas/)了解更多细节。 -```shell ---admission-control=NamespaceLifecycle,LimitRanger,SecurityContextDeny,ServiceAccount,PersistentVolumeLabel,ResourceQuota -``` + + + +### 容器运行时类 {#runtimeclass} {{< feature-state for_k8s_version="v1.16" state="alpha" >}} + +[容器运行时类](/docs/concepts/containers/runtime-class/)定义描述了与运行 Pod 相关的开销。此准入控制器将相应地设置 pod.Spec.Overhead 字段。 + +详情请参见 [Pod 开销](/docs/concepts/configuration/pod-overhead/)。 + +### SecurityContextDeny {#securitycontextdeny} + + +该准入控制器将拒绝任何试图设置特定提升 [SecurityContext](/docs/user-guide/security-context) 字段的 pod。 +如果集群没有使用 [pod 安全策略](/docs/user-guide/pod-security-policy)来限制安全上下文所能获取的值集,那么应该启用这个功能。 + +### ServiceAccount {#serviceaccount} + + +该准入控制器实现了 [serviceAccounts](/docs/user-guide/service-accounts) 的自动化。 +如果您打算使用 Kubernetes 的 ServiceAccount 对象,我们强烈建议您使用这个准入控制器。 + +### StorageObjectInUseProtection + + +`StorageObjectInUseProtection` 插件将 `kubernetes.io/pvc-protection` 或 `kubernetes.io/pv-protection` finalizers 添加到新创建的持久化卷声明(PVC)或持久化卷(PV)中。 如果用户尝试删除 PVC/PV,除非 PVC/PV 的保护控制器移除 finalizers,否则 PVC/PV 不会被删除。有关更多详细信息,请参考[保护使用中的存储对象](/docs/concepts/storage/persistent-volumes/#storage-object-in-use-protection)。 + +### TaintNodesByCondition {#taintnodesbycondition} {{< feature-state for_k8s_version="v1.12" state="beta" >}} + + +该准入控制器 {{< glossary_tooltip text="污点" term_id="taint" >}} 新创建的 `NotReady` 和 `NoSchedule` 节点。 +避免了可能导致 Pod 在更新其污点以准确反映其所报告状况之前,就安排了在新节点上的竞争条件的情况。 + +### ValidatingAdmissionWebhook {#validatingadmissionwebhook} {{< feature-state for_k8s_version="v1.13" state="beta" >}} + + +该准入控制器调用与请求匹配的所有验证 webhook。匹配的 webhook 将被并行调用。如果其中任何一个拒绝请求,则整个请求将失败。 +该准入控制器仅在验证阶段运行;与 `MutatingAdmissionWebhook` 准入控制器所调用的 webhook 相反,它调用的 webhook 应该不会使对象出现变更。 + + +如果以此方式调用的 webhook 有其它作用(如,配额递减),则它必须具有协调系统,因为不能保证后续的 webhook 或其他有效的准入控制器都允许请求完成。 + + +如果您禁用了 ValidatingAdmissionWebhook,还必须在 `admissionregistration.k8s.io/v1beta1` 组/版本中使用 `--runtime-config` 标志来禁用 `ValidatingWebhookConfiguration` 对象(默认情况下在 1.9 版和更高版本中均处于启用状态)。 + + + +## 有推荐的准入控制器吗? + +有,对于 Kubernetes 1.10 以上的版本,推荐使用的准入控制器默认情况下都处于启用状态(查看[这里](/docs/reference/command-line-tools-reference/kube-apiserver/#options))。 +因此您无需显式指定它们。您可以使用 `--enable-admission-plugins` 标志( **顺序不重要** )来启用默认设置以外的其他准入控制器。 + +{{< note >}} + +`--admission-control` 在 1.10 中已废弃,已由 `--enable-admission-plugins` 取代。 +{{< /note >}} + + + +对于 Kubernetes 1.9 及更早版本,我们建议使用 `--admission-control` 标志(**顺序很重要**)运行下面的一组准入控制器。 + +* v1.9 + + ```shell + --admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota + ``` + + + +* 需要重申的是,在 1.9 中,它们都发生在变更阶段和验证阶段,例如 `ResourceQuota` 在验证阶段运行,因此是最后一个运行的准入控制器。 + `MutatingAdmissionWebhook` 出现在此列表的前面,因为它在变更阶段运行。 + + + 对于更早期版本,没有验证和变更的概念,并且准入控制器按照指定的确切顺序运行。 + +{{% /capture %}} diff --git a/content/zh/docs/reference/access-authn-authz/rbac.md b/content/zh/docs/reference/access-authn-authz/rbac.md new file mode 100644 index 0000000000..5f3adb0190 --- /dev/null +++ b/content/zh/docs/reference/access-authn-authz/rbac.md @@ -0,0 +1,2138 @@ +--- +title: 使用 RBAC 鉴权 +content_template: templates/concept +weight: 70 +--- + + + +{{% capture overview %}} + +基于角色(Role)的访问控制(RBAC)是一种基于企业中用户的角色来调节控制对计算机或网络资源的访问方法。 +{{% /capture %}} + +{{% capture body %}} + +`RBAC` 使用 `rbac.authorization.k8s.io` {{< glossary_tooltip text="API 组" term_id="api-group" >}} +来驱动鉴权操作,允许管理员通过 Kubernetes API 动态配置策略。 + +在 1.8 版本中,RBAC 模式是稳定的并通过 rbac.authorization.k8s.io/v1 API 提供支持。 + +要启用 RBAC,在启动 API 服务器时添加 `--authorization-mode=RBAC` 参数。 + + + +## API 概述 + +本节介绍 RBAC API 所声明的四种顶级类型。用户可以像与其他 API 资源交互一样, +(通过 `kubectl`、API 调用等方式)与这些资源交互。例如, +命令 `kubectl apply -f (resource).yml` 可以用在这里的任何一个例子之上。 +尽管如此,建议读者循序渐进阅读下面的章节,由浅入深。 + + +### Role 和 ClusterRole + +在 RBAC API 中,一个角色包含一组相关权限的规则。权限是纯粹累加的(不存在拒绝某操作的规则)。 +角色可以用 `Role` 来定义到某个命名空间上, +或者用 `ClusterRole` 来定义到整个集群作用域。 + +一个 `Role` 只可以用来对某一命名空间中的资源赋予访问权限。 +下面的 `Role` 示例定义到名称为 "default" 的命名空间,可以用来授予对该命名空间中的 Pods 的读取权限: + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + namespace: default + name: pod-reader +rules: +- apiGroups: [""] # "" 指定核心 API 组 + resources: ["pods"] + verbs: ["get", "watch", "list"] +``` + +`ClusterRole` 可以授予的权限和 `Role` 相同, +但是因为 `ClusterRole` 属于集群范围,所以它也可以授予以下访问权限: + +* 集群范围资源 (比如 nodes) +* 非资源端点(比如 "/healthz") +* 跨命名空间访问的有名字空间作用域的资源(如 Pods),比如运行命令`kubectl get pods --all-namespaces` 时需要此能力 + +下面的 `ClusterRole` 示例可用来对某特定命名空间下的 Secrets 的读取操作授权, +或者跨所有命名空间执行授权(取决于它是如何[绑定](#rolebinding-and-clusterrolebinding)的): + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + # 此处的 "namespace" 被省略掉是因为 ClusterRoles 是没有命名空间的。 + name: secret-reader +rules: +- apiGroups: [""] + resources: ["secrets"] + verbs: ["get", "watch", "list"] +``` + + +### RoleBinding 和 ClusterRoleBinding + +角色绑定(RoleBinding)是将角色中定义的权限赋予一个或者一组用户。 +它包含若干主体(用户,组和服务账户)的列表和对这些主体所获得的角色的引用。 +可以使用 `RoleBinding` 在指定的命名空间中执行授权, +或者在集群范围的命名空间使用 `ClusterRoleBinding` 来执行授权。 + +一个 `RoleBinding` 可以引用同一的命名空间中的 `Role` 。 +下面的例子 `RoleBinding` 将 "pod-reader" 角色授予在 "default" 命名空间中的用户 "jane"; +这样,用户 "jane" 就具有了读取 "default" 命名空间中 pods 的权限。 + +`roleRef` 里的内容决定了实际创建绑定的方法。`kind` 可以是 `Role` 或 `ClusterRole`, +`name` 将引用你要指定的 `Role` 或 `ClusterRole` 的名称。在下面的例子中,角色绑定使用 +`roleRef` 将用户 "jane" 绑定到前文创建的角色 `Role`,其名称是 `pod-reader`。 + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +# 此角色绑定使得用户 "jane" 能够读取 "default" 命名空间中的 Pods +kind: RoleBinding +metadata: + name: read-pods + namespace: default +subjects: +- kind: User + name: jane # Name is case sensitive + apiGroup: rbac.authorization.k8s.io +roleRef: + kind: Role #this must be Role or ClusterRole + name: pod-reader # 这里的名称必须与你想要绑定的 Role 或 ClusterRole 名称一致 + apiGroup: rbac.authorization.k8s.io +``` + + +`RoleBinding` 也可以引用 `ClusterRole`,对 `ClusterRole` 所定义的、位于 `RoleBinding` 命名空间内的资源授权。 +这可以允许管理者在 +整个集群中定义一组通用的角色,然后在多个命名空间中重用它们。 + +例如下面的例子,`RoleBinding` 指定的是 `ClusterRole`, +"dave" (主体,区分大小写)将只可以读取在"development" +命名空间( `RoleBinding` 的命名空间)中的"secrets"。 + + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +# 这个角色绑定允许 "dave" 用户在 "development" 命名空间中有读取 secrets 的权限。 +kind: RoleBinding +metadata: + name: read-secrets + namespace: development # 这里只授予 "development" 命名空间的权限。 +subjects: +- kind: User + name: dave # 名称区分大小写 + apiGroup: rbac.authorization.k8s.io +roleRef: + kind: ClusterRole + name: secret-reader + apiGroup: rbac.authorization.k8s.io +``` + + + +最后,`ClusterRoleBinding` 可用来在集群级别或对所有命名空间执行授权。 +下面的例子允许 "manager" 组中的任何用户读取任意命名空间中 "secrets"。 + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +# 这个集群角色绑定允许 "manager" 组中的任何用户读取任意命名空间中 "secrets"。 +kind: ClusterRoleBinding +metadata: + name: read-secrets-global +subjects: +- kind: Group + name: manager # 名称区分大小写 + apiGroup: rbac.authorization.k8s.io +roleRef: + kind: ClusterRole + name: secret-reader + apiGroup: rbac.authorization.k8s.io +``` + +你不能修改绑定对象所引用的 `Role` 或 `ClusterRole` 。 +试图改变绑定对象的 `roleRef` 将导致验证错误。想要 +改变现有绑定对象中 `roleRef` 字段的内容,必须删除并 +重新创建绑定对象。这种限制有两个主要原因: + +1.关于不同角色的绑定是完全不一样的。更改 `roleRef` + 需要删除/重建绑定,确保要赋予绑定的完整主体列表是新 +的角色(而不是只是启用修改 `roleRef` 在不验证所有现有 +主体的情况下的,应该授予新角色对应的权限)。 + +2.使得 `roleRef` 不可以改变现有绑定主体用户的 `update` 权限, +这样可以让它们能够管理主体列表,而不能更改授予这些主体相关 +的角色。 + +命令 `kubectl auth reconcile` 可以创建或者更新包含 RBAC 对象的清单文件, +并且在必要的情况下删除和重新创建绑定对象,以改变所引用的角色。 +更多相关信息请参照[命令用法和示例](#kubectl-auth-reconcile) + + +### 对资源的引用 + +大多数资源都是使用名称的字符串表示,例如在相关的 API 端点的 URL 之中出现的 "pods" 。 +然而有一些 Kubernetes API 涉及 "子资源(subresources)",例如 pod 的日志。Pod 日志相关的端点 URL 如下: + +```http +GET /api/v1/namespaces/{namespace}/pods/{name}/log +``` + +在这种情况下,"pods" 是有命名空间的资源,而 "log" 是 pods 的子资源。在 RBAC 角色中, +使用"/"分隔资源和子资源。允许一个主体要同时读取 pods 和 pod logs,你可以这么写: + + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + namespace: default + name: pod-and-pod-logs-reader +rules: +- apiGroups: [""] + resources: ["pods", "pods/log"] + verbs: ["get", "list"] +``` + + +对于某些请求,也可以通过 `resourceNames` 列表按名称引用资源。 +在指定时,可以将请求类型限制资源的单个实例。限制只可以 "get" 和 "update" +的单一configmap,你可以这么写: + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + namespace: default + name: configmap-updater +rules: +- apiGroups: [""] + resources: ["configmaps"] + resourceNames: ["my-configmap"] + verbs: ["update", "get"] +``` + +需要注意的是,`create` 请求不能被 resourceName 限制,因为在鉴权时还不知道对象名称。 +另一个例外是 `deletecollection`。 + + +### Aggregated ClusterRoles + +从 1.9 开始,集群角色(ClusterRole)可以通过使用 `aggregationRule` 的方式并组合其他 ClusterRoles 来创建。 +聚合集群角色的权限是由控制器管理的,方法是通过过滤与标签选择器匹配的 ClusterRules,并将其中的权限进行组合。 +一个聚合集群角色的示例如下: + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: monitoring +aggregationRule: + clusterRoleSelectors: + - matchLabels: + rbac.example.com/aggregate-to-monitoring: "true" +rules: [] # 具体规则由控制器管理器自动填写。 +``` + +创建一个与标签选择器匹配的 ClusterRole 之后,其上定义的规则将成为聚合集群角色的一部分。在下面的例子中, +通过创建一个新的、标签同样为 `rbac.example.com/aggregate-to-monitoring: true` 的 +ClusterRole,新的规则可被添加到 "monitoring" 集群角色中。 + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: monitoring-endpoints + labels: + rbac.example.com/aggregate-to-monitoring: "true" +# 这些规则将被添加到 "monitoring" 角色中。 +rules: +- apiGroups: [""] + resources: ["services", "endpoints", "pods"] + verbs: ["get", "list", "watch"] +``` + + + +默认的面向用户的角色(如下所述)使用 ClusterRole 聚合。这使得管理者可以为自定义资源设置使用规则属性, +比如通过 CustomResourceDefinitions 或聚合 API 服务器为默认角色提供的服务。 + +例如,在以下 ClusterRoles 中让 "admin" 和 "edit" 拥有管理自定义资源 "CronTabs" 的权限, + "view" 角色对资源有只读操作权限。 + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: aggregate-cron-tabs-edit + labels: + # 将这些权限添加到默认角色 "admin" 和 "edit" 中。 + rbac.authorization.k8s.io/aggregate-to-admin: "true" + rbac.authorization.k8s.io/aggregate-to-edit: "true" +rules: +- apiGroups: ["stable.example.com"] + resources: ["crontabs"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +--- +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: aggregate-cron-tabs-view + labels: + # 将这些权限添加到默认角色 "view" 中。 + rbac.authorization.k8s.io/aggregate-to-view: "true" +rules: +- apiGroups: ["stable.example.com"] + resources: ["crontabs"] + verbs: ["get", "list", "watch"] +``` + + +#### 角色示例 + +在以下示例中,我们仅截取展示了 `rules` 对应部分, +允许读取在核心 {{< glossary_tooltip text="API 组" term_id="api-group" >}}下的 Pods: + +```yaml +rules: +- apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list", "watch"] +``` + +允许读/写在 "extensions" 和 "apps" API 组中的 "deployments" 资源: + +```yaml +rules: +- apiGroups: ["extensions", "apps"] + resources: ["deployments"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +``` + +允许读取 "pods" 和读/写 "jobs" : + +```yaml +rules: +- apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list", "watch"] +- apiGroups: ["batch", "extensions"] + resources: ["jobs"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +``` + + +允许读取名称为 "my-config"的 `ConfigMap` (需要通过 `RoleBinding` 绑定带某名字空间中特定的 `ConfigMap`): + +```yaml +rules: +- apiGroups: [""] + resources: ["configmaps"] + resourceNames: ["my-config"] + verbs: ["get"] +``` + +允许读取在核心组中的 "nodes" 资源(因为 `Node` 是集群范围的,所以需要 `ClusterRole` 绑定到 `ClusterRoleBinding` 才生效) + +```yaml +rules: +- apiGroups: [""] + resources: ["nodes"] + verbs: ["get", "list", "watch"] +``` + +允许在非资源端点 "/healthz" 和其子路径上发起 "GET" 和 "POST" 请求(必须在 `ClusterRole` 绑定 `ClusterRoleBinding` 才生效) + +```yaml +rules: +- nonResourceURLs: ["/healthz", "/healthz/*"] # '*' 在 nonResourceURL 中的意思是后缀全局匹配。 + verbs: ["get", "post"] +``` + + +### 对主体的引用 + +`RoleBinding` 或者 `ClusterRoleBinding` 需要绑定角色到 *主体*。 +主体可以是组,用户或者服务账户。 + +用户是由字符串表示,它们可以是普通的用户名,像 "alice",或者是 +邮件格式 "bob@example.com",或者是数字ID。由 Kubernetes 管理员配置[身份认证模块](/docs/reference/access-authn-authz/authentication/) +需要的格式。RBAC 鉴权系统不对格式作任何要求,但是前缀 `system:` 是 Kubernetes 系统保留的, +所以管理员要确保配置的用户名不能出现上述前缀格式。 + +用户组信息是 Kubernetes 现在提供的一种身份验证模块,与用户一样,对组的字符串没有格式要求, +只是不能使用保留的前缀 `system:` 。 + +[服务账号](/docs/tasks/configure-pod-container/configure-service-account/) 的用户名前缀为`system:serviceaccount:`, +属于前缀为 `system:serviceaccounts:` 的用户组。 + + +#### RoleBinding的示例 + +下面的示例只是展示 `RoleBinding` 中 `subjects` 的部分。 + +用户的名称为 "alice@example.com": + +```yaml +subjects: +- kind: User + name: "alice@example.com" + apiGroup: rbac.authorization.k8s.io +``` + +组的名称为 "frontend-admins": + +```yaml +subjects: +- kind: Group + name: "frontend-admins" + apiGroup: rbac.authorization.k8s.io +``` + +服务账号在 kube-system 命名空间中: + +```yaml +subjects: +- kind: ServiceAccount + name: default + namespace: kube-system +``` + +在名称为 "qa" 命名空间中所有的服务账号: + +```yaml +subjects: +- kind: Group + name: system:serviceaccounts:qa + apiGroup: rbac.authorization.k8s.io +``` + + + +所有的服务账号: + +```yaml +subjects: +- kind: Group + name: system:serviceaccounts + apiGroup: rbac.authorization.k8s.io +``` + +所有认证过的用户 (版本 1.5+): + +```yaml +subjects: +- kind: Group + name: system:authenticated + apiGroup: rbac.authorization.k8s.io +``` + +所有未认证的用户 (版本 1.5+): + +```yaml +subjects: +- kind: Group + name: system:unauthenticated + apiGroup: rbac.authorization.k8s.io +``` + +所有用户 (版本 1.5+): + +```yaml +subjects: +- kind: Group + name: system:authenticated + apiGroup: rbac.authorization.k8s.io +- kind: Group + name: system:unauthenticated + apiGroup: rbac.authorization.k8s.io +``` + + +## 默认 Roles 和 Role Bindings + +API servers创建一组默认为 `ClusterRole` 和 `ClusterRoleBinding` 的对象。 +其中许多是以 `system:` 为前缀的,它表示资源是基础设施 "owned" 的。对于这些资源的修改可能导致集群功能失效。 +例如,`system:node` 是集群角色,它是定义 kubelets 相关的权限,如果这个角色被修改,它将导致 kubelets 无法正常工作。 + +所有默认的 ClusterRole 和 ClusterRoleBinding 对象都会被标记为 `kubernetes.io/bootstrapping=rbac-defaults`。 + + +### 自动更新 + +在每次启动时,API Server 都会更新默认 ClusterRole 所缺少的各种权限,并更新默认 ClusterRoleBinding 所缺少的各个角色绑定主体。 +这种自动更新机制允许集群去修复一些特殊的修改。 +由于权限和角色绑定主体在新的 Kubernetes 版本中可能发生变化,所以这样的话也能够保证角色和角色绑定始终保持是最新的。 + +如果要禁止此功能,请将默认ClusterRole以及ClusterRoleBinding的`rbac.authorization.kubernetes.io/autoupdate`设置成`false`。 + +注意,缺乏默认权限和角色绑定主体可能会导致非功能性集群问题。 + +自动更新功能在 Kubernetes 版本1.6+ 的 RBAC 认证是默认开启的。 + + +### Discovery Roles + +无论是经过身份验证的还是未经过身份验证的用户,默认角色的用户读取API被认为是安全的,可以公开访问(包括CustomResourceDefinitions), +如果要禁用匿名未经过身份验证的用户访问,请在 API server 中添加 `--anonymous-auth=false` 的配置选项。 + +通过运行命令 `kubectl` 可以查看这些角色的配置信息: + +``` +kubectl get clusterroles system:discovery -o yaml +``` + +注意:不建议编辑这个角色,因为更改将在 API server 重启时自动更新时覆盖(见上文) + +
    + + + + + + + + + + + + + + + + + + + + + +
    默认 ClusterRole默认 ClusterRoleBinding描述
    system:basic-usersystem:authenticated允许用户以只读的方式去访问他们自己的基本信息。在1.14版本之前,这个角色在默认情况下也绑定在 `system:unauthenticated` 上。
    system:discoverysystem:authenticated允许以只读方式访问 API 发现端点,这些端点用来发现和协商 API 级别。在1.14版本之前,这个角色在默认情况下绑定在 `system:unauthenticated` 上。
    system:public-info-viewersystem:authenticatedsystem:unauthenticated允许对集群的非敏感信息进行只读访问,它是在1.14版本中引入的。
    + + +### 面向用户的角色 + +一些默认的角色不是前缀 `system:` 开头的。这些是面向用户的角色。它们包括 super-user 角色(`cluster-admin`), +使用 ClusterRoleBindings (`cluster-status`)在集群范围内授予角色, +以及使用 RoleBindings (`admin`, `edit`, `view`)在特定命名空间中授予的角色。 + +在 1.9 开始,面向用户的角色使用[ClusterRole Aggregation](#aggregated-clusterroles)允许管理员在包含这些角色上的 +自定义资源上添加规则。如果想要添加 "admin" "edit" 或者 "view" ,需要先创建使用以下一个或多个的 ClusterRole 的标签: + +```yaml +metadata: + labels: + rbac.authorization.k8s.io/aggregate-to-admin: "true" + rbac.authorization.k8s.io/aggregate-to-edit: "true" + rbac.authorization.k8s.io/aggregate-to-view: "true" +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    默认 ClusterRole默认 ClusterRoleBinding描述
    cluster-adminsystem:masters允许超级用户在平台上的任何资源的所有操作。 +当在 ClusterRoleBinding 中使用时,可以授权对集群中以及所有命名空间中的全部资源进行完全控制。 +当在 RoleBinding 中使用时,可以授权控制 RoleBinding 所在命名空间中的所有资源,包括命名空间本身。
    admin允许管理员访问权限,旨在使用 RoleBinding 在命名空间内执行授权。 +如果在 RoleBinding 中使用,则可授予对命名空间中的大多数资源的读/写权限, +包括创建角色和绑定角色(RoleBinding)的能力。 +但是它不允许对资源配额或者命名空间本身进行写操作。
    edit允许对命名空间的大多数对象进行读/写操作。 +它不允许查看或者修改角色(Roles)或者角色绑定(RoleBindings)。
    view允许对命名空间的大多数对象有只读权限。 +它不允许查看角色(Roles)或角色绑定(RoleBindings)。 +它不允许查看 Secrets,因为这类操作属于越权。
    + + +### 核心组件角色 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    默认 ClusterRole默认 ClusterRoleBinding描述
    system:kube-schedulersystem:kube-scheduler 用户允许访问 kube-scheduler 组件所需要的资源。
    system:volume-schedulersystem:kube-scheduler 用户允许访问 kube-scheduler 组件所需要的的卷资源。
    system:kube-controller-managersystem:kube-controller-manager 用户允许访问 kube-controller-manager 组件所需要的资源。 +各个控制环所需要的权限包含在 controller roles 之中。
    system:node在版本1.8之后无允许访问 kubelet 组件所需要的资源,它包括读取所有的 Secrets 和对所有 Pod 状态对象的写操作。 + +从版本 1.7 开始,推荐使用 Node authorizerNodeRestriction 准入插件 来代替这个角色,它允许基于 kubelet 上调度执行的 Pods 来授权对 kubelet API 的访问。 +在版本 1.7 之前,这个角色会自动绑定到 `system:nodes` 组。 +在版本 1.7中,如果未启用`Node` 鉴权模式,这个角色将自动绑定到 `system:nodes` 组 +在版本 1.8+ 之后,不再自动创建绑定。 +
    system:node-proxiersystem:kube-proxy 用户允许访问 kube-proxy 组件所需要的资源。
    + + +### 其他组件角色 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    默认 ClusterRole默认 ClusterRoleBinding描述
    system:auth-delegator允许代理身份认证和鉴权, +它通常用在插件式 API 服务器上,以实现统一的身份认证和鉴权。
    system:heapsterHeapster 组件定义的角色。
    system:kube-aggregatorkube-aggregator 组件定义的角色。
    system:kube-dnskube-system命名空间中的kube-dns服务账号kube-dns 组件定义的角色。
    system:kubelet-api-admin允许完全访问 kubelet API 。
    system:node-bootstrapper允许访问执行 +Kubelet TLS 启动引导 所需要的资源。
    system:node-problem-detectornode-problem-detector 组件定义的角色。
    system:persistent-volume-provisioner允许访问大部分的 动态卷驱动 所需要的资源。
    + + +### 控制器角色 {#controller-roles} + +[Kubernetes 控制器管理器](/docs/admin/kube-controller-manager/) 运行核心控制环。 +当使用 `--use-service-account-credentials` 参数时, 每个控制环使用一个单独的服务账号启动。 +每个控制环都有相应的、前缀为 `system:controller:` 的角色。 +如果控制管理器启动时未设置 `--use-service-account-credentials`, +它使用自己的身份信息来运行所有的控制环,该身份必须被授予所有相关的角色。 +这些角色包括: + +* system:controller:attachdetach-controller +* system:controller:certificate-controller +* system:controller:clusterrole-aggregation-controller +* system:controller:cronjob-controller +* system:controller:daemon-set-controller +* system:controller:deployment-controller +* system:controller:disruption-controller +* system:controller:endpoint-controller +* system:controller:expand-controller +* system:controller:generic-garbage-collector +* system:controller:horizontal-pod-autoscaler +* system:controller:job-controller +* system:controller:namespace-controller +* system:controller:node-controller +* system:controller:persistent-volume-binder +* system:controller:pod-garbage-collector +* system:controller:pv-protection-controller +* system:controller:pvc-protection-controller +* system:controller:replicaset-controller +* system:controller:replication-controller +* system:controller:resourcequota-controller +* system:controller:root-ca-cert-publisher +* system:controller:route-controller +* system:controller:service-account-controller +* system:controller:service-controller +* system:controller:statefulset-controller +* system:controller:ttl-controller + + +## 初始化与预防权限升级 + +RBAC API 会阻止用户通过编辑角色或者角色绑定来升级权限。 +由于这一点是在 API 级别实现的,所以在 RBAC 鉴权器(RBAC authorizer)未启用的状态下依然可以正常工作。 + +用户只有在符合下列条件之一的情况下,才能创建/更新角色: + + +1. 他们已经拥有角色中包含的所有权限,且其作用域与正被修改的对象相同。 +(对 `ClusterRole` 而言意味着集群范围,对 `Role` 而言意味着相同命名空间或者集群范围) +2. 他们被明确允许在 `rbac.authorization.k8s.io` API 组中的 `roles` 或者 `clusterroles` 资源上使用 `escalate` 动词(Kubernetes 版本 1.12 及以上) + +例如,如果 "user-1" 没有列举集群范围所有 Secrets 的权限,他将不能创建包含对应权限的 `ClusterRole`。 +若要允许用户创建/更新角色: + +根据需要授予他们一个角色,允许他们根据需要创建/更新 `Role` 或者 `ClusterRole` 对象。 +2. 授予他们在所创建/更新角色中包含特殊权限的权限: + * 隐式的,通过给他们权限(如果它们试图创建或者更改 `Role` 或 `ClusterRole` 的权限,但自身没有被授权,API 请求将被禁止) + * 或通过允许他们在 `Role` 或 `ClusterRole` 资源上执行 `escalate` 动作的权限,它包含在 `rbac.authorization.k8s.io` API 组中 (Kubernetes 1.12 及以上版本) + +如果用户已经拥有引用角色中包含的权限,那他则只能创建/更新角色绑定。 +(在角色绑定相同的作用域内)*或* 如果他们被授予对所引用角色执行 `bind` 操作的显式权限。 +例如,如果 "user-1" 没有集群范围内 Secret 的列表权限,他就不能创建可以授予角色权限的 `ClusterRoleBinding`。 +通过以下方法可以允许用户创建/更新角色绑定: + +授予他们一个角色,允许他们根据需要创建/更新 `RoleBinding` 或者`ClusterRoleBinding` 对象。 +2. 授予他们绑定特定角色所需的权限: + * 隐式地,通过给他们授予角色中包含的权限。 + * 显式地,通过允许他们对特定角色(或集群角色)执行`bind` 操作的权限。 + + +例如,这个集群角色和角色绑定将允许 "user-1" 有对"user-1-namespace" 命名空间中的角色执行 `admin`、`edit` 和 `view` 操作权限: + +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: role-grantor +rules: +- apiGroups: ["rbac.authorization.k8s.io"] + resources: ["rolebindings"] + verbs: ["create"] +- apiGroups: ["rbac.authorization.k8s.io"] + resources: ["clusterroles"] + verbs: ["bind"] + resourceNames: ["admin","edit","view"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: role-grantor-binding + namespace: user-1-namespace +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: role-grantor +subjects: +- apiGroup: rbac.authorization.k8s.io + kind: User + name: user-1 +``` + +当初始化第一个角色和角色绑定时,需要为初始用户授予他们尚未拥有的权限。 对初始角色和角色绑定进行初始化时需要: + +* 使用用户组为 `system:masters` 的凭据,该用户组由默认绑定关联到 `cluster-admin` 这个超级用户角色。 +* 如果你的 API server 启动时启用了不安全端口(使用`--insecure-port`), 你也可以通过该端口调用 API ,这样操作会绕过身份验证或鉴权。 + + +## 一些命令行工具 + +### `kubectl create role` + +创建 `Role` 对象,定义在某命名空间中的权限。例如: + +* 创建名称为 "pod-reader" 的 `Role` 对象,允许用户对 pods 执行 "get"、"watch" 和 "list" 操作: + + ``` + kubectl create role pod-reader --verb=get --verb=list --verb=watch --resource=pods + ``` + +* 创建名称为 "pod-reader" 的 `Role` 对象并指定 resourceNames: + + ``` + kubectl create role pod-reader --verb=get --resource=pods --resource-name=readablepod --resource-name=anotherpod + ``` + +* 创建名为 "foo" 的 `Role` 对象并指定 apiGroups: + + ``` + kubectl create role foo --verb=get,list,watch --resource=replicasets.apps + ``` + +* 创建名为 "foo" 的 `Role` 对象并指定子资源权限: + + ``` + kubectl create role foo --verb=get,list,watch --resource=pods,pods/status + ``` + +* 创建名为 "my-component-lease-holder" 的 `Role` 对象,使其具有对特定名称资源执行 get/update 的权限: + + ``` + kubectl create role my-component-lease-holder --verb=get,list,watch,update --resource=lease --resource-name=my-component + ``` + + +### `kubectl create clusterrole` + +创建 `ClusterRole` 对象。例如: + +* 创建名称为 "pod-reader" 的 `ClusterRole` 对象,允许用户对 pods 对象执行 "get"、"watch" 和 "list" 操作: + + ``` + kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods + ``` + +* 创建名为 "pod-reader" 的 `ClusterRole` 对象并指定资源名称: + + ``` + kubectl create clusterrole pod-reader --verb=get --resource=pods --resource-name=readablepod --resource-name=anotherpod + ``` + +* 创建名为 "foo" 的 `ClusterRole` 对象并指定 apiGroups: + + ``` + kubectl create clusterrole foo --verb=get,list,watch --resource=replicasets.apps + ``` + +* 创建名为 "foo" 的`ClusterRole` 对象并指定子资源: + + ``` + kubectl create clusterrole foo --verb=get,list,watch --resource=pods,pods/status + ``` + +* 创建名为 "foo" 的 `ClusterRole` 对象并指定非资源路径: + + ``` + kubectl create clusterrole "foo" --verb=get --non-resource-url=/logs/* + ``` + +* 创建名为 "monitoring" 的 `ClusterRole` 对象并指定聚合规则: + + ``` + kubectl create clusterrole monitoring --aggregation-rule="rbac.example.com/aggregate-to-monitoring=true" + ``` + + +### `kubectl create rolebinding` + +在特定的命名空间中对 `Role` 或 `ClusterRole` 授权。例如: + +* 在命名空间 "acme" 中,将名为 `admin` 的 `ClusterRole` 中的权限授予名称 "bob" 的用户: + + ``` + kubectl create rolebinding bob-admin-binding --clusterrole=admin --user=bob --namespace=acme + ``` + +* 在命名空间 "acme"中,将名为 `view` 的 `ClusterRole` 中的权限授予该命名空间 "acme" 中名为 "myapp" 的服务账号: + + ``` + kubectl create rolebinding myapp-view-binding --clusterrole=view --serviceaccount=acme:myapp --namespace=acme + ``` + +* 在命名空间 "acme" 中,将名为 `view` 的 `ClusterRole` 对象中的权限授予命名空间 "myappnamespace" 中名称为 "myapp" 的服务账号: + + ``` + kubectl create rolebinding myappnamespace-myapp-view-binding --clusterrole=view --serviceaccount=myappnamespace:myapp --namespace=acme + ``` + + +### `kubectl create clusterrolebinding` + +在整个集群、包括所有的命名空间中对 `ClusterRole` 授权。例如: + +* 在整个集群范围,将名为 `cluster-admin` 的 `ClusterRole` 中定义的权限授予名为 "root" 用户: + + ``` + kubectl create clusterrolebinding root-cluster-admin-binding --clusterrole=cluster-admin --user=root + ``` + +* 在整个集群范围,将名为 `system:node-proxier` 的 `ClusterRole` 的权限授予名为 "system:kube-proxy" 的用户: + + ``` + kubectl create clusterrolebinding kube-proxy-binding --clusterrole=system:node-proxier --user=system:kube-proxy + ``` + +* 在整个集群范围,将名为 `view` 的 `ClusterRole` 对象中定义的权限授予 "acme" 命名空间中名为 "myapp" 的服务账号: + + ``` + kubectl create clusterrolebinding myapp-view-binding --clusterrole=view --serviceaccount=acme:myapp + ``` + + +### `kubectl auth reconcile` {#kubectl-auth-reconcile} + +使用清单文件来创建或者更新 `rbac.authorization.k8s.io/v1` API 对象。 + +尚不存在的对象会被创建,如果对应的命名空间也不存在,必要的话也会被创建。 +已经存在的角色会被更新,使之包含输入对象中所给的权限。如果指定了 `--remove-extra-permissions`,可以删除其余权限。 + +已经存在的绑定也会被更新,使之包含输入对象中所给的主体。如果指定了 `--remove-extra-permissions`,则可以删除其余主体。 + +例如: + +* 测试应用 RBAC 对象的清单文件,显示将要进行的更改: + + ``` + kubectl auth reconcile -f my-rbac-rules.yaml --dry-run + ``` + +* 应用 RBAC 对象的清单文件, 保留角色中的其余权限和绑定中的其他主体: + + ``` + kubectl auth reconcile -f my-rbac-rules.yaml + ``` + +* 应用 RBAC 对象的清单文件, 删除角色中的其他权限和绑定中的其他主体: + + ``` + kubectl auth reconcile -f my-rbac-rules.yaml --remove-extra-subjects --remove-extra-permissions + ``` + +查看 CLI 帮助获取详细的用法。 + + +## 服务账号权限 + +默认的 RBAC 策略为控制面组件、节点和控制器授予权限。 +但是不会对 `kube-system` 命名空间之外的服务账号授予权限。 +(除了授予所有已认证用户的 discovery 权限) + +这使得您可以根据需要向特定服务账号授予特定权限。 细粒度的角色绑定可带来更好的安全性,但需要更多精力管理。 +更粗粒度的授权可能导致服务账号被授予不必要的 API 访问权限(甚至导致潜在的权限升级),但更易于管理。 + +按从最安全到最不安全的顺序,存在以下方法: + +1. 为特定应用的服务账户授予角色(最佳实践) + + 这要求应用在其 pod 规范中指定 `serviceAccountName` , + 并额外创建服务账号(包括通过 API、应用程序清单、`kubectl create serviceaccount` 等)。 + + 例如,在命名空间 "my-namespace" 中授予服务账号 "my-sa" 只读权限: + + ```shell + kubectl create rolebinding my-sa-view \ + --clusterrole=view \ + --serviceaccount=my-namespace:my-sa \ + --namespace=my-namespace + ``` + +2. 将角色授予某命名空间中的 ”default” 服务账号 + + 如果一个应用没有指定 `serviceAccountName`,那么它将使用 "default" 服务账号。 + + {{< note >}}不指定 `serviceAccountName` 的话, + "default" 服务账号的权限会授予给命名空间中所有未指定 `serviceAccountName` 的 Pods。{{< /note >}} + + + 例如,在命名空间 "my-namespace" 中授予服务账号 "default" 只读权限: + + ```shell + kubectl create rolebinding default-view \ + --clusterrole=view \ + --serviceaccount=my-namespace:default \ + --namespace=my-namespace + ``` + + 许多附加组件 [add-ons](/docs/concepts/cluster-administration/addons/) 目前在 `kube-system` 命名空间以 "default" 服务账号运行。 + 要允许这些附加组件以超级用户权限运行,需要将集群的 cluster-admin 权限授予 `kube-system` 命名空间中的 "default" 服务账号。 + + {{< note >}}启用这一配置意味着在 `kube-system` 命名空间中包含以超级用户账号来访问 API 的 Secrets。{{< /note >}} + + ```shell + kubectl create clusterrolebinding add-on-cluster-admin \ + --clusterrole=cluster-admin \ + --serviceaccount=kube-system:default + ``` + + + +3. 将角色授予命名空间中所有的服务账号 + + 如果你想要在命名空间中所有的应用都具有某角色,无论它们使用的什么服务账号, + 你可以将角色授予该命名空间的服务账号组。 + + 例如,在命名空间 "my-namespace" 中的只读权限授予该命名空间中的所有服务账号: + + ```shell + kubectl create rolebinding serviceaccounts-view \ + --clusterrole=view \ + --group=system:serviceaccounts:my-namespace \ + --namespace=my-namespace + ``` + +4. 对集群范围内的所有服务账户授予一个受限角色(不鼓励) + + 如果你不想管理每一个命名空间的权限,你可以向所有的服务账号授予集群范围的角色。 + + 例如,为集群范围的所有服务账号授予跨所有命名空间的只读权限: + + ```shell + kubectl create clusterrolebinding serviceaccounts-view \ + --clusterrole=view \ + --group=system:serviceaccounts + ``` + +5. 授予超级用户访问权限给集群范围内的所有服务帐户(强烈不鼓励) + + 如果你不关心如何区分权限,你可以将超级用户访问权限授予所有服务账号。 + + {{< warning >}} + 这将允许所有能够读取 Secrets 和创建 Pods 的用户访问超级用户的私密信息。 + {{< /warning >}} + + ```shell + kubectl create clusterrolebinding serviceaccounts-cluster-admin \ + --clusterrole=cluster-admin \ + --group=system:serviceaccounts + ``` + + +# 从版本1.5升级 + +在Kubernetes 1.6版本之前,许多部署可以使用非常宽松的 ABAC 策略, +包括授予所有服务帐户全权访问 API 的能力。 + +默认的 RBAC 策略被授予控制面组件、节点和控制器。 +`kube-system` 命名空间外的服务账号将没有权限 +(除了授予所有认证用户的发现权限之外) + +这样做虽然安全得多,但可能会干扰期望自动获得 API 权限的现有工作负载。 +这里有两种方法来完成这种转变: + + +### 平行鉴权 + +同时运行 RBAC 和 ABAC 鉴权模式, 并指定包含 +[现有的 ABAC 策略](/docs/reference/access-authn-authz/abac/#policy-file-format) 的策略文件: + +``` +--authorization-mode=RBAC,ABAC --authorization-policy-file=mypolicy.json +``` + +RBAC 鉴权器将首先尝试对请求进行鉴权。如果它拒绝 API 请求, +则 ABAC 鉴权器运行。这意味着被 RBAC 或 ABAC 策略所允许的任何请求 +都是被允许的请求。 + +如果 API 服务器启动时,RBAC 组件的日志级别为 5 或更高(`--vmodule=rbac*=5` or `--v=5`), +你可以在 API 服务器的日志中看到 RBAC 的细节 (前缀 `RBAC DENY:`) +您可以使用这些信息来确定需要将哪些角色授予哪些用户、组或服务帐户。 +一旦你将 [角色授予服务账号](#服务账号权限) ,工作负载运行时在服务器日志中 +没有出现 RBAC 拒绝消息,就可以删除 ABAC 鉴权器。 + + + +## 宽松的 RBAC 权限 + +可以使用 RBAC 角色绑定在多个场合使用宽松的策略。 + +{{< warning >}} +下面的策略允许 **所有** 服务帐户充当集群管理员。 +容器中运行的所有应用程序都会自动收到服务帐户的凭据, +可以对 API 执行任何操作,包括查看 Secrets 和修改权限。 +这个策略是不被推荐的。 + +``` +kubectl create clusterrolebinding permissive-binding \ + --clusterrole=cluster-admin \ + --user=admin \ + --user=kubelet \ + --group=system:serviceaccounts +``` +{{< /warning >}} + +{{% /capture %}} diff --git a/content/zh/docs/reference/command-line-tools-reference/feature-gates.md b/content/zh/docs/reference/command-line-tools-reference/feature-gates.md index dae2db093b..945c5dac7e 100644 --- a/content/zh/docs/reference/command-line-tools-reference/feature-gates.md +++ b/content/zh/docs/reference/command-line-tools-reference/feature-gates.md @@ -1,46 +1,57 @@ +--- +weight: 10 +title: 特性门控 +content_template: templates/concept +--- + ---- -title: 功能开关 -weight: 10 -title: 功能开关 -content_template: templates/concept ---- {{% capture overview %}} -本页详述了管理员可以在不同的 Kubernetes 组件上指定的各种功能开关。 + +本页详述了管理员可以在不同的 Kubernetes 组件上指定的各种特性门控。 + +关于特性各个阶段的说明,请参见[特性阶段](#feature-stages)。 + {{% /capture %}} {{% capture body %}} + + ## 概述 -功能开关是一组描述 alpha 或实验功能的键值对。 + +特性门控是描述 Kubernetes 特性的一组键值对。您可以在 Kubernetes 的每一个组件中使用 `--feature-gates` flag 来启用或禁用这些特性。 + -管理员可以在每个组件上使用 `--feature-gates` 命令行参数来打开或关闭功能。每个组件都支持该组件唯一的一组功能开关。 -使用 `-h` 参数来查看所有组件的完整功能开关。 -要为诸如 kubelet 之类的组件设置功能开关,请使用分配给功能键值对列表的 `--feature-gates` 参数: + +每个 Kubernetes 组件都支持启用或禁用与该组件相关的一组特性门控。 +使用 `-h` 参数来查看所有组件支持的完整特性门控。 +要为诸如 kubelet 之类的组件设置特性门控,请使用 `--feature-gates` 参数,并向其传递一组特性: ```shell --feature-gates="...,DynamicKubeletConfig=true" @@ -50,7 +61,8 @@ To set feature gates for a component, such as kubelet, use the `--feature-gates` The following tables are a summary of the feature gates that you can set on different Kubernetes components. --> -下表总结了可以在不同的 Kubernetes 组件上设置的功能开关。 + +下表总结了在不同的 Kubernetes 组件上可以设置的特性门控。 -- 引入功能或更改其发布阶段后,"Since" 列将包含 Kubernetes 版本。 -- "Until" 列(如果不为空)包含最后一个 Kubernetes 版本,您仍可以在其中使用功能开关。 -- 如果某个功能处于 Alpha 或 Beta 状态,则可以在 Alpha 或者 Beta 功能开关表中找到该功能。 -- 如果某个功能稳定(GA)或已弃用,则可以在 GA 或者不推荐使用的功能开关表中找到该功能的所有阶段。 + +- 引入特性或更改其发布阶段后,"Since" 列将包含 Kubernetes 版本。 +- "Until" 列(如果不为空)包含最后一个 Kubernetes 版本,您仍可以在其中使用特性门控。 +- 如果某个特性处于 Alpha 或 Beta 状态,您可以在 [Alpha 和 Beta 特性门控表](#feature-gates-for-alpha-or-beta-features)中找到该特性。 +- 如果某个特性处于稳定状态,您可以在[毕业和废弃特性门控表](#feature-gates-for-graduated-or-deprecated-features).中找到该特性的所有阶段。 +- [毕业和废弃特性门控表](#feature-gates-for-graduated-or-deprecated-features) 还列出了废弃的和已被移除的特性。 -### Alpha 或 Beta 功能的功能开关 - -{{< table caption="Alpha 或 Beta 状态中功能的功能开关" >}} +### Alpha 和 Beta 的特性门控 -| 功能 | 默认值 | 状态 | 开始(Since) | 结束(Until) | +{{< table caption="处于 Alpha 或 Beta 状态的特性门控" >}} + +| 特性 | 默认值 | 状态 | 开始(Since) | 结束(Until) | |---------|---------|-------|-------|-------| | `APIListChunking` | `false` | Alpha | 1.8 | 1.8 | | `APIListChunking` | `true` | Beta | 1.9 | | +| `APIPriorityAndFairness` | `false` | Alpha | 1.17 | | | `APIResponseCompression` | `false` | Alpha | 1.7 | | | `AppArmor` | `true` | Beta | 1.4 | | -| `AttachVolumeLimit` | `true` | Alpha | 1.11 | 1.11 | -| `AttachVolumeLimit` | `true` | Beta | 1.12 | | | `BalanceAttachedNodeVolumes` | `false` | Alpha | 1.11 | | | `BlockVolume` | `false` | Alpha | 1.9 | 1.12 | | `BlockVolume` | `true` | Beta | 1.13 | - | @@ -102,14 +118,20 @@ Alpha 或 Beta 状态中功能的功能开关 | `CSIDriverRegistry` | `true` | Beta | 1.14 | | | `CSIInlineVolume` | `false` | Alpha | 1.15 | 1.15 | | `CSIInlineVolume` | `true` | Beta | 1.16 | - | -| `CSIMigration` | `false` | Alpha | 1.14 | | +| `CSIMigration` | `false` | Alpha | 1.14 | 1.16 | +| `CSIMigration` | `true` | Beta | 1.17 | | | `CSIMigrationAWS` | `false` | Alpha | 1.14 | | +| `CSIMigrationAWS` | `false` | Beta | 1.17 | | +| `CSIMigrationAWSComplete` | `false` | Alpha | 1.17 | | | `CSIMigrationAzureDisk` | `false` | Alpha | 1.15 | | +| `CSIMigrationAzureDiskComplete` | `false` | Alpha | 1.17 | | | `CSIMigrationAzureFile` | `false` | Alpha | 1.15 | | -| `CSIMigrationGCE` | `false` | Alpha | 1.14 | | +| `CSIMigrationAzureFileComplete` | `false` | Alpha | 1.17 | | +| `CSIMigrationGCE` | `false` | Alpha | 1.14 | 1.16 | +| `CSIMigrationGCE` | `false` | Beta | 1.17 | | +| `CSIMigrationGCEComplete` | `false` | Alpha | 1.17 | | | `CSIMigrationOpenStack` | `false` | Alpha | 1.14 | | -| `CSINodeInfo` | `false` | Alpha | 1.12 | 1.13 | -| `CSINodeInfo` | `true` | Beta | 1.14 | | +| `CSIMigrationOpenStackComplete` | `false` | Alpha | 1.17 | | | `CustomCPUCFSQuotaPeriod` | `false` | Alpha | 1.12 | | | `CustomResourceDefaulting` | `false` | Alpha| 1.15 | 1.15 | | `CustomResourceDefaulting` | `true` | Beta | 1.16 | | @@ -120,7 +142,8 @@ Alpha 或 Beta 状态中功能的功能开关 | `DynamicAuditing` | `false` | Alpha | 1.13 | | | `DynamicKubeletConfig` | `false` | Alpha | 1.4 | 1.10 | | `DynamicKubeletConfig` | `true` | Beta | 1.11 | | -| `EndpointSlice` | `false` | Alpha | 1.16 | | +| `EndpointSlice` | `false` | Alpha | 1.16 | 1.16 | +| `EndpointSlice` | `false` | Beta | 1.17 | | | `EphemeralContainers` | `false` | Alpha | 1.16 | | | `ExpandCSIVolumes` | `false` | Alpha | 1.14 | 1.15 | | `ExpandCSIVolumes` | `true` | Beta | 1.16 | | @@ -140,31 +163,21 @@ Alpha 或 Beta 状态中功能的功能开关 | `LocalStorageCapacityIsolationFSQuotaMonitoring` | `false` | Alpha | 1.15 | | | `MountContainers` | `false` | Alpha | 1.9 | | | `NodeDisruptionExclusion` | `false` | Alpha | 1.16 | | -| `NodeLease` | `false` | Alpha | 1.12 | 1.13 | -| `NodeLease` | `true` | Beta | 1.14 | | | `NonPreemptingPriority` | `false` | Alpha | 1.15 | | | `PodOverhead` | `false` | Alpha | 1.16 | - | -| `PodShareProcessNamespace` | `false` | Alpha | 1.10 | 1.11 | -| `PodShareProcessNamespace` | `true` | Beta | 1.12 | | | `ProcMountType` | `false` | Alpha | 1.12 | | | `QOSReserved` | `false` | Alpha | 1.11 | | | `RemainingItemCount` | `false` | Alpha | 1.15 | | -| `RequestManagement` | `false` | Alpha | 1.15 | | | `ResourceLimitsPriorityFunction` | `false` | Alpha | 1.9 | | -| `ResourceQuotaScopeSelectors` | `false` | Alpha | 1.11 | 1.11 | -| `ResourceQuotaScopeSelectors` | `true` | Beta | 1.12 | | | `RotateKubeletClientCertificate` | `true` | Beta | 1.8 | | | `RotateKubeletServerCertificate` | `false` | Alpha | 1.7 | 1.11 | | `RotateKubeletServerCertificate` | `true` | Beta | 1.12 | | | `RunAsGroup` | `true` | Beta | 1.14 | | | `RuntimeClass` | `false` | Alpha | 1.12 | 1.13 | | `RuntimeClass` | `true` | Beta | 1.14 | | -| `ScheduleDaemonSetPods` | `false` | Alpha | 1.11 | 1.11 | -| `ScheduleDaemonSetPods` | `true` | Beta | 1.12 | | | `SCTPSupport` | `false` | Alpha | 1.12 | | | `ServerSideApply` | `false` | Alpha | 1.14 | 1.15 | | `ServerSideApply` | `true` | Beta | 1.16 | | -| `ServiceLoadBalancerFinalizer` | `false` | Alpha | 1.15 | | | `ServiceNodeExclusion` | `false` | Alpha | 1.8 | | | `StartupProbe` | `false` | Alpha | 1.16 | | | `StorageVersionHash` | `false` | Alpha | 1.14 | 1.14 | @@ -178,43 +191,40 @@ Alpha 或 Beta 状态中功能的功能开关 | `Sysctls` | `true` | Beta | 1.11 | | | `TaintBasedEvictions` | `false` | Alpha | 1.6 | 1.12 | | `TaintBasedEvictions` | `true` | Beta | 1.13 | | -| `TaintNodesByCondition` | `false` | Alpha | 1.8 | 1.11 | -| `TaintNodesByCondition` | `true` | Beta | 1.12 | | | `TokenRequest` | `false` | Alpha | 1.10 | 1.11 | | `TokenRequest` | `true` | Beta | 1.12 | | | `TokenRequestProjection` | `false` | Alpha | 1.11 | 1.11 | | `TokenRequestProjection` | `true` | Beta | 1.12 | | | `TTLAfterFinished` | `false` | Alpha | 1.12 | | | `TopologyManager` | `false` | Alpha | 1.16 | | -| `ValidateProxyRedirects` | `false` | Alpha | 1.10 | 1.13 | +| `ValidateProxyRedirects` | `false` | Alpha | 1.12 | 1.13 | | `ValidateProxyRedirects` | `true` | Beta | 1.14 | | | `VolumePVCDataSource` | `false` | Alpha | 1.15 | 1.15 | | `VolumePVCDataSource` | `true` | Beta | 1.16 | | -| `VolumeSubpathEnvExpansion` | `false` | Alpha | 1.14 | 1.14 | -| `VolumeSubpathEnvExpansion` | `true` | Beta | 1.15 | | -| `VolumeSnapshotDataSource` | `false` | Alpha | 1.12 | - | -| `WatchBookmark` | `false` | Alpha | 1.15 | 1.15 | -| `WatchBookmark` | `true` | Beta | 1.16 | | +| `VolumeSnapshotDataSource` | `false` | Alpha | 1.12 | 1.16 | +| `VolumeSnapshotDataSource` | `true` | Beta | 1.17 | - | | `WindowsGMSA` | `false` | Alpha | 1.14 | | | `WindowsGMSA` | `true` | Beta | 1.16 | | | `WinDSR` | `false` | Alpha | 1.14 | | | `WinOverlay` | `false` | Alpha | 1.14 | | + {{< /table >}} -### 已完成或不推荐使用的功能的功能开关 - -{{< table caption="已完成或不推荐使用的功能的功能开关" >}} +### 已毕业和不推荐使用的特性门控 -| 功能 | 默认值 | 状态 | 开始(Since) | 结束(Until) | +{{< table caption="已毕业或不推荐使用的特性门控" >}} + +| 特性 | 默认值 | 状态 | 开始(Since) | 结束(Until) | |---------|---------|-------|-------|-------| | `Accelerators` | `false` | Alpha | 1.6 | 1.10 | | `Accelerators` | - | Deprecated | 1.11 | - | @@ -225,6 +235,12 @@ Feature Gates for Graduated or Deprecated Features | `AffinityInAnnotations` | - | Deprecated | 1.8 | - | | `AllowExtTrafficLocalEndpoints` | `false` | Beta | 1.4 | 1.6 | | `AllowExtTrafficLocalEndpoints` | `true` | GA | 1.7 | - | +| `CSINodeInfo` | `false` | Alpha | 1.12 | 1.13 | +| `CSINodeInfo` | `true` | Beta | 1.14 | 1.16 | +| `CSINodeInfo` | `true` | GA | 1.17 | | +| `AttachVolumeLimit` | `false` | Alpha | 1.11 | 1.11 | +| `AttachVolumeLimit` | `true` | Beta | 1.12 | 1.16 | +| `AttachVolumeLimit` | `true` | GA | 1.17 | - | | `CSIPersistentVolume` | `false` | Alpha | 1.9 | 1.9 | | `CSIPersistentVolume` | `true` | Beta | 1.10 | 1.12 | | `CSIPersistentVolume` | `true` | GA | 1.13 | - | @@ -266,6 +282,9 @@ Feature Gates for Graduated or Deprecated Features | `MountPropagation` | `false` | Alpha | 1.8 | 1.9 | | `MountPropagation` | `true` | Beta | 1.10 | 1.11 | | `MountPropagation` | `true` | GA | 1.12 | - | +| `NodeLease` | `false` | Alpha | 1.12 | 1.13 | +| `NodeLease` | `true` | Beta | 1.14 | 1.16 | +| `NodeLease` | `true` | GA | 1.17 | - | | `PersistentLocalVolumes` | `false` | Alpha | 1.7 | 1.9 | | `PersistentLocalVolumes` | `true` | Beta | 1.10 | 1.13 | | `PersistentLocalVolumes` | `true` | GA | 1.14 | - | @@ -275,39 +294,61 @@ Feature Gates for Graduated or Deprecated Features | `PodReadinessGates` | `false` | Alpha | 1.11 | 1.11 | | `PodReadinessGates` | `true` | Beta | 1.12 | 1.13 | | `PodReadinessGates` | `true` | GA | 1.14 | - | +| `PodShareProcessNamespace` | `false` | Alpha | 1.10 | 1.11 | +| `PodShareProcessNamespace` | `true` | Beta | 1.12 | 1.16 | +| `PodShareProcessNamespace` | `true` | GA | 1.17 | - | | `PVCProtection` | `false` | Alpha | 1.9 | 1.9 | | `PVCProtection` | - | Deprecated | 1.10 | - | +| `RequestManagement` | `false` | Alpha | 1.15 | 1.16 | +| `ResourceQuotaScopeSelectors` | `false` | Alpha | 1.11 | 1.11 | +| `ResourceQuotaScopeSelectors` | `true` | Beta | 1.12 | 1.16 | +| `ResourceQuotaScopeSelectors` | `true` | GA | 1.17 | - | +| `ScheduleDaemonSetPods` | `false` | Alpha | 1.11 | 1.11 | +| `ScheduleDaemonSetPods` | `true` | Beta | 1.12 | 1.16 | +| `ScheduleDaemonSetPods` | `true` | GA | 1.17 | - | +| `ServiceLoadBalancerFinalizer` | `false` | Alpha | 1.15 | 1.15 | +| `ServiceLoadBalancerFinalizer` | `true` | Beta | 1.16 | 1.16 | +| `ServiceLoadBalancerFinalizer` | `true` | GA | 1.17 | - | | `StorageObjectInUseProtection` | `true` | Beta | 1.10 | 1.10 | | `StorageObjectInUseProtection` | `true` | GA | 1.11 | - | | `SupportIPVSProxyMode` | `false` | Alpha | 1.8 | 1.8 | | `SupportIPVSProxyMode` | `false` | Beta | 1.9 | 1.9 | | `SupportIPVSProxyMode` | `true` | Beta | 1.10 | 1.10 | | `SupportIPVSProxyMode` | `true` | GA | 1.11 | - | +| `TaintNodesByCondition` | `false` | Alpha | 1.8 | 1.11 | +| `TaintNodesByCondition` | `true` | Beta | 1.12 | 1.16 | +| `TaintNodesByCondition` | `true` | GA | 1.17 | - | | `VolumeScheduling` | `false` | Alpha | 1.9 | 1.9 | | `VolumeScheduling` | `true` | Beta | 1.10 | 1.12 | | `VolumeScheduling` | `true` | GA | 1.13 | - | | `VolumeSubpath` | `true` | GA | 1.13 | - | +| `VolumeSubpathEnvExpansion` | `false` | Alpha | 1.14 | 1.14 | +| `VolumeSubpathEnvExpansion` | `true` | Beta | 1.15 | 1.16 | +| `VolumeSubpathEnvExpansion` | `true` | GA | 1.17 | - | +| `WatchBookmark` | `false` | Alpha | 1.15 | 1.15 | +| `WatchBookmark` | `true` | Beta | 1.16 | 1.16 | +| `WatchBookmark` | `true` | GA | 1.17 | - | + {{< /table >}} -## 使用功能 +## Using a feature - -### 功能阶段 + +## 使用特性 + +### 特性阶段 -处于 *Alpha*、*Beta*、*GA* 阶段的功能 - -*Alpha* 功能代表: + +处于 *Alpha* 、*Beta* 、 *GA* 阶段的特性。 + +*Alpha* 特性代表: + * 默认禁用。 -* 可能有错误,启用此功能可能会导致错误。 -* 随时可能删除对此功能的支持,恕不另行通知。 +* 可能有错误,启用此特性可能会导致错误。 +* 随时可能删除对此特性的支持,恕不另行通知。 * 在以后的软件版本中,API 可能会以不兼容的方式更改,恕不另行通知。 -* 建议将其仅用于短期测试集群中,因为开启功能会增加错误的风险,并且缺乏长期支持。 +* 建议将其仅用于短期测试中,因为开启特性会增加错误的风险,并且缺乏长期支持。 -*Beta* 功能代表: + +*Beta* 特性代表: + * 默认禁用。 -* 该功能已经经过良好测试。启用该功能是安全的。 -* 尽管详细信息可能会更改,但不会放弃对整体功能的支持。 -* 对象的架构或语义可能会在随后的 Beta 或稳定版本中以不兼容的方式更改。当发生这种情况时,我们将提供迁移到下一版本的说明。此功能可能需要删除、编辑和重新创建 API 对象。编辑过程可能需要慎重操作,因为这可能会导致依赖该功能的应用程序停机。 -* 推荐仅用于非关键业务用途,因为在后续版本中可能会发生不兼容的更改。如果您具有多个可以独立升级的集群,则可以放宽此限制。 +* 该特性已经经过良好测试。启用该特性是安全的。 +* 尽管详细信息可能会更改,但不会放弃对整体特性的支持。 +* 对象的架构或语义可能会在随后的 Beta 或稳定版本中以不兼容的方式更改。当发生这种情况时,我们将提供迁移到下一版本的说明。此特性可能需要删除、编辑和重新创建 API 对象。编辑过程可能需要慎重操作,因为这可能会导致依赖该特性的应用程序停机。 +* 推荐仅用于非关键业务用途,因为在后续版本中可能会发生不兼容的更改。如果您具有多个可以独立升级的,则可以放宽此限制。 {{< note >}} -请尝试使用 *Beta* 功能并提供有关它们的反馈! -功能退出 Beta 后,对我们进行更多更改可能不切实际。 +请试用 *Beta* 特性并提供相关反馈! +一旦特性结束 Beta 状态,我们就不太可能再对特性进行大幅修改。 {{< /note >}} -*GA* 功能也称为 *稳定* 功能,*GA* 功能代表着: + +*General Availability* (GA) 特性也称为 *稳定* 特性,*GA* 特性代表着: -* 不再需要相应的功能开关。 -* 对于许多后续版本,功能的稳定版本将出现在发行的软件中。 + +* 此特性会一直启用;你不能禁用它。 +* 不再需要相应的特性门控。 +* 对于许多后续版本,特性的稳定版本将出现在发行的软件中。 -### 功能开关 +## List of feature gates {#feature-gates} - -每个功能开关均设计用于启用或禁用特定功能: + +### 特性门控列表 + +每个特性门控均用于启用或禁用某个特定的特性: + - `Accelerators`:使用 Docker 时启用 Nvidia GPU 支持。 - `AdvancedAuditing`:启用[高级审查功能](/docs/tasks/debug-application-cluster/audit/#advanced-audit)。 -- `AffinityInAnnotations`(*已弃用*):启用 [Pod 亲和力或反亲和力](/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity)。 +- `AffinityInAnnotations`( *已弃用* ):启用 [Pod 亲和力或反亲和力](/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity)。 - `AllowExtTrafficLocalEndpoints`:启用服务用于将外部请求路由到节点本地终端。 - `APIListChunking`:启用 API 客户端以块的形式从 API 服务器检索(“LIST” 或 “GET”)资源。 +- `APIPriorityAndFairness`: Enable managing request concurrency with prioritization and fairness at each server. (Renamed from `RequestManagement`) +- `APIPriorityAndFairness`: 在每个服务器上启用优先级和公平性来管理请求并发。(由 `RequestManagement` 重命名而来) - `APIResponseCompression`:压缩 “LIST” 或 “GET” 请求的 API 响应。 -- `AppArmor`:使用 Docker 时,在 Linux 节点上启用基于 AppArmor 机制的强制访问控制。有关更多详细信息,请参见 [AppArmor 教程](/docs/tutorials/clusters/apparmor/)。 +- `AppArmor`:使用 Docker 时,在 Linux 节点上启用基于 AppArmor 机制的强制访问控制。请参见 [AppArmor 教程](/docs/tutorials/clusters/apparmor/) 获取详细信息。 + + - `AttachVolumeLimit`:启用卷插件用于报告可连接到节点的卷数限制。有关更多详细信息,请参见[动态卷限制](/docs/concepts/storage/storage-limits/#dynamic-volume-limits)。 - `BalanceAttachedNodeVolumes`:包括要在调度时进行平衡资源分配的节点上的卷数。scheduler 在决策时会优先考虑 CPU、内存利用率和卷数更近的节点。 - `BlockVolume`:在 Pod 中启用原始块设备的定义和使用。有关更多详细信息,请参见[原始块卷支持](/docs/concepts/storage/persistent-volumes/#raw-block-volume-support)。 - `BoundServiceAccountTokenVolume`:迁移 ServiceAccount 卷以使用由 ServiceAccountTokenVolumeProjection 组成的预计卷。有关更多详细信息,请参见 [Service Account Token 卷](https://git.k8s.io/community/contributors/design-proposals/storage/svcacct-token-volume-source.md)。 - `CPUManager`:启用容器级别的 CPU 亲和力支持,有关更多详细信息,请参见 [CPU 管理策略](/docs/tasks/administer-cluster/cpu-management-policies/)。 + + - `CRIContainerLogRotation`:为 cri 容器运行时启用容器日志轮换。 - `CSIBlockVolume`:启用外部 CSI 卷驱动程序用于支持块存储。有关更多详细信息,请参见 [`csi` 原始块卷支持](/docs/concepts/storage/volumes/#csi-raw-block-volume-support)。 - `CSIDriverRegistry`:在 csi.storage.k8s.io 中启用与 CSIDriver API 对象有关的所有逻辑。 - `CSIInlineVolume`:为 Pod 启用 CSI 内联卷支持。 - `CSIMigration`:确保填充和转换逻辑能够将卷操作从内嵌插件路由到相应的预安装 CSI 插件。 -- `CSIMigrationAWS`:确保填充和转换逻辑能够将卷操作从 AWS-EBS 内嵌插件路由到 EBS CSI 插件。 -- `CSIMigrationAzureDisk`:确保填充和转换逻辑能够将卷操作从 Azure 磁盘内嵌插件路由到 Azure 磁盘 CSI 插件。 -- `CSIMigrationAzureFile`:确保填充和转换逻辑能够将卷操作从 Azure 文件内嵌插件路由到 Azure 文件 CSI 插件。 +- `CSIMigrationAWS`:确保填充和转换逻辑能够将卷操作从 AWS-EBS 内嵌插件路由到 EBS CSI 插件。如果节点未安装和配置 EBS CSI 插件,则支持回退到内嵌 EBS 插件。这需要启用 CSIMigration 特性标志。 +- `CSIMigrationAWSComplete`:停止在 kubelet 和卷控制器中注册 EBS 内嵌插件,并启用 shims 和转换逻辑将卷操作从AWS-EBS 内嵌插件路由到 EBS CSI 插件。这需要启用 CSIMigration 和 CSIMigrationAWS 特性标志,并在群集中的所有节点上安装和配置 EBS CSI 插件。 +- `CSIMigrationAzureDisk`:确保填充和转换逻辑能够将卷操作从 Azure 磁盘内嵌插件路由到 Azure 磁盘 CSI 插件。如果节点未安装和配置 AzureDisk CSI 插件,支持回退到内建 AzureDisk 插件。这需要启用 CSIMigration 特性标志。 +- `CSIMigrationAzureDiskComplete`:停止在 kubelet 和卷控制器中注册 Azure 磁盘内嵌插件,并启用 shims 和转换逻辑以将卷操作从 Azure 磁盘内嵌插件路由到 AzureDisk CSI 插件。这需要启用 CSIMigration 和 CSIMigrationAzureDisk 特性标志,并在群集中的所有节点上安装和配置 AzureDisk CSI 插件。 +- `CSIMigrationAzureFile`:确保填充和转换逻辑能够将卷操作从 Azure 文件内嵌插件路由到 Azure 文件 CSI 插件。如果节点未安装和配置 AzureFile CSI 插件,支持回退到内嵌 AzureFile 插件。这需要启用 CSIMigration 特性标志。 +- `CSIMigrationAzureFileComplete`:停止在 kubelet 和卷控制器中注册 Azure-File 内嵌插件,并启用 shims 和转换逻辑以将卷操作从 Azure-File 内嵌插件路由到 AzureFile CSI 插件。这需要启用 CSIMigration 和 CSIMigrationAzureFile 特性标志,并在群集中的所有节点上安装和配置 AzureFile CSI 插件。 + -- `CSIMigrationGCE`:确保填充和转换逻辑能够将卷操作从 GCE-PD 内嵌插件路由到 PD CSI 插件 -- `CSIMigrationOpenStack`:确保填充和转换逻辑能够将卷操作从 Cinder 内嵌插件路由到 Cinder CSI 插件。 + +- `CSIMigrationGCE`:使 shims 和转换逻辑能够将卷操作从 GCE-PD 内嵌插件路由到 PD CSI 插件。如果节点未安装和配置 PD CSI 插件,支持回退到内嵌 GCE 插件。这需要启用 CSIMigration 特性标志。 +- `CSIMigrationGCEComplete`:停止在 kubelet 和卷控制器中注册 GCE-PD 内嵌插件,并启用 shims 和转换逻辑以将卷操作从 GCE-PD 内嵌插件路由到 PD CSI 插件。这需要启用 CSIMigration 和 CSIMigrationGCE 特性标志,并在群集中的所有节点上安装和配置 PD CSI 插件。 +- `CSIMigrationOpenStack`:确保填充和转换逻辑能够将卷操作从 Cinder 内嵌插件路由到 Cinder CSI 插件。如果节点未安装和配置 Cinder CSI 插件,支持回退到内嵌 Cinder 插件。这需要启用 CSIMigration 特性标志。 +- `CSIMigrationOpenStackComplete`:停止在 kubelet 和卷控制器中注册 Cinder 内嵌插件,并启用 shims 和转换逻辑将卷操作从 Cinder 内嵌插件路由到 Cinder CSI 插件。这需要启用 CSIMigration 和 CSIMigrationOpenStack 特性标志,并在群集中的所有节点上安装和配置 Cinder CSI 插件。 - `CSINodeInfo`:在 csi.storage.k8s.io 中启用与 CSINodeInfo API 对象有关的所有逻辑。 - `CSIPersistentVolume`:启用发现并挂载通过 [CSI(容器存储接口)](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/storage/container-storage-interface.md)兼容卷插件配置的卷。有关更多详细信息,请参见 [`csi` 卷类型](/docs/concepts/storage/volumes/#csi)。 + + - `CustomCPUCFSQuotaPeriod`:使节点能够更改 CPUCFSQuotaPeriod。 - `CustomPodDNS`:使用其 `dnsConfig` 属性启用 Pod 的自定义 DNS 设置。有关更多详细信息,请参见 [Pod 的 DNS 配置](/docs/concepts/services-networking/dns-pod-service/#pods-dns-config)。 - `CustomResourceDefaulting`:为 OpenAPI v3 验证架构中的默认值启用 CRD 支持。 @@ -470,6 +540,7 @@ Each feature gate is designed for enabling/disabling a specific feature: - `CustomResourceValidation`:对于从 [CustomResourceDefinition](/docs/concepts/api-extension/custom-resources/) 中创建的资源启用基于架构的验证。 - `CustomResourceWebhookConversion`:对于从 [CustomResourceDefinition](/docs/concepts/api-extension/custom-resources/) 中创建的资源启用基于 Webhook 的转换。 对正在运行的 Pod 进行故障排除。 + + - `DevicePlugins`:在节点上启用基于 [device-plugins](/docs/concepts/cluster-administration/device-plugins/) 的资源供应。 - `DryRun`:启用服务器端 [dry run](/docs/reference/using-api/api-concepts/#dry-run) 请求,以便无需提交即可测试验证、合并和差异化。 - `DynamicAuditing`:确保[动态审查](/docs/tasks/debug-application-cluster/audit/#dynamic-backend)。 - `DynamicKubeletConfig`:启用 kubelet 的动态配置。请参阅[重新配置 kubelet](/docs/tasks/administer-cluster/reconfigure-kubelet/)。 -- `DynamicProvisioningScheduling`:扩展默认 scheduler 以了解卷拓扑并处理 PV 配置。此功能已在 v1.12 中完全由 `VolumeScheduling` 功能取代。 -- `DynamicVolumeProvisioning`(*已弃用*):启用持久化卷到 Pod 的[动态预配置](/docs/concepts/storage/dynamic-provisioning/)。 +- `DynamicProvisioningScheduling`:扩展默认 scheduler 以了解卷拓扑并处理 PV 配置。此特性已在 v1.12 中完全被 `VolumeScheduling` 特性取代。 +- `DynamicVolumeProvisioning`( *已弃用* ):启用持久化卷到 Pod 的[动态预配置](/docs/concepts/storage/dynamic-provisioning/)。 + -- `EnableAggregatedDiscoveryTimeout` (*已弃用*):对聚集的发现调用启用五秒钟超时设置。 + +- `EnableAggregatedDiscoveryTimeout` ( *已弃用* ):对聚集的发现调用启用五秒钟超时设置。 - `EnableEquivalenceClassCache`:调度 Pod 时,使 scheduler 缓存节点的等效项。 -- `EphemeralContainers`:启用添加 {{< glossary_tooltip text="临时容器" term_id="ephemeral-container" >}} 到正在运行的 Pod 的功能。 -- `EvenPodsSpread`:使 Pod 能够在拓扑域之间平衡调度。请参阅 [Even Pods Spread](/docs/concepts/configuration/even-pods-spread)。 +- `EphemeralContainers`:启用添加 {{< glossary_tooltip text="临时容器" term_id="ephemeral-container" >}} 到正在运行的 Pod 的特性。 +- `EvenPodsSpread`:使 Pod 能够在拓扑域之间平衡调度。请参阅 [Pod 拓扑扩展约束](/docs/concepts/workloads/pods/pod-topology-spread-constraints/)。 - `ExpandInUsePersistentVolumes`:启用扩展使用中的 PVC。请查阅 [调整使用中的 PersistentVolumeClaim 的大小](/docs/concepts/storage/persistent-volumes/#resizing-an-in-use-persistentvolumeclaim)。 - `ExpandPersistentVolumes`:启用持久卷的扩展。请查阅[扩展永久卷声明](/docs/concepts/storage/persistent-volumes/#expanding-persistent-volumes-claims)。 -- `ExperimentalCriticalPodAnnotation`:启用将特定 Pod 注解为 *critical* 的方式,用于[确保其调度](/docs/tasks/administer-cluster/guaranteed-scheduling-critical-addon-pods/)。从 v1.13 开始,Pod 优先级和抢占功能已弃用此功能。 +- `ExperimentalCriticalPodAnnotation`:启用将特定 Pod 注解为 *critical* 的方式,用于[确保其调度](/docs/tasks/administer-cluster/guaranteed-scheduling-critical-addon-pods/)。从 v1.13 开始,Pod 优先级和抢占功能已弃用此特性。 + -- `ExperimentalHostUserNamespaceDefaultingGate`:启用默认的用户命名空间进行托管。这适用于使用其他主机命名空间、主机安装的容器,或具有特权或使用特定的非命名空间功能(例如MKNODE、SYS_MODULE等)的容器。如果在 Docker 守护程序中启用了用户命名空间重新映射,则启用此选项。 -- `EndpointSlice`:启用端点切片以实现更多可扩展的网络端点。需要启用相应的 API 和控制器,请参阅[启用端点切片](/docs/tasks/administer-cluster/enabling-endpoint-slices/)。 -- `GCERegionalPersistentDisk`:在 GCE 上启用区域 PD 功能。 + +- `ExperimentalHostUserNamespaceDefaultingGate`:启用主机默认的用户命名空间。这适用于使用其他主机命名空间、主机安装的容器,或具有特权或使用特定的非命名空间功能(例如MKNODE、SYS_MODULE等)的容器。如果在 Docker 守护程序中启用了用户命名空间重新映射,则启用此选项。 +- `EndpointSlice`:启用端点切片以实现更多可扩展的网络端点。需要启用相应的 API 和控制器,请参阅[启用端点切片](/docs/tasks/administer-cluster/enabling-endpointslices/)。 +- `GCERegionalPersistentDisk`:在 GCE 上启用区域 PD 特性。 - `HugePages`: 启用分配和使用预分配的 [huge pages](/docs/tasks/manage-hugepages/scheduling-hugepages/)。 + + - `HyperVContainer`:为 Windows 容器启用[Hyper-V 隔离](https://docs.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/hyperv-container)。 - `HPAScaleToZero`:使用自定义指标或外部指标时,可将 `HorizontalPodAutoscaler` 资源的 `minReplicas` 设置为 0。 - `KubeletConfigFile`:启用从使用配置文件指定的文件中加载 kubelet 配置。有关更多详细信息,请参见[通过配置文件设置 kubelet 参数](/docs/tasks/administer-cluster/kubelet-config-file/)。 - `KubeletPluginsWatcher`:启用基于探针的插件监视应用程序,使 kubelet 能够发现插件,例如 [CSI 卷驱动程序](/docs/concepts/storage/volumes/#csi)。 - `KubeletPodResources`:启用 kubelet 的 pod 资源 grpc 端点。有关更多详细信息,请参见[支持设备监控](https://git.k8s.io/community/keps/sig-node/compute-device-assignment.md)。 -- `LegacyNodeRoleBehavior`:禁用此选项后,服务负载均衡器中的旧版操作和节点中断将忽略 `node-role.kubernetes.io/master` 标签,而使用特定于功能的标签。 +- `LegacyNodeRoleBehavior`:禁用此选项后,服务负载均衡中的旧版操作和节点中断将忽略 `node-role.kubernetes.io/master` 标签,而使用特性指定的标签。 + + - `LocalStorageCapacityIsolation`:启用[本地临时存储](/docs/concepts/configuration/manage-compute-resources-container/)的消耗,以及 [emptyDir 卷](/docs/concepts/storage/volumes/#emptydir) 的 `sizeLimit` 属性。 - `LocalStorageCapacityIsolationFSQuotaMonitoring`:如果为[本地临时存储](/docs/concepts/configuration/manage-compute-resources-container/)启用了 `LocalStorageCapacityIsolation`,并且 [emptyDir 卷](/docs/concepts/storage/volumes/#emptydir) 的后备文件系统支持项目配额,并且启用了这些配额,请使用项目配额来监视 [emptyDir 卷](/docs/concepts/storage/volumes/#emptydir)的存储消耗而不是遍历文件系统,以此获得更好的性能和准确性。 - `MountContainers`:在主机上启用将应用程序容器用作卷安装程序。 - `MountPropagation`:启用将一个容器安装的共享卷共享到其他容器或 Pod。有关更多详细信息,请参见 [mount propagation](/docs/concepts/storage/volumes/#mount-propagation)。 - `NodeDisruptionExclusion`:启用节点标签 `node.kubernetes.io/exclude-disruption`,以防止在区域故障期间驱逐节点。 + + - `NodeLease`:启用新的租赁 API 以报告节点心跳,可用作节点运行状况信号。 - `NonPreemptingPriority`:为 PriorityClass 和 Pod 启用 NonPreempting 选项。 - `PersistentLocalVolumes`:在 Pod 中启用 “本地” 卷类型的使用。如果请求 “本地” 卷,则必须指定 Pod 亲和力。 -- `PodOverhead`:启用 [PodOverhead](/docs/concepts/configuration/pod-overhead/) 功能以解决 Pod 开销。 +- `PodOverhead`:启用 [PodOverhead](/docs/concepts/configuration/pod-overhead/) 特性以解决 Pod 开销。 - `PodPriority`:根据[优先级](/docs/concepts/configuration/pod-priority-preemption/)启用 Pod 的调度和抢占。 -- `PodReadinessGates`:启用 `PodReadinessGate` 字段的设置以扩展 Pod 准备状态评估。有关更多详细信息,请参见 [Pod readiness 功能开关](/docs/concepts/workloads/pods/pod-lifecycle/#pod-readiness-gate)。 +- `PodReadinessGates`:启用 `PodReadinessGate` 字段的设置以扩展 Pod 准备状态评估。有关更多详细信息,请参见 [Pod readiness 特性门控](/docs/concepts/workloads/pods/pod-lifecycle/#pod-readiness-gate)。 + + - `PodShareProcessNamespace`:在 Pod 中启用 `shareProcessNamespace` 的设置,以便在 Pod 中运行的容器之间共享单个进程命名空间。更多详细信息,请参见[在 Pod 中的容器之间共享进程命名空间](/docs/tasks/configure-pod-container/share-process-namespace/)。 - `ProcMountType`:启用对容器的 ProcMountType 的控制。 -- `PVCProtection`:启用防止任何 Pod 仍使用 PersistentVolumeClaim(PVC) 删除的功能。可以在[此处](/docs/tasks/administer-cluster/storage-object-in-use-protection/)中找到更多详细信息。 +- `PVCProtection`:启用防止任何 Pod 仍使用 PersistentVolumeClaim(PVC) 删除的特性。可以在[此处](/docs/tasks/administer-cluster/storage-object-in-use-protection/)中找到更多详细信息。 - `QOSReserved`:允许在 QoS 级别进行资源预留,以防止处于较低 QoS 级别的 Pod 突发进入处于较高 QoS 级别的请求资源(仅适用于内存)。 -- `ResourceLimitsPriorityFunction`:启用 scheduler 优先级功能,该功能将最低可能得 1 分配给至少满足输入 Pod 的 cpu 和内存限制之一的节点,目的是打破得分相同的节点之间的联系。 +- `ResourceLimitsPriorityFunction`:启用 scheduler 优先级特性,该特性将最低可能得 1 分配给至少满足输入 Pod 的 cpu 和内存限制之一的节点,目的是打破得分相同的节点之间的联系。 + + - `RequestManagement`:在每个服务器上启用具有优先级和公平性的管理请求并发性。 - `ResourceQuotaScopeSelectors`:启用资源配额范围选择器。 - `RotateKubeletClientCertificate`:在 kubelet 上启用客户端 TLS 证书的轮换。有关更多详细信息,请参见 [kubelet 配置](/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/#kubelet-configuration)。 - `RotateKubeletServerCertificate`:在 kubelet 上启用服务器 TLS 证书的轮换。有关更多详细信息,请参见 [kubelet 配置](/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/#kubelet-configuration)。 - `RunAsGroup`:启用对容器初始化过程中设置的主要组 ID 的控制。 -- `RuntimeClass`:启用[RuntimeClass](/docs/concepts/containers/runtime-class/) 功能用于选择容器运行时配置。 +- `RuntimeClass`:启用 [RuntimeClass](/docs/concepts/containers/runtime-class/) 特性用于选择容器运行时配置。 - `ScheduleDaemonSetPods`:启用 DaemonSet Pods 由默认调度程序而不是 DaemonSet 控制器进行调度。 + + - `SCTPSupport`:在 “服务”、“端点”、“NetworkPolicy” 和 “Pod” 定义中,将 SCTP 用作 “协议” 值。 - `ServerSideApply`:在 API 服务器上启用[服务器端应用(SSA)](/docs/reference/using-api/api-concepts/#server-side-apply) 路径。 -- `ServiceLoadBalancerFinalizer`:为服务负载均衡器启用终结器保护。 -- `ServiceNodeExclusion`:启用从云提供商创建的负载均衡器中排除节点。如果节点标记有 `alpha.service-controller.kubernetes.io/exclude-balancer` 键(启用 `LegacyNodeRoleBehavior` 时)或 `node.kubernetes.io/exclude-from-external-load-balancers`,则可以排除节点。 +- `ServiceLoadBalancerFinalizer`:为服务负载均衡启用终结器保护。 +- `ServiceNodeExclusion`:启用从云提供商创建的负载均衡中排除节点。如果节点标记有 `alpha.service-controller.kubernetes.io/exclude-balancer` 键或 `node.kubernetes.io/exclude-from-external-load-balancers`,则可以排除节点。 - `StartupProbe`:在 kubelet 中启用 [startup](/docs/concepts/workloads/pods/pod-lifecycle/#when-should-you-use-a-startup-probe) 探针。 - `StorageObjectInUseProtection`:如果仍在使用 PersistentVolume 或 PersistentVolumeClaim 对象,则将其推迟。 + + - `StorageVersionHash`:允许 apiserver 在发现中公开存储版本的哈希值。 - `StreamingProxyRedirects`:指示 API 服务器拦截(并遵循)从后端(kubelet)进行重定向以处理流请求。流请求的例子包括 `exec`、`attach` 和 `port-forward` 请求。 -- `SupportIPVSProxyMode`:启用使用 IPVS 提供集群内服务负载平衡。有关更多详细信息,请参见[服务代理](/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies)。 +- `SupportIPVSProxyMode`:启用使用 IPVS 提供内服务负载平衡。有关更多详细信息,请参见[服务代理](/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies)。 - `SupportPodPidsLimit`:启用支持限制 Pod 中的进程 PID。 - `Sysctls`:启用对可以为每个 Pod 设置的命名空间内核参数(sysctls)的支持。有关更多详细信息,请参见 [sysctls](/docs/tasks/administer-cluster/sysctl-cluster/)。 + -- `TaintBasedEvictions`:根据节点上的污点和 Pod 上的容忍度启用从节点驱逐 Pod 的功能。有关更多详细信息,请参见[污点和容忍度](/docs/concepts/configuration/taint-and-toleration/)。 + +- `TaintBasedEvictions`:根据节点上的污点和 Pod 上的容忍度启用从节点驱逐 Pod 的特性。有关更多详细信息,请参见[污点和容忍度](/docs/concepts/configuration/taint-and-toleration/)。 - `TaintNodesByCondition`:根据[节点条件](/docs/concepts/configuration/taint-and-toleration/)启用自动在节点标记污点。 - `TokenRequest`:在服务帐户资源上启用 `TokenRequest` 端点。 -- `TokenRequestProjection`:启用通过 [`projected` 卷](/docs/concepts/storage/volumes/#projected) 将服务帐户令牌注入到 Pod 中的功能。 +- `TokenRequestProjection`:启用通过 [`projected` 卷](/docs/concepts/storage/volumes/#projected) 将服务帐户令牌注入到 Pod 中的特性。 +- `TopologyManager`:启用一种机制来协调 Kubernetes 不同组件的细粒度硬件资源分配。详见 [控制节点上的拓扑管理策略](/docs/tasks/administer-cluster/topology-manager/)。 - `TTLAfterFinished`:完成执行后,允许 [TTL 控制器](/docs/concepts/workloads/controllers/ttlafterfinished/)清理资源。 + + - `VolumePVCDataSource`:启用对将现有 PVC 指定数据源的支持。 -- `VolumeScheduling`:启用卷拓扑感知调度,并使 PersistentVolumeClaim(PVC)绑定调度决策;当与 PersistentLocalVolumes 功能开关一起使用时,还可以使用 `PersistentLocalVolumes` 卷类型。 +- `VolumeScheduling`:启用卷拓扑感知调度,并使 PersistentVolumeClaim(PVC)绑定调度决策;当与 PersistentLocalVolumes 特性门控一起使用时,还可以使用 `PersistentLocalVolumes` 卷类型。 - `VolumeSnapshotDataSource`:启用卷快照数据源支持。 + + - `VolumeSubpathEnvExpansion`:启用 `subPathExpr` 字段用于将环境变量扩展为 `subPath`。 - `WatchBookmark`:启用对监测 bookmark 事件的支持。 - `WindowsGMSA`:允许将 GMSA 凭据规范从 Pod 传递到容器运行时。 -- `WinDSR`:允许 kube-proxy 为 Windows 创建 DSR 负载均衡器。 +- `WinDSR`:允许 kube-proxy 为 Windows 创建 DSR 负载均衡。 - `WinOverlay`:允许 kube-proxy 在 Windows 的 overlay 模式下运行。 {{% /capture %}} +{{% capture whatsnext %}} + + + +* Kubernetes 的 [弃用策略](/docs/reference/using-api/deprecation-policy/) 介绍了项目已移除的特性部件和组件的方法。 + +{{% /capture %}} diff --git a/content/zh/docs/reference/glossary/api-group.md b/content/zh/docs/reference/glossary/api-group.md new file mode 100644 index 0000000000..4687391f62 --- /dev/null +++ b/content/zh/docs/reference/glossary/api-group.md @@ -0,0 +1,45 @@ +--- +title: API Group +id: api-group +date: 2019-09-02 +full_link: /docs/concepts/overview/kubernetes-api/#api-groups +short_description: > + Kubernetes API 中的一组相关路径 + +aka: +tags: +- fundamental +- architecture +--- + + + +Kubernetes API 中的一组相关路径。 + + + + +通过更改 API server 的配置,可以启用或禁用每个 API Group。你还可以禁用或启用指向特定资源的路径。API group 使扩展 Kubernetes API 更加的容易。API group 在 REST 路径和序列化对象的 `apiVersion` 字段中指定。 + + +* 阅读 [API Group](/docs/concepts/overview/kubernetes-api/#api-groups) 了解更多信息。 diff --git a/content/zh/docs/reference/glossary/proxy.md b/content/zh/docs/reference/glossary/proxy.md new file mode 100644 index 0000000000..e8ab669393 --- /dev/null +++ b/content/zh/docs/reference/glossary/proxy.md @@ -0,0 +1,55 @@ +--- +title: 代理 +id: proxy +date: 2019-09-10 +short_description: > + 充当客户端和服务器之间的中介的应用程序 + +aka: +tags: +- networking +--- + + +在计算机领域,代理指的是充当远程服务中介的服务器。 + + + + + +客户端与代理进行交互;代理将客户端的数据复制到实际服务器;实际服务器回复代理;代理将实际服务器的回复发送给客户端。 + + +[kube-proxy](/docs/reference/command-line-tools-reference/kube-proxy/) 是集群中每个节点上运行的网络代理,实现了部分 Kubernetes {{< glossary_tooltip term_id="service">}} 概念。 + + +你可以将 kube-proxy 作为普通的用户态代理服务运行。 +如果你的操作系统支持,则可以在混合模式下运行 kube-proxy;该模式使用较少的系统资源即可达到相同的总体效果。 + diff --git a/content/zh/docs/reference/kubectl/overview.md b/content/zh/docs/reference/kubectl/overview.md index e8a1e92b49..2aaf1308e4 100644 --- a/content/zh/docs/reference/kubectl/overview.md +++ b/content/zh/docs/reference/kubectl/overview.md @@ -174,31 +174,31 @@ Operation | Syntax | Description 操作 | 语法 | 描述 -------------------- | -------------------- | -------------------- -`annotate` | `kubectl annotate (-f FILENAME \| TYPE NAME \| TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]` | 添加或更新一个或多个资源的注解。 +`annotate` | kubectl annotate (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags] | 添加或更新一个或多个资源的注解。 `api-versions` | `kubectl api-versions [flags]` | 列出可用的 API 版本。 `apply` | `kubectl apply -f FILENAME [flags]`| 从文件或 stdin 对资源应用配置更改。 `attach` | `kubectl attach POD -c CONTAINER [-i] [-t] [flags]` | 附加到正在运行的容器,查看输出流或与容器(stdin)交互。 -`autoscale` | `kubectl autoscale (-f FILENAME \| TYPE NAME \| TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]` | 自动伸缩由副本控制器管理的一组 pod。 +`autoscale` | kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags] | 自动伸缩由副本控制器管理的一组 pod。 `cluster-info` | `kubectl cluster-info [flags]` | 显示有关集群中主服务器和服务的端口信息。 `config` | `kubectl config SUBCOMMAND [flags]` | 修改 kubeconfig 文件。有关详细信息,请参阅各个子命令。 `create` | `kubectl create -f FILENAME [flags]` | 从文件或 stdin 创建一个或多个资源。 -`delete` | `kubectl delete (-f FILENAME \| TYPE [NAME \| /NAME \| -l label \| --all]) [flags]` | 从文件、标准输入或指定标签选择器、名称、资源选择器或资源中删除资源。 -`describe` | `kubectl describe (-f FILENAME \| TYPE [NAME_PREFIX \| /NAME \| -l label]) [flags]` | 显示一个或多个资源的详细状态。 +`delete` | kubectl delete (-f FILENAME | TYPE [NAME | /NAME | -l label | --all]) [flags] | 从文件、标准输入或指定标签选择器、名称、资源选择器或资源中删除资源。 +`describe` | kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags] | 显示一个或多个资源的详细状态。 `diff` | `kubectl diff -f FILENAME [flags]`| 将 live 配置和文件或标准输入做对比 (**BETA**) -`edit` | `kubectl edit (-f FILENAME \| TYPE NAME \| TYPE/NAME) [flags]` | 使用默认编辑器编辑和更新服务器上一个或多个资源的定义。 +`edit` | kubectl edit (-f FILENAME | TYPE NAME | TYPE/NAME) [flags] | 使用默认编辑器编辑和更新服务器上一个或多个资源的定义。 `exec` | `kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]` | 对 pod 中的容器执行命令。 `explain` | `kubectl explain [--recursive=false] [flags]` | 获取多种资源的文档。例如 pod, node, service 等。 -`expose` | `kubectl expose (-f FILENAME \| TYPE NAME \| TYPE/NAME) [--port=port] [--protocol=TCP\|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags]` | 将副本控制器、服务或 pod 作为新的 Kubernetes 服务暴露。 -`get` | `kubectl get (-f FILENAME \| TYPE [NAME \| /NAME \| -l label]) [--watch] [--sort-by=FIELD] [[-o \| --output]=OUTPUT_FORMAT] [flags]` | 列出一个或多个资源。 -`label` | `kubectl label (-f FILENAME \| TYPE NAME \| TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]` | 添加或更新一个或多个资源的标签。 +`expose` | kubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags] | 将副本控制器、服务或 pod 作为新的 Kubernetes 服务暴露。 +`get` | kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [--watch] [--sort-by=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags] | 列出一个或多个资源。 +`label` | kubectl label (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags] | 添加或更新一个或多个资源的标签。 `logs` | `kubectl logs POD [-c CONTAINER] [--follow] [flags]` | 在 pod 中打印容器的日志。 -`patch` | `kubectl patch (-f FILENAME \| TYPE NAME \| TYPE/NAME) --patch PATCH [flags]` | 使用策略合并 patch 程序更新资源的一个或多个字段。 +`patch` | kubectl patch (-f FILENAME | TYPE NAME | TYPE/NAME) --patch PATCH [flags] | 使用策略合并 patch 程序更新资源的一个或多个字段。 `port-forward` | `kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]` | 将一个或多个本地端口转发到一个 pod。 `proxy` | `kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]` | 运行 Kubernetes API 服务器的代理。 `replace` | `kubectl replace -f FILENAME` | 从文件或标准输入中替换资源。 -`rolling-update` | `kubectl rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE \| -f NEW_CONTROLLER_SPEC) [flags]` | 通过逐步替换指定的副本控制器及其 pod 来执行滚动更新。 +`rolling-update` | kubectl rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC) [flags] | 通过逐步替换指定的副本控制器及其 pod 来执行滚动更新。 `run` | `kubectl run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [flags]` | 在集群上运行指定的镜像。 -`scale` | `kubectl scale (-f FILENAME \| TYPE NAME \| TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags]` | 更新指定副本控制器的大小。 +`scale` | kubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags] | 更新指定副本控制器的大小。 `stop` | `kubectl stop` | 不推荐:相反,请参阅 kubectl delete。 `version` | `kubectl version [--client] [flags]` | 显示运行在客户端和服务器上的 Kubernetes 版本。 diff --git a/content/zh/docs/reference/setup-tools/kubeadm/kubeadm-join.md b/content/zh/docs/reference/setup-tools/kubeadm/kubeadm-join.md index 00ba1ff7e1..6e6fd76fa4 100644 --- a/content/zh/docs/reference/setup-tools/kubeadm/kubeadm-join.md +++ b/content/zh/docs/reference/setup-tools/kubeadm/kubeadm-join.md @@ -101,7 +101,7 @@ The CA key hash has the format `sha256:`. By default, the hash --> CA 键哈希格式为 `sha256:`。 -默认情况下,在 `kubeadm init` 最后打印的 `kubeadm join` 命令或者 `kubeadm token create--print-join-command` 的输出信息中返回哈希值。 +默认情况下,在 `kubeadm init` 最后打印的 `kubeadm join` 命令或者 `kubeadm token create --print-join-command` 的输出信息中返回哈希值。 它使用标准格式 (请参考 [RFC7469](https://tools.ietf.org/html/rfc7469#section-2.4)) 并且也能通过第三方工具或者驱动系统进行计算。 例如,使用 OpenSSL CLI: diff --git a/content/zh/docs/setup/best-practices/certificates.md b/content/zh/docs/setup/best-practices/certificates.md new file mode 100644 index 0000000000..0d04a4dbf4 --- /dev/null +++ b/content/zh/docs/setup/best-practices/certificates.md @@ -0,0 +1,285 @@ +--- +title: PKI 证书和要求 +reviewers: +- sig-cluster-lifecycle +content_template: templates/concept +weight: 40 +--- + + +{{% capture overview %}} + + +Kubernetes 需要 PKI 证书才能进行基于 TLS 的身份验证。如果您是使用 [kubeadm](/docs/reference/setup-tools/kubeadm/kubeadm/) 安装的 Kubernetes,则会自动生成集群所需的证书。您还可以生成自己的证书。例如,不将私钥存储在 API 服务器上,可以让私钥更加安全。此页面说明了集群必需的证书。 + +{{% /capture %}} + +{{% capture body %}} + + +## 集群是如何使用证书的 + +Kubernetes 需要 PKI 才能执行以下操作: + + +* Kubelet 的客户端证书,用于 API 服务器身份验证 +* API 服务器端点的证书 +* 集群管理员的客户端证书,用于 API 服务器身份认证 +* API 服务器的客户端证书,用于和 Kubelet 的会话 +* API 服务器的客户端证书,用于和 etcd 的会话 +* 控制器管理器的客户端证书/kubeconfig,用于和 API server 的会话 +* 调度器的客户端证书/kubeconfig,用于和 API server 的会话 +* [前端代理][proxy] 的客户端及服务端证书 + +{{< note >}} + +只有当您运行 kube-proxy 并要支持[扩展 API 服务器](/docs/tasks/access-kubernetes-api/setup-extension-api-server/)时,才需要 `front-proxy` 证书 +{{< /note >}} + + +etcd 还实现了双向 TLS 来对客户端和对其他对等节点进行身份验证。 + + +## 证书存放的位置 + +如果你是通过 kubeadm 安装的 Kubernetes,所有证书都存放在 `/etc/kuberntes/pki` 目录下。本文所有相关的路径都是基于该路径的相对路径。 + + +## 手动配置证书 + +如果你不想通过 kubeadm 生成这些必需的证书,你可以通过下面两种方式之一来手动创建他们。 + + +### 单根 CA + +你可以创建一个单根 CA,由管理员控制器它。该根 CA 可以创建多个中间 CA,并将所有进一步的创建委托给 Kubernetes。 + + +需要这些 CA: + +| 路径 | 默认 CN | 描述 | +|------------------------|---------------------------|----------------------------------| +| ca.crt,key | kubernetes-ca | Kubernetes 通用 CA | +| etcd/ca.crt,key | etcd-ca | 与 etcd 相关的所有功能 | +| front-proxy-ca.crt,key | kubernetes-front-proxy-ca | 用于 [前端代理][proxy] | + +上面的 CA 之外,还需要获取用于服务账户管理的密钥对,也就是 `sa.key` 和 `sa.pub`。 + + +### 所有的证书 + +如果你不想将 CA 的私钥拷贝至你的集群中,你也可以自己生成全部的证书。 + +需要这些证书: + +| 默认 CN | 父级 CA | O (位于 Subject 中) | 类型 | 主机 (SAN) | +|-------------------------------|---------------------------|----------------|----------------------------------------|---------------------------------------------| +| kube-etcd | etcd-ca | | server, client | `localhost`, `127.0.0.1` | +| kube-etcd-peer | etcd-ca | | server, client | ``, ``, `localhost`, `127.0.0.1` | +| kube-etcd-healthcheck-client | etcd-ca | | client | | +| kube-apiserver-etcd-client | etcd-ca | system:masters | client | | +| kube-apiserver | kubernetes-ca | | server | ``, ``, ``, `[1]` | +| kube-apiserver-kubelet-client | kubernetes-ca | system:masters | client | | +| front-proxy-client | kubernetes-front-proxy-ca | | client | | + + +[1]: 用来连接到集群的不同 IP 或 DNS 名(就像 [kubeadm][kubeadm] 为负载均衡所使用的固定 IP 或 DNS 名,`kubernetes`、`kubernetes.default`、`kubernetes.default.svc`、`kubernetes.default.svc.cluster`、`kubernetes.default.svc.cluster.local`) + +其中,`kind` 对应一种或多种类型的 [x509 密钥用途][usage]: + + +| kind | 密钥用途 | +|--------|---------------------------------------------------------------------------------| +| server | 数字签名、密钥加密、服务端认证 | +| client | 数字签名、密钥加密、客户端认证 | + + +{{< note >}} + +上面列出的 Hosts/SAN 是推荐的配置方式;如果需要特殊安装,则可以在所有服务器证书上添加其他 SAN。 +{{< /note >}} + +{{< note >}} + +对于 kubeadm 用户: + +* 不使用私钥,将证书复制到集群 CA 的方案,在 kubeadm 文档中将这种方案称为外部 CA。 +* 如果将以上列表与 kubeadm 生成的 PKI 进行比较,你会注意到,如果使用外部 etcd,则不会生成 `kube-etcd`、`kube-etcd-peer` 和 `kube-etcd-healthcheck-client` 证书。 + +{{< /note >}} + + +### 证书路径 + +证书应放置在建议的路径中(以便 [kubeadm][kubeadm]使用)。无论使用什么位置,都应使用给定的参数指定路径。 + +| 默认 CN | 建议的密钥路径 | 建议的证书路径 | 命令 | 密钥参数 | 证书参数 | +|------------------------------|------------------------------|-----------------------------|----------------|------------------------------|-------------------------------------------| +| etcd-ca | etcd/ca.key | etcd/ca.crt | kube-apiserver | | --etcd-cafile | +| kube-apiserver-etcd-client | apiserver-etcd-client.key | apiserver-etcd-client.crt | kube-apiserver | --etcd-keyfile | --etcd-certfile | +| kubernetes-ca | ca.key | ca.crt | kube-apiserver | | --client-ca-file | +| kubernetes-ca | ca.key | ca.crt | kube-controller-manager | --cluster-signing-key-file | --client-ca-file, --root-ca-file, --cluster-signing-cert-file | +| kube-apiserver | apiserver.key | apiserver.crt | kube-apiserver | --tls-private-key-file | --tls-cert-file | +| kube-apiserver-kubelet-client| apiserver-kubelet-client.key | apiserver-kubelet-client.crt| kube-apiserver | --kubelet-client-key | --kubelet-client-certificate | +| front-proxy-ca | front-proxy-ca.key | front-proxy-ca.crt | kube-apiserver | | --requestheader-client-ca-file | +| front-proxy-ca | front-proxy-ca.key | front-proxy-ca.crt | kube-controller-manager | | --requestheader-client-ca-file | +| front-proxy-client | front-proxy-client.key | front-proxy-client.crt | kube-apiserver | --proxy-client-key-file | --proxy-client-cert-file | +| etcd-ca | etcd/ca.key | etcd/ca.crt | etcd | | --trusted-ca-file, --peer-trusted-ca-file | +| kube-etcd | etcd/server.key | etcd/server.crt | etcd | --key-file | --cert-file | +| kube-etcd-peer | etcd/peer.key | etcd/peer.crt | etcd | --peer-key-file | --peer-cert-file | +| etcd-ca | | etcd/ca.crt | etcdctl | | --cacert | +| kube-etcd-healthcheck-client | etcd/healthcheck-client.key | etcd/healthcheck-client.crt | etcdctl | --key | --cert | + + +注意事项同样适用于服务帐户密钥对: + +| 私钥路径 | 公钥路径 | 命令 | 参数 | +|------------------------------|-----------------------------|-------------------------|--------------------------------------| +| sa.key | | kube-controller-manager | service-account-private | +| | sa.pub | kube-apiserver | service-account-key | + + +## 为用户帐户配置证书 + +您必须手动配置以下管理员帐户和服务帐户: + +| 文件名 | 凭据名称 | 默认 CN | O (位于 Subject 中) | +|-------------------------|----------------------------|--------------------------------|----------------| +| admin.conf | default-admin | kubernetes-admin | system:masters | +| kubelet.conf | default-auth | system:node:`` (see note) | system:nodes | +| controller-manager.conf | default-controller-manager | system:kube-controller-manager | | +| scheduler.conf | default-scheduler | system:kube-scheduler | | + +{{< note >}} + +`kubelet.conf` 中 `` 的值 **必须** 与 kubelet 向 apiserver 注册时提供的节点名称的值完全匹配。有关更多详细信息,请阅读[节点授权](/docs/reference/access-authn-authz/node/)。 +{{< /note >}} + + +1. 对于每个配置,请都使用给定的 CN 和 O 生成 x509 证书/密钥偶对。 + +1. 为每个配置运行下面的 `kubectl` 命令: + +```shell +KUBECONFIG= kubectl config set-cluster default-cluster --server=https://:6443 --certificate-authority --embed-certs +KUBECONFIG= kubectl config set-credentials --client-key .pem --client-certificate .pem --embed-certs +KUBECONFIG= kubectl config set-context default-system --cluster default-cluster --user +KUBECONFIG= kubectl config use-context default-system +``` + + +这些文件用途如下: + +| 文件名 | 命令 | 说明 | +|-------------------------|-------------------------|-----------------------------------------------------------------------| +| admin.conf | kubectl | 配置集群的管理员 | +| kubelet.conf | kubelet | 集群中的每个节点都需要一份 | +| controller-manager.conf | kube-controller-manager | 必需添加到 `manifests/kube-controller-manager.yaml` 清单中 | +| scheduler.conf | kube-scheduler | 必需添加到 `manifests/kube-scheduler.yaml` 清单中 | + +[usage]: https://godoc.org/k8s.io/api/certificates/v1beta1#KeyUsage +[kubeadm]: /docs/reference/setup-tools/kubeadm/kubeadm/ +[proxy]: /docs/tasks/access-kubernetes-api/configure-aggregation-layer/ + +{{% /capture %}} diff --git a/content/zh/docs/setup/production-environment/tools/kubeadm/setup-ha-etcd-with-kubeadm.md b/content/zh/docs/setup/production-environment/tools/kubeadm/setup-ha-etcd-with-kubeadm.md index ef00f6562c..a3e4420e35 100644 --- a/content/zh/docs/setup/production-environment/tools/kubeadm/setup-ha-etcd-with-kubeadm.md +++ b/content/zh/docs/setup/production-environment/tools/kubeadm/setup-ha-etcd-with-kubeadm.md @@ -1,7 +1,7 @@ --- title: 使用 kubeadm 创建一个高可用 etcd 集群 content_template: templates/task -weight: 60 +weight: 70 --- {{% capture overview %}} +{{< note >}} + +在本指南中,当 kubeadm 用作为外部 etcd 节点管理工具,请注意 kubeadm 不计划支持此类节点的证书更换或升级。对于长期规划是使用 [etcdadm](https://github.com/kubernetes-sigs/etcdadm) 增强工具来管理这方面。 +{{< /note >}} + ```sh - kubeadm alpha phase certs etcd-server --config=/tmp/${HOST2}/kubeadmcfg.yaml - kubeadm alpha phase certs etcd-peer --config=/tmp/${HOST2}/kubeadmcfg.yaml - kubeadm alpha phase certs etcd-healthcheck-client --config=/tmp/${HOST2}/kubeadmcfg.yaml - kubeadm alpha phase certs apiserver-etcd-client --config=/tmp/${HOST2}/kubeadmcfg.yaml + kubeadm init phase certs etcd-server --config=/tmp/${HOST2}/kubeadmcfg.yaml + kubeadm init phase certs etcd-peer --config=/tmp/${HOST2}/kubeadmcfg.yaml + kubeadm init phase certs etcd-healthcheck-client --config=/tmp/${HOST2}/kubeadmcfg.yaml + kubeadm init phase certs apiserver-etcd-client --config=/tmp/${HOST2}/kubeadmcfg.yaml cp -R /etc/kubernetes/pki /tmp/${HOST2}/ # 清理不可重复使用的证书 find /etc/kubernetes/pki -not -name ca.crt -not -name ca.key -type f -delete - kubeadm alpha phase certs etcd-server --config=/tmp/${HOST1}/kubeadmcfg.yaml - kubeadm alpha phase certs etcd-peer --config=/tmp/${HOST1}/kubeadmcfg.yaml - kubeadm alpha phase certs etcd-healthcheck-client --config=/tmp/${HOST1}/kubeadmcfg.yaml - kubeadm alpha phase certs apiserver-etcd-client --config=/tmp/${HOST1}/kubeadmcfg.yaml + kubeadm init phase certs etcd-server --config=/tmp/${HOST1}/kubeadmcfg.yaml + kubeadm init phase certs etcd-peer --config=/tmp/${HOST1}/kubeadmcfg.yaml + kubeadm init phase certs etcd-healthcheck-client --config=/tmp/${HOST1}/kubeadmcfg.yaml + kubeadm init phase certs apiserver-etcd-client --config=/tmp/${HOST1}/kubeadmcfg.yaml cp -R /etc/kubernetes/pki /tmp/${HOST1}/ find /etc/kubernetes/pki -not -name ca.crt -not -name ca.key -type f -delete - kubeadm alpha phase certs etcd-server --config=/tmp/${HOST0}/kubeadmcfg.yaml - kubeadm alpha phase certs etcd-peer --config=/tmp/${HOST0}/kubeadmcfg.yaml - kubeadm alpha phase certs etcd-healthcheck-client --config=/tmp/${HOST0}/kubeadmcfg.yaml - kubeadm alpha phase certs apiserver-etcd-client --config=/tmp/${HOST0}/kubeadmcfg.yaml + kubeadm init phase certs etcd-server --config=/tmp/${HOST0}/kubeadmcfg.yaml + kubeadm init phase certs etcd-peer --config=/tmp/${HOST0}/kubeadmcfg.yaml + kubeadm init phase certs etcd-healthcheck-client --config=/tmp/${HOST0}/kubeadmcfg.yaml + kubeadm init phase certs apiserver-etcd-client --config=/tmp/${HOST0}/kubeadmcfg.yaml # 不需要移动 certs 因为它们是给 HOST0 使用的 # 清理不应从此主机复制的证书 @@ -370,9 +381,9 @@ kubeadm 包含生成下述证书所需的所有必要的密码学工具;在这 既然证书和配置已经就绪,是时候去创建清单了。在每台主机上运行 `kubeadm` 命令来生成 etcd 使用的静态清单。 ```sh - root@HOST0 $ kubeadm alpha phase etcd local --config=/tmp/${HOST0}/kubeadmcfg.yaml - root@HOST1 $ kubeadm alpha phase etcd local --config=/home/ubuntu/kubeadmcfg.yaml - root@HOST2 $ kubeadm alpha phase etcd local --config=/home/ubuntu/kubeadmcfg.yaml + root@HOST0 $ kubeadm init phase etcd local --config=/tmp/${HOST0}/kubeadmcfg.yaml + root@HOST1 $ kubeadm init phase etcd local --config=/home/ubuntu/kubeadmcfg.yaml + root@HOST2 $ kubeadm init phase etcd local --config=/home/ubuntu/kubeadmcfg.yaml ``` + - 将 `${ETCD_TAG}` 设置为你的 etcd 镜像的版本标签,例如 `3.4.3-0`。要查看 kubeadm 使用的 etcd 镜像和标签,请执行 `kubeadm config images list --kubernetes-version ${K8S_VERSION}`,其中 `${K8S_VERSION}` 是 `v1.17.0` 作为例子。 + + - 将 `${HOST0}` 设置为要测试的主机的 IP 地址 {{% /capture %}} diff --git a/content/zh/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md b/content/zh/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md index 8b514ad40b..1e3ab441b4 100644 --- a/content/zh/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md +++ b/content/zh/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm.md @@ -1,650 +1,650 @@ ---- -title: 对 kubeadm 进行故障排查 -content_template: templates/concept -weight: 20 ---- - - -{{% capture overview %}} - - -与任何程序一样,您可能会在安装或者运行 kubeadm 时遇到错误。 -本文列举了一些常见的故障场景,并提供可帮助您理解和解决这些问题的步骤。 - -如果您的问题未在下面列出,请执行以下步骤: - -- 如果您认为问题是 kubeadm 的错误: - - 转到 [github.com/kubernetes/kubeadm](https://github.com/kubernetes/kubeadm/issues) 并搜索存在的问题。 - - 如果没有问题,请 [打开](https://github.com/kubernetes/kubeadm/issues/new) 并遵循问题模板。 - -- 如果您对 kubeadm 的工作方式有疑问,可以在 [Slack](http://slack.k8s.io/) 上的 #kubeadm 频道提问, -或者在 [StackOverflow](https://stackoverflow.com/questions/tagged/kubernetes) 上提问。 -请加入相关标签,例如 `#kubernetes` 和 `#kubeadm`,这样其他人可以帮助您。 - -{{% /capture %}} - -{{% capture body %}} - - -## 在安装过程中没有找到 `ebtables` 或者其他类似的可执行文件 - -如果在运行 `kubeadm init` 命令时,遇到以下的警告 - -```sh -[preflight] WARNING: ebtables not found in system path -[preflight] WARNING: ethtool not found in system path -``` - -那么或许在您的节点上缺失 `ebtables`、`ethtool` 或者类似的可执行文件。 -您可以使用以下命令安装它们: - -- 对于 Ubuntu/Debian 用户,运行 `apt install ebtables ethtool` 命令。 -- 对于 CentOS/Fedora 用户,运行 `yum install ebtables ethtool` 命令。 - - -## 在安装过程中,kubeadm 一直等待控制平面就绪 - -如果您注意到 `kubeadm init` 在打印以下行后挂起: - -```sh -[apiclient] Created API client, waiting for the control plane to become ready -``` - - -这可能是由许多问题引起的。最常见的是: - -- 网络连接问题。在继续之前,请检查您的计算机是否具有全部联通的网络连接。 -- kubelet 的默认 cgroup 驱动程序配置不同于 Docker 使用的配置。 - 检查系统日志文件 (例如 `/var/log/message`) 或检查 `journalctl -u kubelet` 的输出。 如果您看见以下内容: - - ```shell - error: failed to run Kubelet: failed to create kubelet: - misconfiguration: kubelet cgroup driver: "systemd" is different from docker cgroup driver: "cgroupfs" - ``` - - 有两种常见方法可解决 cgroup 驱动程序问题: - - 1. 按照 [此处](/docs/setup/production-environment/container-runtimes/#docker) 的说明再次安装 Docker。 - - 1. 更改 kubelet 配置以手动匹配 Docker cgroup 驱动程序,您可以参考 - [在主节点上配置 kubelet 要使用的 cgroup 驱动程序](/docs/setup/production-environment/tools/kubeadm/install-kubeadm/#configure-cgroup-driver-used-by-kubelet-on-master-node) - -- 控制平面上的 Docker 容器持续进入崩溃状态或(因其他原因)挂起。您可以运行 `docker ps` 命令来检查以及 `docker logs` 命令来检视每个容器的运行日志。 - - -## 当删除托管容器时 kubeadm 阻塞 - -如果 Docker 停止并且不删除 Kubernetes 所管理的所有容器,可能发生以下情况: - -```bash -sudo kubeadm reset -[preflight] Running pre-flight checks -[reset] Stopping the kubelet service -[reset] Unmounting mounted directories in "/var/lib/kubelet" -[reset] Removing kubernetes-managed containers -(block) -``` - -一个可行的解决方案是重新启动 Docker 服务,然后重新运行 `kubeadm reset`: - -```bash -sudo systemctl restart docker.service -sudo kubeadm reset -``` - -检查 docker 的日志也可能有用: - -```sh -journalctl -ul docker -``` - - -## Pods 处于 `RunContainerError`、`CrashLoopBackOff` 或者 `Error` 状态 - -在 `kubeadm init` 命令运行后,系统中不应该有 pods 处于这类状态。 - -- 在 `kubeadm init` 命令执行完后,如果有 pods 处于这些状态之一,请在 kubeadm - 仓库提起一个 issue。`coredns` (或者 `kube-dns`) 应该处于 `Pending` 状态, - 直到您部署了网络解决方案为止。 -- 如果在部署完网络解决方案之后,有 Pods 处于 `RunContainerError`、`CrashLoopBackOff` - 或 `Error` 状态之一,并且`coredns` (或者 `kube-dns`)仍处于 `Pending` 状态, - 那很可能是您安装的网络解决方案由于某种原因无法工作。您或许需要授予它更多的 - RBAC 特权或使用较新的版本。请在 Pod Network 提供商的问题跟踪器中提交问题, - 然后在此处分类问题。 -- 如果您安装的 Docker 版本早于 1.12.1,请在使用 `systemd` 来启动 `dockerd` 和重启 `docker` 时, - 删除 `MountFlags=slave` 选项。 - 您可以在 `/usr/lib/systemd/system/docker.service` 中看到 MountFlags。 - MountFlags 可能会干扰 Kubernetes 挂载的卷, 并使 Pods 处于 `CrashLoopBackOff` 状态。 - 当 Kubernetes 不能找到 `var/run/secrets/kubernetes.io/serviceaccount` 文件时会发生错误。 - - -## `coredns` (或 `kube-dns`)停滞在 `Pending` 状态 - -这一行为是 **预期之中** 的,因为系统就是这么设计的。 -kubeadm 的网络供应商是中立的,因此管理员应该选择 [安装 pod 的网络解决方案](/docs/concepts/cluster-administration/addons/)。 -您必须完成 Pod 的网络配置,然后才能完全部署 CoreDNS。 -在网络被配置好之前,DNS 组件会一直处于 `Pending` 状态。 - - -## `HostPort` 服务无法工作 - -此 `HostPort` 和 `HostIP` 功能是否可用取决于您的 Pod 网络配置。请联系 Pod 解决方案的作者, -以确认 `HostPort` 和 `HostIP` 功能是否可用。 - -已验证 Calico、Canal 和 Flannel CNI 驱动程序支持 HostPort。 - -有关更多信息,请参考 [CNI portmap 文档](https://github.com/containernetworking/plugins/blob/master/plugins/meta/portmap/README.md). - -如果您的网络提供商不支持 portmap CNI 插件,您或许需要使用 [NodePort 服务的功能](/docs/concepts/services-networking/service/#nodeport) 或者使用 `HostNetwork=true`。 - - -## 无法通过其服务 IP 访问 Pod - -- 许多网络附加组件尚未启用 [hairpin 模式](/docs/tasks/debug-application-cluster/debug-service/#a-pod-cannot-reach-itself-via-service-ip) - 该模式允许 Pod 通过其服务 IP 进行访问。这是与 [CNI](https://github.com/containernetworking/cni/issues/476) 有关的问题。请与网络附加组件提供商联系,以获取他们所提供的 hairpin 模式的最新状态。 - -- 如果您正在使用 VirtualBox (直接使用或者通过 Vagrant 使用),您需要 - 确保 `hostname -i` 返回一个可路由的 IP 地址。默认情况下,第一个接口连接不能路由的仅主机网络。 - 解决方法是修改 `/etc/hosts`,请参考示例 [Vagrantfile](https://github.com/errordeveloper/k8s-playground/blob/22dd39dfc06111235620e6c4404a96ae146f26fd/Vagrantfile#L11)。 - - -## TLS 证书错误 - -以下错误指出证书可能不匹配。 - -```none -# kubectl get pods -Unable to connect to the server: x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "kubernetes") -``` - -- 验证 `$HOME/.kube/config` 文件是否包含有效证书,并 - 在必要时重新生成证书。在 kubeconfig 文件中的证书是 base64 编码的。 - 该 `base64 -d` 命令可以用来解码证书,`openssl x509 -text -noout` 命令 - 可以用于查看证书信息。 -- 使用如下方法取消设置 `KUBECONFIG` 环境变量的值: - - ```sh - unset KUBECONFIG - ``` - - 或者将其设置为默认的 `KUBECONFIG` 位置: - - ```sh - export KUBECONFIG=/etc/kubernetes/admin.conf - ``` - -- 另一个方法是覆盖 `kubeconfig` 的现有用户 "管理员" : - - ```sh - mv $HOME/.kube $HOME/.kube.bak - mkdir $HOME/.kube - sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config - sudo chown $(id -u):$(id -g) $HOME/.kube/config - ``` - - -## 在 Vagrant 中使用 flannel 作为 pod 网络时的默认 NIC - -以下错误可能表明 Pod 网络中出现问题: - -```sh -Error from server (NotFound): the server could not find the requested resource -``` - -- 如果你正在 Vagrant 中使用 flannel 作为 pod 网络,则必须指定 flannel 的默认接口名称。 - - Vagrant 通常为所有 VM 分配两个接口。第一个为所有主机分配了 IP 地址 `10.0.2.15`,用于获得 NATed 的外部流量。 - - 这可能会导致 flannel 出现问题,它默认为主机上的第一个接口。这导致所有主机认为它们具有 - 相同的公共 IP 地址。为防止这种情况,传递 `--iface eth1` 标志给 flannel 以便选择第二个接口。 - - -## 容器使用的非公共 IP - -在某些情况下 `kubectl logs` 和 `kubectl run` 命令或许会返回以下错误,即便除此之外集群一切功能正常: - -```sh -Error from server: Get https://10.19.0.41:10250/containerLogs/default/mysql-ddc65b868-glc5m/mysql: dial tcp 10.19.0.41:10250: getsockopt: no route to host -``` - -- 这或许是由于 Kubernetes 使用的 IP 无法与看似相同的子网上的其他 IP 进行通信的缘故, -可能是由机器提供商的政策所导致的。 -- Digital Ocean 既分配一个共有 IP 给 `eth0`,也分配一个私有 IP 在内部用作其浮动 IP 功能的锚点, -然而 `kubelet` 将选择后者作为节点的 `InternalIP` 而不是公共 IP - - 使用 `ip addr show` 命令代替 `ifconfig` 命令去检查这种情况,因为 `ifconfig` 命令 - 不会显示有问题的别名 IP 地址。或者指定的 Digital Ocean 的 API 端口允许从 droplet 中 - 查询 anchor IP: - - ```sh - curl http://169.254.169.254/metadata/v1/interfaces/public/0/anchor_ipv4/address - ``` - - 解决方法是通知 `kubelet` 使用哪个 `--node-ip`。当使用 Digital Ocean 时,可以是公网IP(分配给 `eth0`的), - 或者是私网IP(分配给 `eth1` 的)。私网 IP 是可选的。 - 这个 [`KubeletExtraArgs` section of the kubeadm `NodeRegistrationOptions` structure](https://github.com/kubernetes/kubernetes/blob/release-1.13/cmd/kubeadm/app/apis/kubeadm/v1beta1/types.go) 被用来处理这种情况。 - - 然后重启 `kubelet`: - - ```sh - systemctl daemon-reload - systemctl restart kubelet - ``` - -## `coredns` pods 有 `CrashLoopBackOff` 或者 `Error` 状态 - -如果有些节点运行的是旧版本的 Docker,同时启用了 SELinux,您或许会遇到 `coredns` pods 无法启动的情况。 -要解决此问题,您可以尝试以下选项之一: - -- 升级到 [Docker 的较新版本](/docs/setup/production-environment/container-runtimes/#docker)。 - -- [禁用 SELinux](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security-enhanced_linux/sect-security-enhanced_linux-enabling_and_disabling_selinux-disabling_selinux). -- 修改 `coredns` 部署以设置 `allowPrivilegeEscalation` 为 `true`: - -```bash -kubectl -n kube-system get deployment coredns -o yaml | \ - sed 's/allowPrivilegeEscalation: false/allowPrivilegeEscalation: true/g' | \ - kubectl apply -f - -``` - -CoreDNS 处于 `CrashLoopBackOff` 时的另一个原因是当 Kubernetes 中部署的 CoreDNS Pod 检测 -到环路时。[有许多解决方法](https://github.com/coredns/coredns/tree/master/plugin/loop#troubleshooting-loops-in-kubernetes-clusters) -可以避免在每次 CoreDNS 监测到循环并退出时,Kubernetes 尝试重启 CoreDNS Pod 的情况。 - -{{< warning >}} - -**警告**:禁用 SELinux 或设置 `allowPrivilegeEscalation` 为 `true` 可能会损害集群的安全性。 -{{< /warning >}} - - -## etcd pods 持续重启 - -如果您遇到以下错误: - -``` -rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "process_linux.go:110: decoding init error from pipe caused \"read parent: connection reset by peer\"" -``` - -如果您使用 Docker 1.13.1.84 运行 CentOS 7 就会出现这种问题。 -此版本的 Docker 会阻止 kubelet 在 etcd 容器中执行。 - -为解决此问题,请选择以下选项之一: - -- 回滚到早期版本的 Docker,例如 1.13.1-75 -``` -yum downgrade docker-1.13.1-75.git8633870.el7.centos.x86_64 docker-client-1.13.1-75.git8633870.el7.centos.x86_64 docker-common-1.13.1-75.git8633870.el7.centos.x86_64 -``` - -- 安装较新的推荐版本之一,例如 18.06: -```bash -sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo -yum install docker-ce-18.06.1.ce-3.el7.x86_64 -``` - - -## 无法将以逗号分隔的值列表传递给 `--component-extra-args` 标志内的参数 - -`kubeadm init` 标志例如 `--component-extra-args` 允许您将自定义参数传递给像 kube-apiserver 这样的控制平面组件。然而,由于解析 (`mapStringString`) 的基础类型值,此机制将受到限制。 - -如果您决定传递一个支持多个逗号分隔值(例如 `--apiserver-extra-args "enable-admission-plugins=LimitRanger,NamespaceExists"`)参数,将出现 `flag: malformed pair, expect string=string` 错误。 -发生这种问题是因为参数列表 `--apiserver-extra-args` 预期的是 `key=value` 形式,而这里的 `NamespacesExists` 被误认为是缺少取值的键名。 - -一种解决方法是尝试分离 `key=value` 对,像这样: -`--apiserver-extra-args "enable-admission-plugins=LimitRanger,enable-admission-plugins=NamespaceExists"` -但这将导致键 `enable-admission-plugins` 仅有值 `NamespaceExists`。 - -已知的解决方法是使用 kubeadm [配置文件](/docs/setup/production-environment/tools/kubeadm/control-plane-flags/#apiserver-flags)。 - - -## 在节点被云控制管理器初始化之前,kube-proxy 就被调度了 - -在云环境场景中,可能出现在云控制管理器完成节点地址初始化之前,kube-proxy 就被调度到新节点了。 -这会导致 kube-proxy 无法正确获取节点的 IP 地址,并对管理负载平衡器的代理功能产生连锁反应。 - -在 kube-proxy Pod 中可以看到以下错误: -``` -server.go:610] Failed to retrieve node IP: host IP unknown; known addresses: [] -proxier.go:340] invalid nodeIP, initializing kube-proxy with 127.0.0.1 as nodeIP -``` - -一种已知的解决方案是修补 kube-proxy DaemonSet,以允许在控制平面节点上调度它,而不管它们的条件如何,将其与其他节点保持隔离,直到它们的初始保护条件消除: -``` -kubectl -n kube-system patch ds kube-proxy -p='{ "spec": { "template": { "spec": { "tolerations": [ { "key": "CriticalAddonsOnly", "operator": "Exists" }, { "effect": "NoSchedule", "key": "node-role.kubernetes.io/master" } ] } } } }' -``` - -此问题的跟踪 [在这里](https://github.com/kubernetes/kubeadm/issues/1027)。 - - -## NodeRegistration.Taints 字段在编组 kubeadm 配置时丢失 - -*注意:这个 [问题](https://github.com/kubernetes/kubeadm/issues/1358) 仅适用于操控 kubeadm 数据类型的工具(例如,YAML 配置文件)。它将在 kubeadm API v1beta2 修复。* - -默认情况下,kubeadm 将 `role.kubernetes.io/master:NoSchedule` 污点应用于控制平面节点。 -如果您希望 kubeadm 不污染控制平面节点,并将 `InitConfiguration.NodeRegistration.Taints` 设置成空切片,则应在编组时省略该字段。 -如果省略该字段,则 kubeadm 将应用默认污点。 - -至少有两种解决方法: - -1. 使用 `role.kubernetes.io/master:PreferNoSchedule` 污点代替空切片。 -除非其他节点具有容量,[否则将在主节点上调度 Pods](https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/)。 - -2. 在 kubeadm init 退出后删除污点: -```bash -kubectl taint nodes NODE_NAME role.kubernetes.io/master:NoSchedule- -``` - -{{% /capture %}} +--- +title: 对 kubeadm 进行故障排查 +content_template: templates/concept +weight: 20 +--- + + +{{% capture overview %}} + + +与任何程序一样,您可能会在安装或者运行 kubeadm 时遇到错误。 +本文列举了一些常见的故障场景,并提供可帮助您理解和解决这些问题的步骤。 + +如果您的问题未在下面列出,请执行以下步骤: + +- 如果您认为问题是 kubeadm 的错误: + - 转到 [github.com/kubernetes/kubeadm](https://github.com/kubernetes/kubeadm/issues) 并搜索存在的问题。 + - 如果没有问题,请 [打开](https://github.com/kubernetes/kubeadm/issues/new) 并遵循问题模板。 + +- 如果您对 kubeadm 的工作方式有疑问,可以在 [Slack](http://slack.k8s.io/) 上的 #kubeadm 频道提问, +或者在 [StackOverflow](https://stackoverflow.com/questions/tagged/kubernetes) 上提问。 +请加入相关标签,例如 `#kubernetes` 和 `#kubeadm`,这样其他人可以帮助您。 + +{{% /capture %}} + +{{% capture body %}} + + +## 在安装过程中没有找到 `ebtables` 或者其他类似的可执行文件 + +如果在运行 `kubeadm init` 命令时,遇到以下的警告 + +```sh +[preflight] WARNING: ebtables not found in system path +[preflight] WARNING: ethtool not found in system path +``` + +那么或许在您的节点上缺失 `ebtables`、`ethtool` 或者类似的可执行文件。 +您可以使用以下命令安装它们: + +- 对于 Ubuntu/Debian 用户,运行 `apt install ebtables ethtool` 命令。 +- 对于 CentOS/Fedora 用户,运行 `yum install ebtables ethtool` 命令。 + + +## 在安装过程中,kubeadm 一直等待控制平面就绪 + +如果您注意到 `kubeadm init` 在打印以下行后挂起: + +```sh +[apiclient] Created API client, waiting for the control plane to become ready +``` + + +这可能是由许多问题引起的。最常见的是: + +- 网络连接问题。在继续之前,请检查您的计算机是否具有全部联通的网络连接。 +- kubelet 的默认 cgroup 驱动程序配置不同于 Docker 使用的配置。 + 检查系统日志文件 (例如 `/var/log/message`) 或检查 `journalctl -u kubelet` 的输出。 如果您看见以下内容: + + ```shell + error: failed to run Kubelet: failed to create kubelet: + misconfiguration: kubelet cgroup driver: "systemd" is different from docker cgroup driver: "cgroupfs" + ``` + + 有两种常见方法可解决 cgroup 驱动程序问题: + + 1. 按照 [此处](/docs/setup/production-environment/container-runtimes/#docker) 的说明再次安装 Docker。 + + 1. 更改 kubelet 配置以手动匹配 Docker cgroup 驱动程序,您可以参考 + [在主节点上配置 kubelet 要使用的 cgroup 驱动程序](/docs/setup/production-environment/tools/kubeadm/install-kubeadm/#configure-cgroup-driver-used-by-kubelet-on-master-node) + +- 控制平面上的 Docker 容器持续进入崩溃状态或(因其他原因)挂起。您可以运行 `docker ps` 命令来检查以及 `docker logs` 命令来检视每个容器的运行日志。 + + +## 当删除托管容器时 kubeadm 阻塞 + +如果 Docker 停止并且不删除 Kubernetes 所管理的所有容器,可能发生以下情况: + +```bash +sudo kubeadm reset +[preflight] Running pre-flight checks +[reset] Stopping the kubelet service +[reset] Unmounting mounted directories in "/var/lib/kubelet" +[reset] Removing kubernetes-managed containers +(block) +``` + +一个可行的解决方案是重新启动 Docker 服务,然后重新运行 `kubeadm reset`: + +```bash +sudo systemctl restart docker.service +sudo kubeadm reset +``` + +检查 docker 的日志也可能有用: + +```sh +journalctl -ul docker +``` + + +## Pods 处于 `RunContainerError`、`CrashLoopBackOff` 或者 `Error` 状态 + +在 `kubeadm init` 命令运行后,系统中不应该有 pods 处于这类状态。 + +- 在 `kubeadm init` 命令执行完后,如果有 pods 处于这些状态之一,请在 kubeadm + 仓库提起一个 issue。`coredns` (或者 `kube-dns`) 应该处于 `Pending` 状态, + 直到您部署了网络解决方案为止。 +- 如果在部署完网络解决方案之后,有 Pods 处于 `RunContainerError`、`CrashLoopBackOff` + 或 `Error` 状态之一,并且`coredns` (或者 `kube-dns`)仍处于 `Pending` 状态, + 那很可能是您安装的网络解决方案由于某种原因无法工作。您或许需要授予它更多的 + RBAC 特权或使用较新的版本。请在 Pod Network 提供商的问题跟踪器中提交问题, + 然后在此处分类问题。 +- 如果您安装的 Docker 版本早于 1.12.1,请在使用 `systemd` 来启动 `dockerd` 和重启 `docker` 时, + 删除 `MountFlags=slave` 选项。 + 您可以在 `/usr/lib/systemd/system/docker.service` 中看到 MountFlags。 + MountFlags 可能会干扰 Kubernetes 挂载的卷, 并使 Pods 处于 `CrashLoopBackOff` 状态。 + 当 Kubernetes 不能找到 `var/run/secrets/kubernetes.io/serviceaccount` 文件时会发生错误。 + + +## `coredns` (或 `kube-dns`)停滞在 `Pending` 状态 + +这一行为是 **预期之中** 的,因为系统就是这么设计的。 +kubeadm 的网络供应商是中立的,因此管理员应该选择 [安装 pod 的网络解决方案](/docs/concepts/cluster-administration/addons/)。 +您必须完成 Pod 的网络配置,然后才能完全部署 CoreDNS。 +在网络被配置好之前,DNS 组件会一直处于 `Pending` 状态。 + + +## `HostPort` 服务无法工作 + +此 `HostPort` 和 `HostIP` 功能是否可用取决于您的 Pod 网络配置。请联系 Pod 解决方案的作者, +以确认 `HostPort` 和 `HostIP` 功能是否可用。 + +已验证 Calico、Canal 和 Flannel CNI 驱动程序支持 HostPort。 + +有关更多信息,请参考 [CNI portmap 文档](https://github.com/containernetworking/plugins/blob/master/plugins/meta/portmap/README.md). + +如果您的网络提供商不支持 portmap CNI 插件,您或许需要使用 [NodePort 服务的功能](/docs/concepts/services-networking/service/#nodeport) 或者使用 `HostNetwork=true`。 + + +## 无法通过其服务 IP 访问 Pod + +- 许多网络附加组件尚未启用 [hairpin 模式](/docs/tasks/debug-application-cluster/debug-service/#a-pod-cannot-reach-itself-via-service-ip) + 该模式允许 Pod 通过其服务 IP 进行访问。这是与 [CNI](https://github.com/containernetworking/cni/issues/476) 有关的问题。请与网络附加组件提供商联系,以获取他们所提供的 hairpin 模式的最新状态。 + +- 如果您正在使用 VirtualBox (直接使用或者通过 Vagrant 使用),您需要 + 确保 `hostname -i` 返回一个可路由的 IP 地址。默认情况下,第一个接口连接不能路由的仅主机网络。 + 解决方法是修改 `/etc/hosts`,请参考示例 [Vagrantfile](https://github.com/errordeveloper/k8s-playground/blob/22dd39dfc06111235620e6c4404a96ae146f26fd/Vagrantfile#L11)。 + + +## TLS 证书错误 + +以下错误指出证书可能不匹配。 + +```none +# kubectl get pods +Unable to connect to the server: x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "kubernetes") +``` + +- 验证 `$HOME/.kube/config` 文件是否包含有效证书,并 + 在必要时重新生成证书。在 kubeconfig 文件中的证书是 base64 编码的。 + 该 `base64 -d` 命令可以用来解码证书,`openssl x509 -text -noout` 命令 + 可以用于查看证书信息。 +- 使用如下方法取消设置 `KUBECONFIG` 环境变量的值: + + ```sh + unset KUBECONFIG + ``` + + 或者将其设置为默认的 `KUBECONFIG` 位置: + + ```sh + export KUBECONFIG=/etc/kubernetes/admin.conf + ``` + +- 另一个方法是覆盖 `kubeconfig` 的现有用户 "管理员" : + + ```sh + mv $HOME/.kube $HOME/.kube.bak + mkdir $HOME/.kube + sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config + sudo chown $(id -u):$(id -g) $HOME/.kube/config + ``` + + +## 在 Vagrant 中使用 flannel 作为 pod 网络时的默认 NIC + +以下错误可能表明 Pod 网络中出现问题: + +```sh +Error from server (NotFound): the server could not find the requested resource +``` + +- 如果你正在 Vagrant 中使用 flannel 作为 pod 网络,则必须指定 flannel 的默认接口名称。 + + Vagrant 通常为所有 VM 分配两个接口。第一个为所有主机分配了 IP 地址 `10.0.2.15`,用于获得 NATed 的外部流量。 + + 这可能会导致 flannel 出现问题,它默认为主机上的第一个接口。这导致所有主机认为它们具有 + 相同的公共 IP 地址。为防止这种情况,传递 `--iface eth1` 标志给 flannel 以便选择第二个接口。 + + +## 容器使用的非公共 IP + +在某些情况下 `kubectl logs` 和 `kubectl run` 命令或许会返回以下错误,即便除此之外集群一切功能正常: + +```sh +Error from server: Get https://10.19.0.41:10250/containerLogs/default/mysql-ddc65b868-glc5m/mysql: dial tcp 10.19.0.41:10250: getsockopt: no route to host +``` + +- 这或许是由于 Kubernetes 使用的 IP 无法与看似相同的子网上的其他 IP 进行通信的缘故, +可能是由机器提供商的政策所导致的。 +- Digital Ocean 既分配一个共有 IP 给 `eth0`,也分配一个私有 IP 在内部用作其浮动 IP 功能的锚点, +然而 `kubelet` 将选择后者作为节点的 `InternalIP` 而不是公共 IP + + 使用 `ip addr show` 命令代替 `ifconfig` 命令去检查这种情况,因为 `ifconfig` 命令 + 不会显示有问题的别名 IP 地址。或者指定的 Digital Ocean 的 API 端口允许从 droplet 中 + 查询 anchor IP: + + ```sh + curl http://169.254.169.254/metadata/v1/interfaces/public/0/anchor_ipv4/address + ``` + + 解决方法是通知 `kubelet` 使用哪个 `--node-ip`。当使用 Digital Ocean 时,可以是公网IP(分配给 `eth0`的), + 或者是私网IP(分配给 `eth1` 的)。私网 IP 是可选的。 + 这个 [`KubeletExtraArgs` section of the kubeadm `NodeRegistrationOptions` structure](https://github.com/kubernetes/kubernetes/blob/release-1.13/cmd/kubeadm/app/apis/kubeadm/v1beta1/types.go) 被用来处理这种情况。 + + 然后重启 `kubelet`: + + ```sh + systemctl daemon-reload + systemctl restart kubelet + ``` + +## `coredns` pods 有 `CrashLoopBackOff` 或者 `Error` 状态 + +如果有些节点运行的是旧版本的 Docker,同时启用了 SELinux,您或许会遇到 `coredns` pods 无法启动的情况。 +要解决此问题,您可以尝试以下选项之一: + +- 升级到 [Docker 的较新版本](/docs/setup/production-environment/container-runtimes/#docker)。 + +- [禁用 SELinux](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security-enhanced_linux/sect-security-enhanced_linux-enabling_and_disabling_selinux-disabling_selinux). +- 修改 `coredns` 部署以设置 `allowPrivilegeEscalation` 为 `true`: + +```bash +kubectl -n kube-system get deployment coredns -o yaml | \ + sed 's/allowPrivilegeEscalation: false/allowPrivilegeEscalation: true/g' | \ + kubectl apply -f - +``` + +CoreDNS 处于 `CrashLoopBackOff` 时的另一个原因是当 Kubernetes 中部署的 CoreDNS Pod 检测 +到环路时。[有许多解决方法](https://github.com/coredns/coredns/tree/master/plugin/loop#troubleshooting-loops-in-kubernetes-clusters) +可以避免在每次 CoreDNS 监测到循环并退出时,Kubernetes 尝试重启 CoreDNS Pod 的情况。 + +{{< warning >}} + +**警告**:禁用 SELinux 或设置 `allowPrivilegeEscalation` 为 `true` 可能会损害集群的安全性。 +{{< /warning >}} + + +## etcd pods 持续重启 + +如果您遇到以下错误: + +``` +rpc error: code = 2 desc = oci runtime error: exec failed: container_linux.go:247: starting container process caused "process_linux.go:110: decoding init error from pipe caused \"read parent: connection reset by peer\"" +``` + +如果您使用 Docker 1.13.1.84 运行 CentOS 7 就会出现这种问题。 +此版本的 Docker 会阻止 kubelet 在 etcd 容器中执行。 + +为解决此问题,请选择以下选项之一: + +- 回滚到早期版本的 Docker,例如 1.13.1-75 +``` +yum downgrade docker-1.13.1-75.git8633870.el7.centos.x86_64 docker-client-1.13.1-75.git8633870.el7.centos.x86_64 docker-common-1.13.1-75.git8633870.el7.centos.x86_64 +``` + +- 安装较新的推荐版本之一,例如 18.06: +```bash +sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo +yum install docker-ce-18.06.1.ce-3.el7.x86_64 +``` + + +## 无法将以逗号分隔的值列表传递给 `--component-extra-args` 标志内的参数 + +`kubeadm init` 标志例如 `--component-extra-args` 允许您将自定义参数传递给像 kube-apiserver 这样的控制平面组件。然而,由于解析 (`mapStringString`) 的基础类型值,此机制将受到限制。 + +如果您决定传递一个支持多个逗号分隔值(例如 `--apiserver-extra-args "enable-admission-plugins=LimitRanger,NamespaceExists"`)参数,将出现 `flag: malformed pair, expect string=string` 错误。 +发生这种问题是因为参数列表 `--apiserver-extra-args` 预期的是 `key=value` 形式,而这里的 `NamespacesExists` 被误认为是缺少取值的键名。 + +一种解决方法是尝试分离 `key=value` 对,像这样: +`--apiserver-extra-args "enable-admission-plugins=LimitRanger,enable-admission-plugins=NamespaceExists"` +但这将导致键 `enable-admission-plugins` 仅有值 `NamespaceExists`。 + +已知的解决方法是使用 kubeadm [配置文件](/docs/setup/production-environment/tools/kubeadm/control-plane-flags/#apiserver-flags)。 + + +## 在节点被云控制管理器初始化之前,kube-proxy 就被调度了 + +在云环境场景中,可能出现在云控制管理器完成节点地址初始化之前,kube-proxy 就被调度到新节点了。 +这会导致 kube-proxy 无法正确获取节点的 IP 地址,并对管理负载平衡器的代理功能产生连锁反应。 + +在 kube-proxy Pod 中可以看到以下错误: +``` +server.go:610] Failed to retrieve node IP: host IP unknown; known addresses: [] +proxier.go:340] invalid nodeIP, initializing kube-proxy with 127.0.0.1 as nodeIP +``` + +一种已知的解决方案是修补 kube-proxy DaemonSet,以允许在控制平面节点上调度它,而不管它们的条件如何,将其与其他节点保持隔离,直到它们的初始保护条件消除: +``` +kubectl -n kube-system patch ds kube-proxy -p='{ "spec": { "template": { "spec": { "tolerations": [ { "key": "CriticalAddonsOnly", "operator": "Exists" }, { "effect": "NoSchedule", "key": "node-role.kubernetes.io/master" } ] } } } }' +``` + +此问题的跟踪 [在这里](https://github.com/kubernetes/kubeadm/issues/1027)。 + + +## NodeRegistration.Taints 字段在编组 kubeadm 配置时丢失 + +*注意:这个 [问题](https://github.com/kubernetes/kubeadm/issues/1358) 仅适用于操控 kubeadm 数据类型的工具(例如,YAML 配置文件)。它将在 kubeadm API v1beta2 修复。* + +默认情况下,kubeadm 将 `node-role.kubernetes.io/master:NoSchedule` 污点应用于控制平面节点。 +如果您希望 kubeadm 不污染控制平面节点,并将 `InitConfiguration.NodeRegistration.Taints` 设置成空切片,则应在编组时省略该字段。 +如果省略该字段,则 kubeadm 将应用默认污点。 + +至少有两种解决方法: + +1. 使用 `node-role.kubernetes.io/master:PreferNoSchedule` 污点代替空切片。 +除非其他节点具有容量,[否则将在主节点上调度 Pods](https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/)。 + +2. 在 kubeadm init 退出后删除污点: +```bash +kubectl taint nodes NODE_NAME node-role.kubernetes.io/master:NoSchedule- +``` + +{{% /capture %}} diff --git a/content/zh/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume.md b/content/zh/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume.md index b08a6dda2e..a858c266c5 100644 --- a/content/zh/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume.md +++ b/content/zh/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume.md @@ -1,10 +1,5 @@ --- title: 同 Pod 内的容器使用共享卷通信 -redirect_from: -- "/docs/user-guide/pods/multi-container/" -- "/docs/user-guide/pods/multi-container.html" -- "/docs/tasks/configure-pod-container/communicate-containers-same-pod/" -- "/docs/tasks/configure-pod-container/communicate-containers-same-pod.html" content_template: templates/task --- diff --git a/content/zh/docs/tasks/administer-cluster/access-cluster-services.md b/content/zh/docs/tasks/administer-cluster/access-cluster-services.md index 2035d498b4..82253e0c32 100644 --- a/content/zh/docs/tasks/administer-cluster/access-cluster-services.md +++ b/content/zh/docs/tasks/administer-cluster/access-cluster-services.md @@ -1,9 +1,6 @@ --- title: 访问集群上运行的服务 -redirect_from: -- "/docs/user-guide/accessing-the-cluster/" -- "/docs/user-guide/accessing-the-cluster.html" content_template: templates/task --- diff --git a/content/zh/docs/tasks/configure-pod-container/assign-memory-resource.md b/content/zh/docs/tasks/configure-pod-container/assign-memory-resource.md new file mode 100644 index 0000000000..1a67f8afaa --- /dev/null +++ b/content/zh/docs/tasks/configure-pod-container/assign-memory-resource.md @@ -0,0 +1,539 @@ +--- +title: 为容器和 Pod 分配内存资源 +content_template: templates/task +weight: 10 +--- + + + +{{% capture overview %}} + + +此页面显示如何将内存 *请求* (request)和内存 *限制* (limit)分配给一个容器。我们保障容器拥有它请求数量的内存,但不允许使用超过限制数量的内存。 + +{{% /capture %}} + + +{{% capture prerequisites %}} + +{{< include "task-tutorial-prereqs.md" >}} {{< version-check >}} + + +您集群中的每个节点必须拥有至少 300 MiB 的内存。 + + +该页面上的一些步骤要求您在集群中运行 [metrics-server](https://github.com/kubernetes-incubator/metrics-server) 服务。如果您已经有在运行中的 metrics-server,则可以跳过这些步骤。 + + +如果您运行的是 Minikube,可以运行下面的命令启用 metrics-server: + +```shell +minikube addons enable metrics-server +``` + + +要查看 metrics-server 或资源指标 API (`metrics.k8s.io`) 是否已经运行,请运行以下命令: + +```shell +kubectl get apiservices +``` + + +如果资源指标 API 可用,则输出结果将包含对 `metrics.k8s.io` 的引用信息。 + +```shell +NAME +v1beta1.metrics.k8s.io +``` + +{{% /capture %}} + +{{% capture steps %}} + + +## 创建命名空间 + +创建一个命名空间,以便将本练习中创建的资源与集群的其余部分隔离。 + +```shell +kubectl create namespace mem-example +``` + + +## 指定内存请求和限制 + +要为容器指定内存请求,请在容器资源清单中包含 `resources:requests` 字段。 +同理,要指定内存限制,请包含 `resources:limits`。 + +在本练习中,您将创建一个拥有一个容器的 Pod。 +容器将会请求 100 MiB 内存,并且内存会被限制在 200 MiB 以内。 +这是 Pod 的配置文件: + +{{< codenew file="pods/resource/memory-request-limit.yaml" >}} + + +配置文件的 `args` 部分提供了容器启动时的参数。 +`"--vm-bytes", "150M"` 参数告知容器尝试分配 150 MiB 内存。 + +开始创建 Pod: + +```shell +kubectl apply -f https://k8s.io/examples/pods/resource/memory-request-limit.yaml --namespace=mem-example +``` + + +验证 Pod 中的容器是否已运行: + +```shell +kubectl get pod memory-demo --namespace=mem-example +``` + + +查看 Pod 相关的详细信息: + +```shell +kubectl get pod memory-demo --output=yaml --namespace=mem-example +``` + + +输出结果显示:该 Pod 中容器的内存请求为 100 MiB,内存限制为 200 MiB。 + +```yaml +... +resources: + limits: + memory: 200Mi + requests: + memory: 100Mi +... +``` + + +运行 `kubectl top` 命令,获取该 Pod 的指标数据: + +```shell +kubectl top pod memory-demo --namespace=mem-example +``` + + +输出结果显示:Pod 正在使用的内存大约为 162,900,000 字节,约为 150 MiB。 +这大于 Pod 请求的 100 MiB,但在 Pod 限制的 200 MiB之内。 + +``` +NAME CPU(cores) MEMORY(bytes) +memory-demo 162856960 +``` + + +删除 Pod: + +```shell +kubectl delete pod memory-demo --namespace=mem-example +``` + + +## 超过容器限制的内存 + +当节点拥有足够的可用内存时,容器可以使用其请求的内存。但是,容器不允许使用超过其限制的内存。 +如果容器分配的内存超过其限制,该容器会成为被终止的候选容器。如果容器继续消耗超出其限制的内存,则终止容器。 +如果终止的容器可以被重启,则 kubelet 会重新启动它,就像其他任何类型的运行时失败一样。 + + +在本练习中,您将创建一个 Pod,尝试分配超出其限制的内存。 +这是一个 Pod 的配置文件,其拥有一个容器,该容器的内存请求为 50 MiB,内存限制为 100 MiB: + +{{< codenew file="pods/resource/memory-request-limit-2.yaml" >}} + + +在配置文件的 `args` 部分中,您可以看到容器会尝试分配 250 MiB 内存,这远高于 100 MiB 的限制。 + +创建 Pod: + +```shell +kubectl apply -f https://k8s.io/examples/pods/resource/memory-request-limit-2.yaml --namespace=mem-example +``` + + +查看 Pod 相关的详细信息: + +```shell +kubectl get pod memory-demo-2 --namespace=mem-example +``` + +此时,容器可能正在运行或被杀死。重复前面的命令,直到容器被杀掉: + +```shell +NAME READY STATUS RESTARTS AGE +memory-demo-2 0/1 OOMKilled 1 24s +``` + + +获取容器更详细的状态信息: + +```shell +kubectl get pod memory-demo-2 --output=yaml --namespace=mem-example +``` + + +输出结果显示:由于内存溢出(OOM),容器已被杀掉: + +```shell +lastState: + terminated: + containerID: docker://65183c1877aaec2e8427bc95609cc52677a454b56fcb24340dbd22917c23b10f + exitCode: 137 + finishedAt: 2017-06-20T20:52:19Z + reason: OOMKilled + startedAt: null +``` + + +本练习中的容器可以被重启,所以 kubelet 会重启它。多次运行下面的命令,可以看到容器在反复的被杀死和重启: + +```shell +kubectl get pod memory-demo-2 --namespace=mem-example +``` + + +输出结果显示:容器被杀掉、重启、再杀掉、再重启……: + +``` +kubectl get pod memory-demo-2 --namespace=mem-example +NAME READY STATUS RESTARTS AGE +memory-demo-2 0/1 OOMKilled 1 37s +``` +``` + +kubectl get pod memory-demo-2 --namespace=mem-example +NAME READY STATUS RESTARTS AGE +memory-demo-2 1/1 Running 2 40s +``` + + +查看关于该 Pod 历史的详细信息: + +``` +kubectl describe pod memory-demo-2 --namespace=mem-example +``` + + +输出结果显示:该容器反复的在启动和失败: + +``` +... Normal Created Created container with id 66a3a20aa7980e61be4922780bf9d24d1a1d8b7395c09861225b0eba1b1f8511 +... Warning BackOff Back-off restarting failed container +``` + + +查看关于集群节点的详细信息: + +``` +kubectl describe nodes +``` + + +输出结果包含了一条练习中的容器由于内存溢出而被杀掉的记录: + +``` +Warning OOMKilling Memory cgroup out of memory: Kill process 4481 (stress) score 1994 or sacrifice child +``` + + +删除 Pod: + +```shell +kubectl delete pod memory-demo-2 --namespace=mem-example +``` + + +## 超过整个节点容量的内存 + +内存请求和限制是与容器关联的,但将 Pod 视为具有内存请求和限制,也是很有用的。 +Pod 的内存请求是 Pod 中所有容器的内存请求之和。 +同理,Pod 的内存限制是 Pod 中所有容器的内存限制之和。 + + +Pod 的调度基于请求。只有当节点拥有足够满足 Pod 内存请求的内存时,才会将 Pod 调度至节点上运行。 + +在本练习中,你将创建一个 Pod,其内存请求超过了您集群中的任意一个节点所拥有的内存。 +这是该 Pod 的配置文件,其拥有一个请求 1000 GiB 内存的容器,这应该超过了您集群中任何节点的容量。 + +{{< codenew file="pods/resource/memory-request-limit-3.yaml" >}} + + +创建 Pod: + +```shell +kubectl apply -f https://k8s.io/examples/pods/resource/memory-request-limit-3.yaml --namespace=mem-example +``` + + +查看 Pod 状态: + +```shell +kubectl get pod memory-demo-3 --namespace=mem-example +``` + + +输出结果显示:Pod 处于 PENDING 状态。这意味着,该 Pod 没有被调度至任何节点上运行,并且它会无限期的保持该状态: + +``` +kubectl get pod memory-demo-3 --namespace=mem-example +NAME READY STATUS RESTARTS AGE +memory-demo-3 0/1 Pending 0 25s +``` + + +查看关于 Pod 的详细信息,包括事件: + + +```shell +kubectl describe pod memory-demo-3 --namespace=mem-example +``` + + +输出结果显示:由于节点内存不足,该容器无法被调度: + +```shell +Events: + ... Reason Message + ------ ------- + ... FailedScheduling No nodes are available that match all of the following predicates:: Insufficient memory (3). +``` + + +## 内存单位 + +内存资源的基本单位是字节(byte)。您可以使用这些后缀之一,将内存表示为纯整数或定点整数:E、P、T、G、M、K、Ei、Pi、Ti、Gi、Mi、Ki。例如,下面是一些近似相同的值: + +```shell +128974848, 129e6, 129M , 123Mi +``` + + +删除 Pod: + +```shell +kubectl delete pod memory-demo-3 --namespace=mem-example +``` + + +## 如果你没有指定内存限制 + +如果你没有为一个容器指定内存限制,则自动遵循以下情况之一: + + +* 容器可无限制地使用内存。容器可以使用其所在节点所有的可用内存,进而可能导致该节点调用 OOM Killer。 +此外,如果发生 OOM Kill,没有资源限制的容器将被杀掉的可行性更大。 + +* 运行的容器所在命名空间有默认的内存限制,那么该容器会被自动分配默认限制。 +集群管理员可用使用 [LimitRange](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#limitrange-v1-core) +来指定默认的内存限制。 + + +## 内存请求和限制的目的 + +通过为集群中运行的容器配置内存请求和限制,您可以有效利用集群节点上可用的内存资源。通过将 Pod 的内存请求保持在较低水平,您可以更好地安排 Pod 调度。通过让内存限制大于内存请求,您可以完成两件事: + + +* Pod 可以进行一些突发活动,从而更好的利用可用内存。 +* Pod 在突发活动期间,可使用的内存被限制为合理的数量。 + + +## 清理 + +删除命名空间。下面的命令会删除你根据这个任务创建的所有 Pod: + +```shell +kubectl delete namespace mem-example +``` + +{{% /capture %}} + +{{% capture whatsnext %}} + +### 应用开发者扩展阅读 + +* [为容器和 Pod 分配 CPU 资源](/docs/tasks/configure-pod-container/assign-cpu-resource/) + +* [配置 Pod 的服务质量](/docs/tasks/configure-pod-container/quality-service-pod/) + +### 集群管理员扩展阅读 + +* [为命名空间配置默认的内存请求和限制](/docs/tasks/administer-cluster/memory-default-namespace/) + +* [为命名空间配置默认的 CPU 请求和限制](/docs/tasks/administer-cluster/cpu-default-namespace/) + +* [配置命名空间的最小和最大内存约束](/docs/tasks/administer-cluster/memory-constraint-namespace/) + +* [配置命名空间的最小和最大 CPU 约束](/docs/tasks/administer-cluster/cpu-constraint-namespace/) + +* [为命名空间配置内存和 CPU 配额](/docs/tasks/administer-cluster/quota-memory-cpu-namespace/) + +* [配置命名空间下 Pod 总数](/docs/tasks/administer-cluster/quota-pod-namespace/) + +* [配置 API 对象配额](/docs/tasks/administer-cluster/quota-api-object/) + +{{% /capture %}} + + + diff --git a/content/zh/docs/tasks/configure-pod-container/configure-pod-configmap.md b/content/zh/docs/tasks/configure-pod-container/configure-pod-configmap.md index 1d4dce70ce..a5cdbea9d8 100644 --- a/content/zh/docs/tasks/configure-pod-container/configure-pod-configmap.md +++ b/content/zh/docs/tasks/configure-pod-container/configure-pod-configmap.md @@ -73,10 +73,6 @@ For example: --> 你可以使用 `kubectl create configmap` 从同一目录中的多个文件创建 ConfigMap。 例如: - -# Create the local directory -# Download the sample files into `configure-pod-container/configmap/` directory -# Create the configmap ```shell # 创建本地目录 mkdir -p configure-pod-container/configmap/ @@ -242,7 +238,7 @@ allowed="true" --> # env 文件中的每一行必须为 VAR = VAL 格式。 # 以#开头的行(即注释)将被忽略。 # 空行将被忽略。 -# 引号没有特殊处理(即它们将成为 ConfigMap 值的一部分)。 +# 引号没有特殊处理(即它们将成为 ConfigMap 值的一部分)。 # 将样本文件下载到 `configure-pod-container/configmap/` 目录 wget https://kubernetes.io/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties @@ -527,16 +523,6 @@ configmap/game-config-5-m67dt67794 created 要从文字 `special.type=charm` 和 `special.how=very` 生成 ConfigMap,可以在 `kusotmization.yaml` 中将 ConfigMap 生成器指定。 - ```shell # 使用 ConfigMapGenerator 创建 kustomization.yaml 文件 cat <./kustomization.yaml diff --git a/content/zh/docs/tasks/configure-pod-container/configure-runasusername.md b/content/zh/docs/tasks/configure-pod-container/configure-runasusername.md new file mode 100644 index 0000000000..65a9e88cb5 --- /dev/null +++ b/content/zh/docs/tasks/configure-pod-container/configure-runasusername.md @@ -0,0 +1,234 @@ +--- +title: 为 Windows 的 pod 和容器配置 RunAsUserName +content_template: templates/task +weight: 20 +--- + + + +{{% capture overview %}} + +{{< feature-state for_k8s_version="v1.17" state="beta" >}} + + + +本页展示如何为运行在 Windows 节点上的 pod 和容器启用并使用 `RunAsUserName` 功能。此功能旨在成为 Windows 版的 `runAsUser`(Linux),允许用户使用与默认用户名不同的用户名运行容器 entrypoint。 + +{{< note >}} + +该功能目前处于 beta 状态。 `RunAsUserName` 的整体功能不会出现变更,但是关于用户名验证的部分可能会有所更改。 +{{< /note >}} + +{{% /capture %}} + +{{% capture prerequisites %}} + + + +你必须有一个 Kubernetes 集群,并且 kubectl 必须能和集群通信。集群应该要有 Windows 工作节点,将在其中调度运行 Windows 工作负载的 pod 和容器。 + + + +## 为 Pod 设置 Username + +要指定运行 Pod 容器时所使用的用户名,请在 Pod 声明中包含 `securityContext` ([PodSecurityContext](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#podsecuritycontext-v1-core))字段,并在其内部包含 `windowsOptions` ([WindowsSecurityContextOptions](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#windowssecuritycontextoptions-v1-core))字段的 `runAsUserName` 字段。 + + + +您为 Pod 指定的 Windows SecurityContext 选项适用于该 Pod 中(包括 init 容器)的所有容器。 + +这儿有一个已经设置了 `runAsUserName` 字段的 Windows Pod 的配置文件: + +{{< codenew file="windows/run-as-username-pod.yaml" >}} + + + +创建 Pod: + +```shell +kubectl apply -f https://k8s.io/examples/windows/run-as-username-pod.yaml +``` + + + +验证 Pod 容器是否在运行: + +```shell +kubectl get pod run-as-username-pod-demo +``` + + + +获取该容器的 shell: + +```shell +kubectl exec -it run-as-username-pod-demo -- powershell +``` + + + +检查运行 shell 的用户的用户名是否正确: + +```powershell +echo $env:USERNAME +``` + + + +输出结果应该是这样: + +```shell +ContainerUser +``` + + + +## 为容器设置 Username + +要指定运行容器时所使用的用户名,请在容器清单中包含 `securityContext` ([SecurityContext](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#securitycontext-v1-core))字段,并在其内部包含 `windowsOptions` ([WindowsSecurityContextOptions](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#windowssecuritycontextoptions-v1-core))字段的 `runAsUserName` 字段。 + + + +您为容器指定的 Windows SecurityContext 选项仅适用于该容器,并且它会覆盖 Pod 级别设置。 + +这儿有一个 Pod 的配置文件,其只有一个容器,并且在 Pod 级别和容器级别都设置了 `runAsUserName`: + +{{< codenew file="windows/run-as-username-container.yaml" >}} + + + +创建 Pod: + +```shell +kubectl apply -f https://k8s.io/examples/windows/run-as-username-container.yaml +``` + + + +验证 Pod 容器是否在运行: + +```shell +kubectl get pod run-as-username-container-demo +``` + + + +获取该容器的 shell: + +```shell +kubectl exec -it run-as-username-container-demo -- powershell +``` + + + +检查运行 shell 的用户的用户名是否正确(应该是容器级别设置的那个): + +```powershell +echo $env:USERNAME +``` + + + +输出结果应该是这样: + +```shell +ContainerAdministrator +``` + + + +## Windows Username 的局限性 + +想要使用此功能,在 `runAsUserName` 字段中设置的值必须是有效的用户名。它必须是 `DOMAIN\USER` 这种格式,其中 `DOMAIN\` 是可选的。Windows 用户名不区分大小写。此外,关于 `DOMAIN` 和 `USER` 还有一些限制: + + + +- `runAsUserName` 字段不能为空,并且不能包含控制字符(ASCII 值:`0x00-0x1F`、`0x7F`) +- `DOMAIN` 必须是 NetBios 名称或 DNS 名称,每种名称都有各自的局限性: + - NetBios 名称:最多 15 个字符,不能以 `.`(点)开头,并且不能包含以下字符:`\ / : * ? " < > |` + - DNS 名称:最多 255 个字符,只能包含字母、数字、点和中划线,并且不能以 `.`(点)或 `-`(中划线)开头和结尾。 +- `USER` 最多不超过 20 个字符,不能 **只** 包含点或空格,并且不能包含以下字符:`" / \ [ ] : ; | = , + * ? < > @` + + + +`runAsUserName` 字段接受的值的一些示例:`ContainerAdministrator`、`ContainerUser`、`NT AUTHORITY\NETWORK SERVICE`、`NT AUTHORITY\LOCAL SERVICE`。 + +关于这些限制的更多信息,可以查看[这里](https://support.microsoft.com/en-us/help/909264/naming-conventions-in-active-directory-for-computers-domains-sites-and)和[这里](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/new-localuser?view=powershell-5.1)。 + +{{% /capture %}} + +{{% capture whatsnext %}} + + + +* [Kubernetes 中调度 Windows 容器的指南](/docs/setup/production-environment/windows/user-guide-windows-containers/) +* [使用组托管服务帐户(GMSA)管理工作负载身份](/docs/setup/production-environment/windows/user-guide-windows-containers/#managing-workload-identity-with-group-managed-service-accounts) +* [Windows 下 pod 和容器的 GMSA 配置](/docs/tasks/configure-pod-container/configure-gmsa/) + +{{% /capture %}} diff --git a/content/zh/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information.md b/content/zh/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information.md index f00d36d457..e702a8dcf2 100644 --- a/content/zh/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information.md +++ b/content/zh/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information.md @@ -31,7 +31,7 @@ content_template: templates/task 在这个练习中,你将创建一个包含一个容器的pod。这是该pod的配置文件: -{{< codenew file="pods/inject/dapi-volume-resources.yaml" >}} +{{< codenew file="pods/inject/dapi-volume.yaml" >}} 在配置文件中,你可以看到Pod有一个`downwardAPI`类型的Volume,并且挂载到容器中的`/etc`。 @@ -148,7 +148,7 @@ drwxrwxrwt 3 root root 120 Dec 5 07:00 .. 前面的练习中,你将Pod字段保存到DownwardAPIVolumeFile中。接下来这个练习,你将存储容器字段。这里是包含一个容器的pod的配置文件: -{{< codenew file="pods/inject/dapi-volume.yaml" >}} +{{< codenew file="pods/inject/dapi-volume-resources.yaml" >}} 在这个配置文件中,你可以看到Pod有一个`downwardAPI`类型的Volume,并且挂载到容器的`/etc`目录。 diff --git a/content/zh/docs/tasks/manage-kubernetes-objects/imperative-config.md b/content/zh/docs/tasks/manage-kubernetes-objects/imperative-config.md index 29e4da5793..d001d4638a 100644 --- a/content/zh/docs/tasks/manage-kubernetes-objects/imperative-config.md +++ b/content/zh/docs/tasks/manage-kubernetes-objects/imperative-config.md @@ -249,11 +249,11 @@ Example label: ```yaml selector: matchLabels: - controller-selector: "extensions/v1beta1/deployment/nginx" + controller-selector: "apps/v1/deployment/nginx" template: metadata: labels: - controller-selector: "extensions/v1beta1/deployment/nginx" + controller-selector: "apps/v1/deployment/nginx" ``` {{% /capture %}} diff --git a/content/zh/docs/tasks/tools/install-minikube.md b/content/zh/docs/tasks/tools/install-minikube.md index 9c93d35cb5..db9657876d 100644 --- a/content/zh/docs/tasks/tools/install-minikube.md +++ b/content/zh/docs/tasks/tools/install-minikube.md @@ -1,7 +1,10 @@ --- -title: Install Minikube +title: 安装 Minikube content_template: templates/task weight: 20 +card: + name: tasks + weight: 10 --- {{% capture overview %}} -本页面讲述如何安装 Minikube。 +本页面讲述如何安装 [Minikube](/docs/tutorials/hello-minikube),该工具用于在您电脑中的虚拟机上运行一个单节点的 Kubernetes 集群。 + {{% /capture %}} {{% capture prerequisites %}} -您的计算机必须在 BIOS 中启用 VT-x 或 AMD-v 虚拟化。 +{{< tabs name="minikube_before_you_begin" >}} +{{% tab name="Linux" %}} + +若要检查您的 Linux 是否支持虚拟化技术,请运行下面的命令并验证输出结果是否不为空: + +``` +grep -E --color 'vmx|svm' /proc/cpuinfo +``` + +{{% /tab %}} + +{{% tab name="macOS" %}} + + + +若要检查您的 macOS 是否支持虚拟化技术,请运行下面的命令: + +``` +sysctl -a | grep -E --color 'machdep.cpu.features|VMX' +``` + + + +如果你在输出结果中看到了 `VMX` (应该会高亮显示)的字眼,说明您的电脑已启用 VT-x 特性。 + +{{% /tab %}} + +{{% tab name="Windows" %}} + + +若要检查您的 Windows8 及以上的系统是否支持虚拟化技术,请终端或者 cmd 中运行以下命令: + +``` +systeminfo +``` + + +如果您看到下面的输出,则表示该 Windows 支持虚拟化技术。 + +``` +Hyper-V Requirements: VM Monitor Mode Extensions: Yes + Virtualization Enabled In Firmware: Yes + Second Level Address Translation: Yes + Data Execution Prevention Available: Yes +``` + + + +如果您看到下面的输出,则表示您的操作系统已经安装了 Hypervisor,您可以跳过安装 Hypervisor 的步骤。 +``` +Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed. +``` + + +{{% /tab %}} +{{< /tabs >}} + {{% /capture %}} {{% capture steps %}} -## 安装 Hypervisor -如果还没有装过 hypervisor,以下是一些不错的选择: - - - +# 安装 minikube -* macOS:[VirtualBox](https://www.virtualbox.org/wiki/Downloads) 或者 -[VMware Fusion](https://www.vmware.com/products/fusion),或者 -[HyperKit](https://github.com/moby/hyperkit)。 -* Linux:[VirtualBox](https://www.virtualbox.org/wiki/Downloads) 或者 -[KVM](http://www.linux-kvm.org/)。 - - - {{< note >}} - - Minikube 也支持 `-\-vm-driver=none` 选项,该选项在主机而非 VM 上运行 Kubernetes 组件。 - 使用这个驱动程序需要 Docker 和 linux 环境,而不需要 hypervisor。 - - - - - {{< /note >}} - -* Windows:[VirtualBox](https://www.virtualbox.org/wiki/Downloads) 或者 -[Hyper-V](https://msdn.microsoft.com/en-us/virtualization/hyperv_on_windows/quick_start/walkthrough_install)。 - -## 安装 kubectl +{{< tabs name="tab_with_md" >}} +{{% tab name="Linux" %}} - -* 请参照 [安装与设置 kubectl](/docs/tasks/tools/install-kubectl/) 中的说明安装 kubectl。 +### 安装 kubectl -## 安装 Minikube +请确保你已正确安装 kubectl。您可以根据[安装并设置 kubectl](/docs/tasks/tools/install-kubectl/#install-kubectl-on-linux) 的说明来安装 kubectl。 + +### 安装 Hypervisor + +如果还没有装过 hypervisor,请选择以下方式之一进行安装: + -* 请参照[最新发行](https://github.com/kubernetes/minikube/releases)指导安装 Minikube。 +• [KVM](https://www.linux-kvm.org/),也使用了 QEMU +• [VirtualBox](https://www.virtualbox.org/wiki/Downloads) + + + +Minikube 还支持使用一个 `--vm-driver=none` 选项,让 Kubernetes 组件运行在主机中,而不是在 VM 中。 +使用这种驱动方式需要 [Docker](https://www.docker.com/products/docker-desktop) 和 Linux 环境,但不需要 hypervisor。 + +如果你在 Debian 系的 OS 中使用了 `none` 这种驱动方式,请使用 `.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`。 +使用超级用户权限(root 用户)运行 Podman 可以最好的确保容器具有足够的权限使用你操作系统上的所有特性。 + +{{< caution >}} + +`Podman` 驱动方式需要以 root 用户身份运行容器,因为普通用户帐户没有足够的权限使用容器运行可能需要的操作系统上的所有特性。 +{{< /caution >}} + + + +### 使用包安装 Minikube + +Minikube 有 *实验性* 的安装包。你可以在 Minikube 在 GitHub 上的 [releases](https://github.com/kubernetes/minikube/releases) 找到 Linux (AMD64) 的包。 + +根据您的 Linux 发行版选择安装合适的包。 + + + +### 直接下载并安装 Minikube + +如果你不想通过包安装,你也可以下载并使用一个单节点二进制文件。 + +```shell +curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 \ + && chmod +x minikube +``` + + +将 Minikube 可执行文件添加至 path: + +```shell +sudo mkdir -p /usr/local/bin/ +sudo install minikube /usr/local/bin/ +``` + + + +### 使用 Homebrew 安装 Minikube + +你还可以使用 Linux [Homebrew](https://docs.brew.sh/Homebrew-on-Linux) 安装 Minikube: + +```shell +brew install minikube +``` + +{{% /tab %}} +{{% tab name="macOS" %}} + + + +### 安装 kubectl + +请确保你已正确安装 kubectl。您可以根据[安装并设置 kubectl](/docs/tasks/tools/install-kubectl/#install-kubectl-on-linux) 的说明来安装 kubectl。 + + + +### 安装 Hypervisor + +如果你还没有安装 hypervisor,请选择以下方式之一进行安装: + +• [HyperKit](https://github.com/moby/hyperkit) + +• [VirtualBox](https://www.virtualbox.org/wiki/Downloads) + +• [VMware Fusion](https://www.vmware.com/products/fusion) + + + +### 安装 Minikube + +macOS 安装 Minikube 最简单的方法是使用 [Homebrew](https://brew.sh): + +```shell +brew install minikube +``` + + + +你也可以通过下载单节点二进制文件进行安装: + +```shell +curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-darwin-amd64 \ + && chmod +x minikube +``` + + + +这是一个简单的将 Minikube 可执行文件添加至 path 的方法: + +```shell +sudo mv minikube /usr/local/bin +``` + +{{% /tab %}} +{{% tab name="Windows" %}} + + + +### 安装 kubectl + +请确保你已正确安装 kubectl。您可以根据[安装并设置 kubectl](/docs/tasks/tools/install-kubectl/#install-kubectl-on-windows) 的说明来安装 kubectl。 + + + +### 安装 Hypervisor + +如果你还没有安装 hypervisor,请选择以下方式之一进行安装: + +• [Hyper-V](https://msdn.microsoft.com/en-us/virtualization/hyperv_on_windows/quick_start/walkthrough_install) + +• [VirtualBox](https://www.virtualbox.org/wiki/Downloads) + +{{< note >}} + +Hyper-V 可以运行在三个版本的 Windows 10 上:企业版、专业版和教育版(Enterprise, Professional, Education)。 +{{< /note >}} + + + +### 使用 Chocolatey 安装 Minikube + +Windows 安装 Minikube 最简单的方法是使用 [Chocolatey](https://chocolatey.org/) (以管理员身份运行): + +```shell +choco install minikube +``` + + + +完成 Minikube 的安装后,关闭当前 CLI 界面再重新打开。 +Minikube 应该已经自动添加至 path 中。 + + + +### 使用安装程序安装 Minikube + +在 Windows 上使用 [Windows Installer](https://docs.microsoft.com/en-us/windows/desktop/msi/windows-installer-portal) 手动安装 Minikube,下载并运行 [`minikube-installer.exe`](https://github.com/kubernetes/minikube/releases/latest/download/minikube-installer.exe) 即可。 + + + +### 直接下载并安装 Minikube + +想在 Windows 上手动安装 Minikube,下载 [`minikube-windows-amd64`](https://github.com/kubernetes/minikube/releases/latest) 并将其重命名为 `minikube.exe`,然后将其添加至 path 即可。 + +{{% /tab %}} +{{< /tabs >}} {{% /capture %}} {{% capture whatsnext %}} -* [使用 Minikube 在本地运行 Kubernetes](/docs/getting-started-guides/minikube/) +* [使用 Minikube 在本地运行 Kubernetes](/docs/setup/learning-environment/minikube/) + {{% /capture %}} + + + +## 安装确认 + +要确认 hypervisor 和 Minikube 均已成功安装,可以运行以下命令来启动本地 Kubernetes 集群: + +{{< note >}} + + +通过 `minikube start` 设置 `--vm-driver`。在下面提到 `` 的地方,用小写字母,输入你安装的 hypervisor 的名称。 +[指定 VM 驱动程序](https://kubernetes.io/docs/setup/learning-environment/minikube/#specifying-the-vm-driver) 列举了 `--vm-driver` 值的完整列表 + +{{< /note >}} + +```shell +minikube start --vm-driver= +``` + + + +一旦 `minikube start` 完成,你可以运行下面的命令来检查集群的状态: + +```shell +minikube status +``` + + + +如果你的集群正在运行,`minikube status` 的输出结果应该类似于这样: + +``` +host: Running +kubelet: Running +apiserver: Running +kubeconfig: Configured +``` + + + +在确认 Minikube 与 hypervisor 均正常工作后,您可以继续使用 Minikube 或停止集群。要停止集群,请运行: + +```shell +minikube stop +``` + + + +## 清理本地状态{#cleanup-local-state} + +如果您之前安装过 Minikube,并运行了: + +```shell +minikube start +``` + + + +并且 `minikube start` 返回了一个错误: +``` +machine does not exist +``` + + + +那么,你需要清理 minikube 的本地状态: +```shell +minikube delete +``` diff --git a/content/zh/docs/tutorials/services/source-ip.md b/content/zh/docs/tutorials/services/source-ip.md index f4369268ce..d8811a57ce 100644 --- a/content/zh/docs/tutorials/services/source-ip.md +++ b/content/zh/docs/tutorials/services/source-ip.md @@ -278,7 +278,7 @@ client_address=10.240.0.5 ``` -然而,如果你的集群运行在 Google Kubernetes Engine/GCE 上,设置 `service.spec.externalTrafficPolicy` 字段值为 `Local` 可以强制使*没有* endpoints 的节点把他们自己从负载均衡流量的可选节点名单中删除。这是通过故意使它们健康检查失败达到的。 +然而,如果你的集群运行在 Google Kubernetes Engine/GCE 上,可以通过设置 service.spec.externalTrafficPolicy 字段值为 Local ,故意导致健康检查失败来强制使没有 endpoints 的节点把自己从负载均衡流量的可选节点列表中删除。 用图表示: diff --git a/content/zh/docs/tutorials/stateful-application/basic-stateful-set.md b/content/zh/docs/tutorials/stateful-application/basic-stateful-set.md index b661ea9601..2586d8600a 100644 --- a/content/zh/docs/tutorials/stateful-application/basic-stateful-set.md +++ b/content/zh/docs/tutorials/stateful-application/basic-stateful-set.md @@ -1527,7 +1527,7 @@ storage configuration, and provisioning method, to ensure that all storage is reclaimed. --> -你需要删除本教程中用到的 PersistentVolumes 的持久化存储媒体。基于你的环境、存储配置和提供方式,按照必须的步骤保证回收所有的存储。 +你需要删除本教程中用到的 PersistentVolumes 的持久化存储介质。基于你的环境、存储配置和提供方式,按照必须的步骤保证回收所有的存储。 {{% /capture %}} diff --git a/data/tasks.yml b/data/tasks.yml index 71ca4c957d..4220e059cc 100644 --- a/data/tasks.yml +++ b/data/tasks.yml @@ -196,25 +196,6 @@ toc: - docs/tasks/administer-cluster/storage-object-in-use-protection.md - docs/tasks/administer-cluster/endpoint-slices.md -- title: Federation - Run an App on Multiple Clusters - landing_page: /docs/tasks/federation/set-up-cluster-federation-kubefed/ - section: - - docs/tasks/federation/federation-service-discovery.md - - docs/tasks/federation/set-up-cluster-federation-kubefed.md - - docs/tasks/federation/set-up-coredns-provider-federation.md - - docs/tasks/federation/set-up-placement-policies-federation.md - - docs/tasks/administer-federation/cluster.md - - docs/tasks/administer-federation/configmap.md - - docs/tasks/administer-federation/daemonset.md - - docs/tasks/administer-federation/deployment.md - - docs/tasks/administer-federation/events.md - - docs/tasks/administer-federation/hpa.md - - docs/tasks/administer-federation/ingress.md - - docs/tasks/administer-federation/job.md - - docs/tasks/administer-federation/namespaces.md - - docs/tasks/administer-federation/replicaset.md - - docs/tasks/administer-federation/secret.md - - title: Manage Cluster Daemons landing_page: /docs/tasks/manage-daemon/update-daemon-set/ section: diff --git a/data/tools.yml b/data/tools.yml index 53a9e5ef43..0f5a970d3c 100644 --- a/data/tools.yml +++ b/data/tools.yml @@ -9,11 +9,9 @@ toc: path: /docs/reference/kubectl/overview/ - title: Kubeadm path: /docs/getting-started-guides/kubeadm - - title: Kubefed - path: /docs/admin/federation/kubefed/ - title: Kubernetes Dashboard path: /docs/user-guide/ui/ - + - title: Third-Party Tools section: - docs/tools/kompose/index.md diff --git a/i18n/de.toml b/i18n/de.toml index ea0ad27f74..4155902ec7 100644 --- a/i18n/de.toml +++ b/i18n/de.toml @@ -195,3 +195,6 @@ other = "Veranstaltungskalender" # UI elements [ui_search_placeholder] other = "Suchen" + +[input_placeholder_email_address] +other = "E-Mail-Addresse" \ No newline at end of file diff --git a/i18n/fr.toml b/i18n/fr.toml index 2cf29aafda..13d2bade6e 100644 --- a/i18n/fr.toml +++ b/i18n/fr.toml @@ -134,3 +134,6 @@ other = "Calendrier" # UI elements [ui_search_placeholder] other = "Recherche" + +[input_placeholder_email_address] +other = "adresse email" \ No newline at end of file diff --git a/i18n/id.toml b/i18n/id.toml index 8406981b78..aa196a6758 100644 --- a/i18n/id.toml +++ b/i18n/id.toml @@ -137,3 +137,6 @@ other = "Kalender acara" # UI elements [ui_search_placeholder] other = "Cari" + +[input_placeholder_email_address] +other = "Alamat email" diff --git a/i18n/ko.toml b/i18n/ko.toml index 9e1ec12b46..02f9c7a720 100644 --- a/i18n/ko.toml +++ b/i18n/ko.toml @@ -193,3 +193,6 @@ other = "이벤트 캘린더" # UI elements [ui_search_placeholder] other = "검색하기" + +[input_placeholder_email_address] +other = "전자 우편 주소" diff --git a/i18n/ru.toml b/i18n/ru.toml index 19b8e21a1a..7a0e39b708 100644 --- a/i18n/ru.toml +++ b/i18n/ru.toml @@ -193,3 +193,6 @@ other = "Календарь событий" # UI elements [ui_search_placeholder] other = "Поиск" + +[input_placeholder_email_address] +other = "адрес электронной почты" \ No newline at end of file diff --git a/i18n/zh.toml b/i18n/zh.toml index 41a6f0c045..c42cb6c230 100644 --- a/i18n/zh.toml +++ b/i18n/zh.toml @@ -186,3 +186,6 @@ other = "警告:" [whatsnext_heading] other = "接下来" + +[input_placeholder_email_address] +other = "电子邮件地址" \ No newline at end of file diff --git a/layouts/blog/post.html b/layouts/blog/post.html index cd07c5395d..3d1afae8e2 100644 --- a/layouts/blog/post.html +++ b/layouts/blog/post.html @@ -1,3 +1,3 @@ -

    {{ .Date.Format site.Params.time_format_blog }}

    +

    {{ .Title }}

    {{ .Content }} diff --git a/layouts/partials/css.html b/layouts/partials/css.html index 520611ec8c..b4aadaed4f 100644 --- a/layouts/partials/css.html +++ b/layouts/partials/css.html @@ -25,6 +25,9 @@ {{- if eq .Params.class "gridPage" }} {{- end }} +{{- if eq .Params.class "training" }} + +{{- end }} {{- with .Params.css }} {{- $extraCss := split . "," }} {{- range $extraCss }} diff --git a/layouts/partials/footer.html b/layouts/partials/footer.html index e85366460f..dfedd412b0 100644 --- a/layouts/partials/footer.html +++ b/layouts/partials/footer.html @@ -2,7 +2,7 @@