Masterbtc/Kubernetes_documentation huggingface dataset:
# Kubernetes Self-Healing

Kubernetes Self-HealingKubernetes is designed with self-healing capabilities that help maintain the health and availability of workloads. It automatically replaces failed containers, reschedules workloads when nodes become unavailable, and ensures that the desired state of the system is maintained.Self-Healing capabilitiesContainer-level restarts: If a container inside a Pod fails, Kubernetes restarts it based on the restartPolicy.Replica replacement: If a Pod in a Deployment or StatefulSet fails, Kubernetes creates a replacement Pod to maintain the specified number of replicas. If a Pod fails that is part of a DaemonSet fails, the control plane creates a replacement Pod to run on the same node.Persistent storage recovery: If a node is running a Pod with a PersistentVolume (PV) attached, and the node fails, Kubernetes can reattach the volume to a new Pod on a different node.Load balancing for Services: If a Pod behind a Service fails, Kubernetes automatically removes it from the Service's endpoints to route traffic only to healthy Pods.Here are some of the key components that provide Kubernetes self-healing:kubelet: Ensures that containers are running, and restarts those that fail.ReplicaSet, StatefulSet and DaemonSet controller: Maintains the desired number of Pod replicas.PersistentVolume controller: Manages volume attachment and detachment for stateful workloads.ConsiderationsStorage Failures: If a persistent volume becomes unavailable, recovery steps may be required.Application Errors: Kubernetes can restart containers, but underlying application issues must be addressed separately.What's nextRead more about PodsLearn about Kubernetes ControllersExplore PersistentVolumesRead about node autoscaling. Node autoscaling also provides automatic healing if or when nodes fail in your cluster.
# Administer a Cluster

Administer a ClusterLearn common tasks for administering a cluster.Administration with kubeadmOverprovision Node Capacity For A ClusterMigrating from dockershimGenerate Certificates ManuallyManage Memory, CPU, and API ResourcesInstall a Network Policy ProviderAccess Clusters Using the Kubernetes APIAdvertise Extended Resources for a NodeAutoscale the DNS Service in a ClusterChange the Access Mode of a PersistentVolume to ReadWriteOncePodChange the default StorageClassSwitching from Polling to CRI Event-based Updates to Container StatusChange the Reclaim Policy of a PersistentVolumeCloud Controller Manager AdministrationConfigure a kubelet image credential providerConfigure Quotas for API ObjectsControl CPU Management Policies on the NodeControl Topology Management Policies on a nodeCustomizing DNS ServiceDebugging DNS ResolutionDeclare Network PolicyDeveloping Cloud Controller ManagerEnable Or Disable A Kubernetes APIEncrypting Confidential Data at RestDecrypt Confidential Data that is Already Encrypted at RestGuaranteed Scheduling For Critical Add-On PodsIP Masquerade Agent User GuideLimit Storage ConsumptionMigrate Replicated Control Plane To Use Cloud Controller ManagerOperating etcd clusters for KubernetesReserve Compute Resources for System DaemonsRunning Kubernetes Node Components as a Non-root UserSafely Drain a NodeSecuring a ClusterSet Kubelet Parameters Via A Configuration FileShare a Cluster with NamespacesUpgrade A ClusterUse Cascading Deletion in a ClusterUsing a KMS provider for data encryptionUsing CoreDNS for Service DiscoveryUsing NodeLocal DNSCache in Kubernetes ClustersUsing sysctls in a Kubernetes ClusterUtilizing the NUMA-aware Memory ManagerVerify Signed Kubernetes Artifacts
# Security For Windows Nodes

Security For Windows NodesThis page describes security considerations and best practices specific to the Windows operating system.Protection for Secret data on nodesOn Windows, data from Secrets are written out in clear text onto the node's local storage (as compared to using tmpfs / in-memory filesystems on Linux). As a cluster operator, you should take both of the following additional measures:Use file ACLs to secure the Secrets' file location.Apply volume-level encryption using BitLocker.Container usersRunAsUsername can be specified for Windows Pods or containers to execute the container processes as specific user. This is roughly equivalent to RunAsUser.Windows containers offer two default user accounts, ContainerUser and ContainerAdministrator. The differences between these two user accounts are covered in When to use ContainerAdmin and ContainerUser user accounts within Microsoft's Secure Windows containers documentation.Local users can be added to container images during the container build process.Note:Nano Server based images run as ContainerUser by defaultServer Core based images run as ContainerAdministrator by defaultWindows containers can also run as Active Directory identities by utilizing Group Managed Service AccountsPod-level security isolationLinux-specific pod security context mechanisms (such as SELinux, AppArmor, Seccomp, or custom POSIX capabilities) are not supported on Windows nodes.Privileged containers are not supported on Windows. Instead HostProcess containers can be used on Windows to perform many of the tasks performed by privileged containers on Linux.
# Authorization Resources

Authorization ResourcesLocalSubjectAccessReviewLocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace.SelfSubjectAccessReviewSelfSubjectAccessReview checks whether or the current user can perform an action.SelfSubjectRulesReviewSelfSubjectRulesReview enumerates the set of actions the current user can perform within a namespace.SubjectAccessReviewSubjectAccessReview checks whether or not a user or group can perform an action.ClusterRoleClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding.ClusterRoleBindingClusterRoleBinding references a ClusterRole, but not contain it.RoleRole is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding.RoleBindingRoleBinding references a role, but does not contain it.This page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.
# Submitting case studies

Submitting case studiesCase studies highlight how organizations are using Kubernetes to solve real-world problems. The Kubernetes marketing team and members of the CNCF collaborate with you on all case studies.Case studies require extensive review before they're approved.Submit a case studyHave a look at the source for the existing case studies.Refer to the case study guidelines and submit your request as outlined in the guidelines.
# Configure Certificate Rotation for the Kubelet

Configure Certificate Rotation for the KubeletThis page shows how to enable and configure certificate rotation for the kubelet.FEATURE STATE: Kubernetes v1.19 [stable]Before you beginKubernetes version 1.8.0 or later is requiredOverviewThe kubelet uses certificates for authenticating to the Kubernetes API. By default, these certificates are issued with one year expiration so that they do not need to be renewed too frequently.Kubernetes contains kubelet certificate rotation, that will automatically generate a new key and request a new certificate from the Kubernetes API as the current certificate approaches expiration. Once the new certificate is available, it will be used for authenticating connections to the Kubernetes API.Enabling client certificate rotationThe kubelet process accepts an argument --rotate-certificates that controls if the kubelet will automatically request a new certificate as the expiration of the certificate currently in use approaches.The kube-controller-manager process accepts an argument --cluster-signing-duration (--experimental-cluster-signing-duration prior to 1.19) that controls how long certificates will be issued for.Understanding the certificate rotation configurationWhen a kubelet starts up, if it is configured to bootstrap (using the --bootstrap-kubeconfig flag), it will use its initial certificate to connect to the Kubernetes API and issue a certificate signing request. You can view the status of certificate signing requests using:kubectl get csr Initially a certificate signing request from the kubelet on a node will have a status of Pending. If the certificate signing requests meets specific criteria, it will be auto approved by the controller manager, then it will have a status of Approved. Next, the controller manager will sign a certificate, issued for the duration specified by the --cluster-signing-duration parameter, and the signed certificate will be attached to the certificate signing request.The kubelet will retrieve the signed certificate from the Kubernetes API and write that to disk, in the location specified by --cert-dir. Then the kubelet will use the new certificate to connect to the Kubernetes API.As the expiration of the signed certificate approaches, the kubelet will automatically issue a new certificate signing request, using the Kubernetes API. This can happen at any point between 30% and 10% of the time remaining on the certificate. Again, the controller manager will automatically approve the certificate request and attach a signed certificate to the certificate signing request. The kubelet will retrieve the new signed certificate from the Kubernetes API and write that to disk. Then it will update the connections it has to the Kubernetes API to reconnect using the new certificate.
# Workload Resources

Workload ResourcesPodPod is a collection of containers that can run on a host.BindingBinding ties one object to another; for example, a pod is bound to a node by a scheduler.PodTemplatePodTemplate describes a template for creating copies of a predefined pod.ReplicationControllerReplicationController represents the configuration of a replication controller.ReplicaSetReplicaSet ensures that a specified number of pod replicas are running at any given time.DeploymentDeployment enables declarative updates for Pods and ReplicaSets.StatefulSetStatefulSet represents a set of pods with consistent identities.ControllerRevisionControllerRevision implements an immutable snapshot of state data.DaemonSetDaemonSet represents the configuration of a daemon set.JobJob represents the configuration of a single job.CronJobCronJob represents the configuration of a single cron job.HorizontalPodAutoscalerconfiguration of a horizontal pod autoscaler.HorizontalPodAutoscalerHorizontalPodAutoscaler is the configuration for a horizontal pod autoscaler, which automatically manages the replica count of any resource implementing the scale subresource based on the metrics specified.PriorityClassPriorityClass defines mapping from a priority class name to the priority integer value.DeviceTaintRule v1alpha3DeviceTaintRule adds one taint to all devices which match the selector.ResourceClaimResourceClaim describes a request for access to resources in the cluster, for use by workloads.ResourceClaimTemplateResourceClaimTemplate is used to produce ResourceClaim objects.ResourceSliceResourceSlice represents one or more resources in a pool of similar resources, managed by a common driver.This page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.
# CSI Volume Cloning

CSI Volume CloningThis document describes the concept of cloning existing CSI Volumes in Kubernetes. Familiarity with Volumes is suggested.IntroductionThe CSI Volume Cloning feature adds support for specifying existing PVCs in the dataSource field to indicate a user would like to clone a Volume.A Clone is defined as a duplicate of an existing Kubernetes Volume that can be consumed as any standard Volume would be. The only difference is that upon provisioning, rather than creating a "new" empty Volume, the back end device creates an exact duplicate of the specified Volume.The implementation of cloning, from the perspective of the Kubernetes API, adds the ability to specify an existing PVC as a dataSource during new PVC creation. The source PVC must be bound and available (not in use).Users need to be aware of the following when using this feature:Cloning support (VolumePVCDataSource) is only available for CSI drivers.Cloning support is only available for dynamic provisioners.CSI drivers may or may not have implemented the volume cloning functionality.You can only clone a PVC when it exists in the same namespace as the destination PVC (source and destination must be in the same namespace).Cloning is supported with a different Storage Class.Destination volume can be the same or a different storage class as the source.Default storage class can be used and storageClassName omitted in the spec.Cloning can only be performed between two volumes that use the same VolumeMode setting (if you request a block mode volume, the source MUST also be block mode)ProvisioningClones are provisioned like any other PVC with the exception of adding a dataSource that references an existing PVC in the same namespace.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 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.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.UsageUpon availability of the new PVC, the cloned PVC is consumed the same as other PVC. It's also expected at this point that the newly created PVC is an independent object. It can be consumed, cloned, snapshotted, or deleted independently and without consideration for it's original dataSource PVC. This also implies that the source is not linked in any way to the newly created clone, it may also be modified or deleted without affecting the newly created clone.
# ObjectFieldSelector

ObjectFieldSelectorObjectFieldSelector selects an APIVersioned field of an object.import "k8s.io/api/core/v1"ObjectFieldSelector selects an APIVersioned field of an object.fieldPath (string), requiredPath of the field to select in the specified API version.apiVersion (string)Version of the schema the FieldPath is written in terms of, defaults to "v1".This page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.
# kubeadm alpha

kubeadm alphaCaution:kubeadm alpha provides a preview of a set of features made available for gathering
# Manage Memory, CPU, and API Resources

Manage Memory, CPU, and API ResourcesConfigure Default Memory Requests and Limits for a NamespaceDefine a default memory resource limit for a namespace, so that every new Pod in that namespace has a memory resource limit configured.Configure Default CPU Requests and Limits for a NamespaceDefine a default CPU resource limits for a namespace, so that every new Pod in that namespace has a CPU resource limit configured.Configure Minimum and Maximum Memory Constraints for a NamespaceDefine a range of valid memory resource limits for a namespace, so that every new Pod in that namespace falls within the range you configure.Configure Minimum and Maximum CPU Constraints for a NamespaceDefine a range of valid CPU resource limits for a namespace, so that every new Pod in that namespace falls within the range you configure.Configure Memory and CPU Quotas for a NamespaceDefine overall memory and CPU resource limits for a namespace.Configure a Pod Quota for a NamespaceRestrict how many Pods you can create within a namespace.
# Upgrading Windows nodes

Upgrading Windows nodesFEATURE STATE: Kubernetes v1.18 [beta]This page explains how to upgrade a Windows node created with kubeadm.Before you beginYou need to have shell access to all the nodes, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts.Your Kubernetes server must be at or later than version 1.17.To check the version, enter kubectl version.Familiarize yourself with the process for upgrading the rest of your kubeadm cluster. You will want to upgrade the control plane nodes before upgrading your Windows nodes.Upgrading worker nodesUpgrade kubeadmFrom the Windows node, upgrade kubeadm:# replace 1.34.0 with your desired version curl.exe -Lo <path-to-kubeadm.exe> "https://dl.k8s.io/v1.34.0/bin/windows/amd64/kubeadm.exe" Drain the nodeFrom a machine with access to the Kubernetes API, prepare the node for maintenance by marking it unschedulable and evicting the workloads:# replace <node-to-drain> with the name of your node you are draining kubectl drain <node-to-drain> --ignore-daemonsets You should see output similar to this:node/ip-172-31-85-18 cordoned node/ip-172-31-85-18 drained Upgrade the kubelet configurationFrom the Windows node, call the following command to sync new kubelet configuration:kubeadm upgrade node Upgrade kubelet and kube-proxyFrom the Windows node, upgrade and restart the kubelet:stop-service kubelet curl.exe -Lo <path-to-kubelet.exe> "https://dl.k8s.io/v1.34.0/bin/windows/amd64/kubelet.exe" restart-service kubelet From the Windows node, upgrade and restart the kube-proxy.stop-service kube-proxy curl.exe -Lo <path-to-kube-proxy.exe> "https://dl.k8s.io/v1.34.0/bin/windows/amd64/kube-proxy.exe" restart-service kube-proxy Note:If you are running kube-proxy in a HostProcess container within a Pod, and not as a Windows Service, you can upgrade kube-proxy by applying a newer version of your kube-proxy manifests.Uncordon the nodeFrom a machine with access to the Kubernetes API, bring the node back online by marking it schedulable:# replace <node-to-drain> with the name of your node kubectl uncordon <node-to-drain> What's nextSee how to Upgrade Linux nodes.
# Kubernetes Metrics (v1beta1)

Kubernetes Metrics (v1beta1)Package v1beta1 is the v1beta1 version of the metrics API.Resource TypesNodeMetricsNodeMetricsListPodMetricsPodMetricsListNodeMetricsAppears in:NodeMetricsListNodeMetrics sets resource usage metrics of a node.FieldDescriptionapiVersionstringmetrics.k8s.io/v1beta1kindstringNodeMetricsmetadatameta/v1.ObjectMetaStandard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadataRefer to the Kubernetes API documentation for the fields of the metadata field.timestamp [Required]meta/v1.TimeThe following fields define time interval from which metrics were collected from the interval [Timestamp-Window, Timestamp].window [Required]meta/v1.DurationNo description provided.usage [Required]core/v1.ResourceListThe memory usage is the memory working set.NodeMetricsListNodeMetricsList is a list of NodeMetrics.FieldDescriptionapiVersionstringmetrics.k8s.io/v1beta1kindstringNodeMetricsListmetadata [Required]meta/v1.ListMetaStandard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kindsitems [Required][]NodeMetricsList of node metrics.PodMetricsAppears in:PodMetricsListPodMetrics sets resource usage metrics of a pod.FieldDescriptionapiVersionstringmetrics.k8s.io/v1beta1kindstringPodMetricsmetadatameta/v1.ObjectMetaStandard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadataRefer to the Kubernetes API documentation for the fields of the metadata field.timestamp [Required]meta/v1.TimeThe following fields define time interval from which metrics were collected from the interval [Timestamp-Window, Timestamp].window [Required]meta/v1.DurationNo description provided.containers [Required][]ContainerMetricsMetrics for all containers are collected within the same time window.PodMetricsListPodMetricsList is a list of PodMetrics.FieldDescriptionapiVersionstringmetrics.k8s.io/v1beta1kindstringPodMetricsListmetadata [Required]meta/v1.ListMetaStandard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kindsitems [Required][]PodMetricsList of pod metrics.ContainerMetricsAppears in:PodMetricsContainerMetrics sets resource usage metrics of a container.FieldDescriptionname [Required]stringContainer name corresponding to the one from pod.spec.containers.usage [Required]core/v1.ResourceListThe memory usage is the memory working set.This page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.
# kubectl Usage Conventions

kubectl Usage ConventionsRecommended usage conventions for kubectl.Using kubectl in Reusable ScriptsFor a stable output in a script:Request one of the machine-oriented output forms, such as -o name, -o json, -o yaml, -o go-template, or -o jsonpath.Fully-qualify the version. For example, jobs.v1.batch/myjob. This will ensure that kubectl does not use its default version that can change over time.Don't rely on context, preferences, or other implicit states.SubresourcesYou can use the --subresource argument for kubectl subcommands such as get, patch, edit, apply and replace to fetch and update subresources for all resources that support them. In Kubernetes version 1.34, only the status, scale and resize subresources are supported.For kubectl edit, the scale subresource is not supported. If you use --subresource with kubectl edit and specify scale as the subresource, the command will error out.The API contract against a subresource is identical to a full resource. While updating the status subresource to a new value, keep in mind that the subresource could be potentially reconciled by a controller to a different value.Best Practiceskubectl runFor kubectl run to satisfy infrastructure as code:Tag the image with a version-specific tag and don't move that tag to a new version. For example, use :v1234, v1.2.3, r03062016-1-4, rather than :latest (For more information, see Best Practices for Configuration).Check in the script for an image that is heavily parameterized.Switch to configuration files checked into source control for features that are needed, but not expressible via kubectl run flags.You can use the --dry-run=client flag to preview the object that would be sent to your cluster, without really submitting it.kubectl applyYou can use kubectl apply to create or update resources. For more information about using kubectl apply to update resources, see Kubectl Book.
# Romana for NetworkPolicy

Romana for NetworkPolicyThis page shows how to use Romana for NetworkPolicy.Before you beginComplete steps 1, 2, and 3 of the kubeadm getting started guide.Installing Romana with kubeadmFollow the containerized installation guide for kubeadm.Applying network policiesTo apply network policies use one of the following:Romana network policies.Example of Romana network policy.The NetworkPolicy API.What's nextOnce you have installed Romana, you can follow the Declare Network Policy to try out Kubernetes NetworkPolicy.
# PR wranglers

PR wranglersSIG Docs approvers take week-long shifts managing pull requests for the repository.This section covers the duties of a PR wrangler. For more information on giving good reviews, see Reviewing changes.DutiesEach day in a week-long shift as PR Wrangler:Review open pull requests for quality and adherence to the Style and Content guides.Start with the smallest PRs (size/XS) first, and end with the largest (size/XXL). Review as many PRs as you can.Make sure PR contributors sign the CLA.Use this script to remind contributors that haven't signed the CLA to do so.Provide
# Opening a pull request

Opening a pull requestNote:Code developers: If you are documenting a new feature for an upcoming Kubernetes release, see Document a new feature.To contribute new content pages or improve existing content pages, open a pull request (PR). Make sure you follow all the requirements in the Before you begin section.If your change is small, or you're unfamiliar with git, read Changes using GitHub to learn how to edit a page.If your changes are large, read Work from a local fork to learn how to make changes locally on your computer.Changes using GitHubIf you're less experienced with git workflows, here's an easier method of opening a pull request. Figure 1 outlines the steps and the details follow.flowchart LR A([fa:fa-user NewContributor]) --- id1[(kubernetes/websiteGitHub)] subgraph tasks[Changes using GitHub] direction TB 0[ ] -.- 1[1.
# Configure Pods and Containers

Configure Pods and ContainersPerform common configuration tasks for Pods and containers.Assign Memory Resources to Containers and PodsAssign CPU Resources to Containers and PodsAssign Devices to Pods and ContainersAssign infrastructure resources to your Kubernetes workloads.Assign Pod-level CPU and memory resourcesConfigure GMSA for Windows Pods and containersResize CPU and Memory Resources assigned to ContainersConfigure RunAsUserName for Windows pods and containersCreate a Windows HostProcess PodConfigure Quality of Service for PodsAssign Extended Resources to a ContainerConfigure a Pod to Use a Volume for StorageConfigure a Pod to Use a PersistentVolume for StorageConfigure a Pod to Use a Projected Volume for StorageConfigure a Security Context for a Pod or ContainerConfigure Service Accounts for PodsPull an Image from a Private RegistryConfigure Liveness, Readiness and Startup ProbesAssign Pods to NodesAssign Pods to Nodes using Node AffinityConfigure Pod InitializationAttach Handlers to Container Lifecycle EventsConfigure a Pod to Use a ConfigMapShare Process Namespace between Containers in a PodUse a User Namespace With a PodUse an Image Volume With a PodCreate static PodsTranslate a Docker Compose File to Kubernetes ResourcesEnforce Pod Security Standards by Configuring the Built-in Admission ControllerEnforce Pod Security Standards with Namespace LabelsMigrate from PodSecurityPolicy to the Built-In PodSecurity Admission Controller
# Enforce Pod Security Standards with Namespace Labels

Enforce Pod Security Standards with Namespace LabelsNamespaces can be labeled to enforce the Pod Security Standards. The three policies privileged, baseline and restricted broadly cover the security spectrum and are implemented by the Pod Security admission controller.Before you beginPod Security Admission was available by default in Kubernetes v1.23, as a beta. From version 1.25 onwards, Pod Security Admission is generally available.To check the version, enter kubectl version.Requiring the baseline Pod Security Standard with namespace labelsThis manifest defines a Namespace my-baseline-namespace that:Blocks any pods that don't satisfy the baseline policy requirements.Generates a user-facing warning and adds an audit annotation to any created pod that does not meet the restricted policy requirements.Pins the versions of the baseline and restricted policies to v1.34.apiVersion: v1 kind: Namespace metadata: name: my-baseline-namespace labels: pod-security.kubernetes.io/enforce: baseline pod-security.kubernetes.io/enforce-version: v1.34 # We are setting these to our _desired_ `enforce` level. pod-security.kubernetes.io/audit: restricted pod-security.kubernetes.io/audit-version: v1.34 pod-security.kubernetes.io/warn: restricted pod-security.kubernetes.io/warn-version: v1.34 Add labels to existing namespaces with kubectl labelNote:When an enforce policy (or version) label is added or changed, the admission plugin will test each pod in the namespace against the new policy. Violations are returned to the user as warnings.It is helpful to apply the --dry-run flag when initially evaluating security profile changes for namespaces. The Pod Security Standard checks will still be run in dry run mode, giving you information about how the new policy would treat existing pods, without actually updating a policy.kubectl label --dry-run=server --overwrite ns --all \ pod-security.kubernetes.io/enforce=baseline Applying to all namespacesIf you're just getting started with the Pod Security Standards, a suitable first step would be to configure all namespaces with audit annotations for a stricter level such as baseline:kubectl label --overwrite ns --all \ pod-security.kubernetes.io/audit=baseline \ pod-security.kubernetes.io/warn=baseline Note that this is not setting an enforce level, so that namespaces that haven't been explicitly evaluated can be distinguished. You can list namespaces without an explicitly set enforce level using this command:kubectl get namespaces --selector='!pod-security.kubernetes.io/enforce' Applying to a single namespaceYou can update a specific namespace as well. This command adds the enforce=restricted policy to my-existing-namespace, pinning the restricted policy version to v1.34.kubectl label --overwrite ns my-existing-namespace \ pod-security.kubernetes.io/enforce=restricted \ pod-security.kubernetes.io/enforce-version=v1.34
# Service Internal Traffic Policy

Service Internal Traffic PolicyIf two Pods in your cluster want to communicate, and both Pods are actually running on the same node, use Service Internal Traffic Policy to keep network traffic within that node. Avoiding a round trip via the cluster network can help with reliability, performance (network latency and throughput), or cost.FEATURE STATE: Kubernetes v1.26 [stable]Service Internal Traffic Policy enables internal traffic restrictions to only route internal traffic to endpoints within the node the traffic originated from. The "internal" traffic here refers to traffic originated from Pods in the current cluster. This can help to reduce costs and improve performance.Using Service Internal Traffic PolicyYou can enable the internal-only traffic policy for a Service, by setting its .spec.internalTrafficPolicy to Local. This tells kube-proxy to only use node local endpoints for cluster internal traffic.Note:For pods on nodes with no endpoints for a given Service, the Service behaves as if it has zero endpoints (for Pods on this node) even if the service does have endpoints on other nodes.The following example shows what a Service looks like when you set .spec.internalTrafficPolicy to Local:apiVersion: v1 kind: Service metadata: name: my-service spec: selector: app.kubernetes.io/name: MyApp ports: - protocol: TCP port: 80 targetPort: 9376 internalTrafficPolicy: Local How it worksThe kube-proxy filters the endpoints it routes to based on the spec.internalTrafficPolicy setting. When it's set to Local, only node local endpoints are considered. When it's Cluster (the default), or is not set, Kubernetes considers all endpoints.What's nextRead about Topology Aware RoutingRead about Service External Traffic PolicyFollow the Connecting Applications with Services tutorial
# Ephemeral Containers

Ephemeral ContainersFEATURE STATE: Kubernetes v1.25 [stable]This page provides an overview of ephemeral containers: a special type of container that runs temporarily in an existing Pod to accomplish user-initiated actions such as troubleshooting. You use ephemeral containers to inspect services rather than to build applications.Understanding ephemeral containersPods are the fundamental building block of Kubernetes applications. Since Pods are intended to be disposable and replaceable, you cannot add a container to a Pod once it has been created. Instead, you usually delete and replace Pods in a controlled fashion using deployments.Sometimes it's necessary to inspect the state of an existing Pod, however, for example to troubleshoot a hard-to-reproduce bug. In these cases you can run an ephemeral container in an existing Pod to inspect its state and run arbitrary commands.What is an ephemeral container?Ephemeral containers differ from other containers in that they lack guarantees for resources or execution, and they will never be automatically restarted, so they are not appropriate for building applications. Ephemeral containers are described using the same ContainerSpec as regular containers, but many fields are incompatible and disallowed for ephemeral containers.Ephemeral containers may not have ports, so fields such as ports, livenessProbe, readinessProbe are disallowed.Pod resource allocations are immutable, so setting resources is disallowed.For a complete list of allowed fields, see the EphemeralContainer reference documentation.Ephemeral containers are created using a special ephemeralcontainers handler in the API rather than by adding them directly to pod.spec, so it's not possible to add an ephemeral container using kubectl edit.Like regular containers, you may not change or remove an ephemeral container after you have added it to a Pod.Note:Ephemeral containers are not supported by static pods.Uses for ephemeral containersEphemeral containers are useful for interactive troubleshooting when kubectl exec is insufficient because a container has crashed or a container image doesn't include debugging utilities.In particular, distroless images enable you to deploy minimal container images that reduce attack surface and exposure to bugs and vulnerabilities. Since distroless images do not include a shell or any debugging utilities, it's difficult to troubleshoot distroless images using kubectl exec alone.When using ephemeral containers, it's helpful to enable process namespace sharing so you can view processes in other containers.What's nextLearn how to debug pods using ephemeral containers.
# Node Labels Populated By The Kubelet

Node Labels Populated By The KubeletKubernetes nodes come pre-populated with a standard set of labels.You can also set your own labels on nodes, either through the kubelet configuration or using the Kubernetes API.Preset labelsThe preset labels that Kubernetes sets on nodes are:kubernetes.io/archkubernetes.io/hostnamekubernetes.io/osnode.kubernetes.io/instance-type (if known to the kubelet – Kubernetes may not have this information to set the label)topology.kubernetes.io/region (if known to the kubelet – Kubernetes may not have this information to set the label)topology.kubernetes.io/zone (if known to the kubelet – Kubernetes may not have this information to set the label)Note:The value of these labels is cloud provider specific and is not guaranteed to be reliable. For example, the value of kubernetes.io/hostname may be the same as the node name in some environments and a different value in other environments.What's nextSee Well-Known Labels, Annotations and Taints for a list of common labels.Learn how to add a label to a node.
# Use Calico for NetworkPolicy

Use Calico for NetworkPolicyThis page shows a couple of quick ways to create a Calico cluster on Kubernetes.Before you beginDecide whether you want to deploy a cloud or local cluster.Creating a Calico cluster with Google Kubernetes Engine (GKE)Prerequisite: gcloud.To launch a GKE cluster with Calico, include the --enable-network-policy flag.Syntaxgcloud container clusters create [CLUSTER_NAME] --enable-network-policy Examplegcloud container clusters create my-calico-cluster --enable-network-policy To verify the deployment, use the following command.kubectl get pods --namespace=kube-system The Calico pods begin with calico. Check to make sure each one has a status of Running.Creating a local Calico cluster with kubeadmTo get a local single-host Calico cluster in fifteen minutes using kubeadm, refer to the Calico Quickstart.What's nextOnce your cluster is running, you can follow the Declare Network Policy to try out Kubernetes NetworkPolicy.
# Bootstrapping clusters with kubeadm

Bootstrapping clusters with kubeadmInstalling kubeadmTroubleshooting kubeadmCreating a cluster with kubeadmCustomizing components with the kubeadm APIOptions for Highly Available TopologyCreating Highly Available Clusters with kubeadmSet up a High Availability etcd Cluster with kubeadmConfiguring each kubelet in your cluster using kubeadmDual-stack support with kubeadm
# Debug Init Containers

Debug Init ContainersThis page shows how to investigate problems related to the execution of Init Containers. The example command lines below refer to the Pod as <pod-name> and the Init Containers as <init-container-1> and <init-container-2>.Before you beginYou need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:iximiuz LabsKillercodaKodeKloudPlay with KubernetesTo check the version, enter kubectl version.You should be familiar with the basics of Init Containers.You should have Configured an Init Container.Checking the status of Init ContainersDisplay the status of your pod:kubectl get pod <pod-name> For example, a status of Init:1/2 indicates that one of two Init Containers has completed successfully:NAME READY STATUS RESTARTS AGE <pod-name> 0/1 Init:1/2 0 7s See Understanding Pod status for more examples of status values and their meanings.Getting details about Init ContainersView more detailed information about Init Container execution:kubectl describe pod <pod-name> For example, a Pod with two Init Containers might show the following:Init Containers: <init-container-1>: Container ID: ... ... State: Terminated Reason: Completed Exit Code: 0 Started: ... Finished: ... Ready: True Restart Count: 0 ... <init-container-2>: Container ID: ... ... State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Error Exit Code: 1 Started: ... Finished: ... Ready: False Restart Count: 3 ... You can also access the Init Container statuses programmatically by reading the status.initContainerStatuses field on the Pod Spec:kubectl get pod nginx --template '{{.status.initContainerStatuses}}' This command will return the same information as above in raw JSON.Accessing logs from Init ContainersPass the Init Container name along with the Pod name to access its logs.kubectl logs <pod-name> -c <init-container-2> Init Containers that run a shell script print commands as they're executed. For example, you can do this in Bash by running set -x at the beginning of the script.Understanding Pod statusA Pod status beginning with Init: summarizes the status of Init Container execution. The table below describes some example status values that you might see while debugging Init Containers.StatusMeaningInit:N/MThe Pod has M Init Containers, and N have completed so far.Init:ErrorAn Init Container has failed to execute.Init:CrashLoopBackOffAn Init Container has failed repeatedly.PendingThe Pod has not yet begun executing Init Containers.PodInitializing or RunningThe Pod has already finished executing Init Containers.
# Service

ServiceExpose an application running in your cluster behind a single outward-facing endpoint, even when the workload is split across multiple backends.In Kubernetes, a Service is a method for exposing a network application that is running as one or more Pods in your cluster.A key aim of Services in Kubernetes is that you don't need to modify your existing application to use an unfamiliar service discovery mechanism. You can run code in Pods, whether this is a code designed for a cloud-native world, or an older app you've containerized. You use a Service to make that set of Pods available on the network so that clients can interact with it.If you use a Deployment to run your app, that Deployment can create and destroy Pods dynamically. From one moment to the
# Configure DNS for a Cluster

Configure DNS for a ClusterKubernetes offers a DNS cluster addon, which most of the supported environments enable by default. In Kubernetes version 1.11 and later, CoreDNS is recommended and is installed by default with kubeadm.For more information on how to configure CoreDNS for a Kubernetes cluster, see the Customizing DNS Service. An example demonstrating how to use Kubernetes DNS with kube-dns, see the Kubernetes DNS sample plugin.
# NodeSelectorRequirement

NodeSelectorRequirementA node selector requirement is a selector that contains values, a key, and an operator that relates the key and values.import "k8s.io/api/core/v1"A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values.key (string), requiredThe label key that the selector applies to.operator (string), requiredRepresents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt.values ([]string)Atomic: will be replaced during a mergeAn array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch.This page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.
# Coordinated Leader Election

Coordinated Leader ElectionFEATURE STATE: Kubernetes v1.33 [beta] (enabled by default: false)Kubernetes 1.34 includes a beta feature that allows control plane components to deterministically select a leader via coordinated leader election. This is useful to satisfy Kubernetes version skew constraints during cluster upgrades. Currently, the only builtin selection strategy is OldestEmulationVersion, preferring the leader with the lowest emulation version, followed by binary version, followed by creation timestamp.Enabling coordinated leader electionEnsure that CoordinatedLeaderElection feature gate is enabled when you start the API Server: and that the coordination.k8s.io/v1beta1 API group is enabled.This can be done by setting flags --feature-gates="CoordinatedLeaderElection=true" and --runtime-config="coordination.k8s.io/v1beta1=true".Component configurationProvided that you have enabled the CoordinatedLeaderElection feature gate andhave the coordination.k8s.io/v1beta1 API group enabled, compatible control planecomponents automatically use the LeaseCandidate and Lease APIs to elect a leaderas needed.For Kubernetes 1.34, two control plane components(kube-controller-manager and kube-scheduler) automatically use coordinatedleader election when the feature gate and API group are enabled.
# Configure a Pod to Use a Projected Volume for Storage

Configure a Pod to Use a Projected Volume for StorageThis page shows how to use a projected Volume to mount several existing volume sources into the same directory. Currently, secret, configMap, downwardAPI, and serviceAccountToken volumes can be projected.Note:serviceAccountToken is not a volume type.Before you beginYou need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:iximiuz LabsKillercodaKodeKloudPlay with KubernetesTo check the version, enter kubectl version.Configure a projected volume for a podIn this exercise, you create username and password Secrets from local files. You then create a Pod that runs one container, using a projected Volume to mount the Secrets into the same shared directory.Here is the configuration file for the Pod:pods/storage/projected.yaml apiVersion: v1 kind: Pod metadata: name: test-projected-volume spec: containers: - name: test-projected-volume image: busybox:1.28 args: - sleep - "86400" volumeMounts: - name: all-in-one mountPath: "/projected-volume" readOnly: true volumes: - name: all-in-one projected: sources: - secret: name: user - secret: name: pass Create the Secrets:# Create files containing the username and password: echo -n "admin" > ./username.txt echo -n "1f2d1e2e67df" > ./password.txt # Package these files into secrets: kubectl create secret generic user --from-file=./username.txt kubectl create secret generic pass --from-file=./password.txt Create the Pod:kubectl apply -f https://k8s.io/examples/pods/storage/projected.yaml Verify that the Pod's container is running, and then watch for changes to the Pod:kubectl get --watch pod test-projected-volume The output looks like this:NAME READY STATUS RESTARTS AGE test-projected-volume 1/1 Running 0 14s In another terminal, get a shell to the running container:kubectl exec -it test-projected-volume -- /bin/sh In your shell, verify that the projected-volume directory contains your projected sources:ls /projected-volume/ Clean upDelete the Pod and the Secrets:kubectl delete pod test-projected-volume kubectl delete secret user pass What's nextLearn more about projected volumes.Read the all-in-one volume design document.
# Available Documentation Versions

Available Documentation VersionsThis website contains documentation for the current version of Kubernetes and the four previous versions of Kubernetes.The availability of documentation for a Kubernetes version is separate from whether that release is currently supported. Read Support period to learn about which versions of Kubernetes are officially supported, and for how long.Latest versionv1.34 (this documentation)Older versionsv1.33v1.32v1.31v1.30