Merge branch 'kubernetes:main' into patch-1

This commit is contained in:
Gwenaël Gallon
2022-03-30 14:30:40 +02:00
committed by GitHub
142 changed files with 4999 additions and 2231 deletions
@@ -13,7 +13,7 @@ allows the clean up of resources like the following:
* [Objects without owner references](#owners-dependents)
* [Unused containers and container images](#containers-images)
* [Dynamically provisioned PersistentVolumes with a StorageClass reclaim policy of Delete](/docs/concepts/storage/persistent-volumes/#delete)
* [Stale or expired CertificateSigningRequests (CSRs)](/reference/access-authn-authz/certificate-signing-requests/#request-signing-process)
* [Stale or expired CertificateSigningRequests (CSRs)](/docs/reference/access-authn-authz/certificate-signing-requests/#request-signing-process)
* {{<glossary_tooltip text="Nodes" term_id="node">}} deleted in the following scenarios:
* On a cloud when the cluster uses a [cloud controller manager](/docs/concepts/architecture/cloud-controller/)
* On-premises when the cluster uses an addon similar to a cloud controller
@@ -134,7 +134,7 @@ Mi, Ki. For example, the following represent roughly the same value:
128974848, 129e6, 129M, 128974848000m, 123Mi
```
Take care about case for suffixes. If you request `400m` of memory, this is a request
Pay attention to the case of the suffixes. If you request `400m` of memory, this is a request
for 0.4 bytes. Someone who types that probably meant to ask for 400 mebibytes (`400Mi`)
or 400 megabytes (`400M`).
@@ -33,7 +33,7 @@ specific Pods:
## Node labels {#built-in-node-labels}
Like many other Kubernetes objects, nodes have
[labels](/docs/concepts/overview/working-with-objects/labels/). You can [attach labels manually](/docs/tasks/confiure-pod-container/assign-pods-nodes/#add-a-label-to-a-node).
[labels](/docs/concepts/overview/working-with-objects/labels/). You can [attach labels manually](/docs/tasks/configure-pod-container/assign-pods-nodes/#add-a-label-to-a-node).
Kubernetes also populates a standard set of labels on all nodes in a cluster. See [Well-Known Labels, Annotations and Taints](/docs/reference/labels-annotations-taints/)
for a list of common node labels.
@@ -72,7 +72,7 @@ spec:
runtimeClassName: kata-fc
containers:
- name: busybox-ctr
image: busybox
image: busybox:1.28
stdin: true
tty: true
resources:
@@ -125,7 +125,7 @@ spec:
image: nginx:11.14.2
ports:
- containerPort: 80
name: http-web-service
name: http-web-svc
---
apiVersion: v1
@@ -139,7 +139,7 @@ spec:
- name: name-of-service-port
protocol: TCP
port: 80
targetPort: http-web-service
targetPort: http-web-svc
```
@@ -107,7 +107,7 @@ metadata:
spec:
containers:
- name: my-frontend
image: busybox
image: busybox:1.28
volumeMounts:
- mountPath: "/data"
name: my-csi-inline-vol
@@ -125,9 +125,17 @@ driver. These attributes are specific to each driver and not
standardized. See the documentation of each CSI driver for further
instructions.
### CSI driver restrictions
{{< feature-state for_k8s_version="v1.21" state="deprecated" >}}
As a cluster administrator, you can use a [PodSecurityPolicy](/docs/concepts/policy/pod-security-policy/) to control which CSI drivers can be used in a Pod, specified with the
[`allowedCSIDrivers` field](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#podsecuritypolicyspec-v1beta1-policy).
{{< note >}}
PodSecurityPolicy is deprecated and will be removed in the Kubernetes v1.25 release.
{{< /note >}}
### Generic ephemeral volumes
{{< feature-state for_k8s_version="v1.23" state="stable" >}}
@@ -158,7 +166,7 @@ metadata:
spec:
containers:
- name: my-frontend
image: busybox
image: busybox:1.28
volumeMounts:
- mountPath: "/scratch"
name: scratch-volume
@@ -23,7 +23,7 @@ Currently, the following types of volume sources can be projected:
* [`secret`](/docs/concepts/storage/volumes/#secret)
* [`downwardAPI`](/docs/concepts/storage/volumes/#downwardapi)
* [`configMap`](/docs/concepts/storage/volumes/#configmap)
* `serviceAccountToken`
* [`serviceAccountToken`](#serviceaccounttoken)
All sources are required to be in the same namespace as the Pod. For more details,
see the [all-in-one volume](https://github.com/kubernetes/design-proposals-archive/blob/main/node/all-in-one-volume.md) design document.
@@ -45,6 +45,7 @@ parameters are nearly the same with two exceptions:
volume source. However, as illustrated above, you can explicitly set the `mode`
for each individual projection.
## serviceAccountToken projected volumes {#serviceaccounttoken}
When the `TokenRequestProjection` feature is enabled, you can inject the token
for the current [service account](/docs/reference/access-authn-authz/authentication/#service-account-tokens)
into a Pod at a specified path. For example:
@@ -52,8 +53,9 @@ into a Pod at a specified path. For example:
{{< codenew file="pods/storage/projected-service-account-token.yaml" >}}
The example Pod has a projected volume containing the injected service account
token. This token can be used by a Pod's containers to access the Kubernetes API
server. The `audience` field contains the intended audience of the
token. Containers in this Pod can use that token to access the Kubernetes API
server, authenticating with the identity of [the pod's ServiceAccount](/docs/tasks/configure-pod-container/configure-service-account/).
The `audience` field contains the intended audience of the
token. A recipient of the token must identify itself with an identifier specified
in the audience of the token, and otherwise should reject the token. This field
is optional and it defaults to the identifier of the API server.
+2 -2
View File
@@ -251,7 +251,7 @@ metadata:
spec:
containers:
- name: test
image: busybox
image: busybox:1.28
volumeMounts:
- name: config-vol
mountPath: /etc/config
@@ -1128,7 +1128,7 @@ spec:
fieldRef:
apiVersion: v1
fieldPath: metadata.name
image: busybox
image: busybox:1.28
command: [ "sh", "-c", "while [ true ]; do echo 'Hello'; sleep 10; done | tee -a /logs/hello.txt" ]
volumeMounts:
- name: workdir1
@@ -180,7 +180,7 @@ spec:
spec:
containers:
- name: hello
image: busybox
image: busybox:1.28
command: ['sh', '-c', 'echo "Hello, Kubernetes!" && sleep 3600']
restartPolicy: OnFailure
# The pod template ends here
@@ -121,7 +121,7 @@ token,user,uid,"group1,group2,group3"
When using bearer token authentication from an http client, the API
server expects an `Authorization` header with a value of `Bearer
THETOKEN`. The bearer token must be a character sequence that can be
<token>`. The bearer token must be a character sequence that can be
put in an HTTP header value using no more than the encoding and
quoting facilities of HTTP. For example: if the bearer token is
`31ada4fd-adec-460c-809a-9e56ceb75269` then it would appear in an HTTP
@@ -63,7 +63,8 @@ different Kubernetes components.
| `AllowInsecureBackendProxy` | `true` | Beta | 1.17 | |
| `AnyVolumeDataSource` | `false` | Alpha | 1.18 | |
| `AppArmor` | `true` | Beta | 1.4 | |
| `ControllerManagerLeaderMigration` | `false` | Alpha | 1.21 | |
| `ControllerManagerLeaderMigration` | `false` | Alpha | 1.21 | 1.21 |
| `ControllerManagerLeaderMigration` | `true` | Beta | 1.22 | |
| `CPUManager` | `false` | Alpha | 1.8 | 1.9 |
| `CPUManager` | `true` | Beta | 1.10 | |
| `CPUManagerPolicyAlphaOptions` | `false` | Alpha | 1.23 | |
@@ -74,7 +75,7 @@ different Kubernetes components.
| `CSIInlineVolume` | `true` | Beta | 1.16 | - |
| `CSIMigration` | `false` | Alpha | 1.14 | 1.16 |
| `CSIMigration` | `true` | Beta | 1.17 | |
| `CSIMigrationAWS` | `false` | Alpha | 1.14 | |
| `CSIMigrationAWS` | `false` | Alpha | 1.14 | 1.16 |
| `CSIMigrationAWS` | `false` | Beta | 1.17 | 1.22 |
| `CSIMigrationAWS` | `true` | Beta | 1.23 | |
| `CSIMigrationAzureDisk` | `false` | Alpha | 1.15 | 1.18 |
@@ -579,39 +580,47 @@ Each feature gate is designed for enabling/disabling a specific feature:
See [AppArmor Tutorial](/docs/tutorials/security/apparmor/) for more details.
- `AttachVolumeLimit`: Enable volume plugins to report limits on number of volumes
that can be attached to a node.
See [dynamic volume limits](/docs/concepts/storage/storage-limits/#dynamic-volume-limits) for more details.
- `BalanceAttachedNodeVolumes`: Include volume count on node to be considered for balanced resource allocation
while scheduling. A node which has closer CPU, memory utilization, and volume count is favored by the scheduler
while making decisions.
See [dynamic volume limits](/docs/concepts/storage/storage-limits/#dynamic-volume-limits)
for more details.
- `BalanceAttachedNodeVolumes`: Include volume count on node to be considered for
balanced resource allocation while scheduling. A node which has closer CPU,
memory utilization, and volume count is favored by the scheduler while making decisions.
- `BlockVolume`: Enable the definition and consumption of raw block devices in Pods.
See [Raw Block Volume Support](/docs/concepts/storage/persistent-volumes/#raw-block-volume-support)
for more details.
- `BoundServiceAccountTokenVolume`: Migrate ServiceAccount volumes to use a projected volume consisting of a
ServiceAccountTokenVolumeProjection. Cluster admins can use metric `serviceaccount_stale_tokens_total` to
monitor workloads that are depending on the extended tokens. If there are no such workloads, turn off
extended tokens by starting `kube-apiserver` with flag `--service-account-extend-token-expiration=false`.
- `BoundServiceAccountTokenVolume`: Migrate ServiceAccount volumes to use a projected volume
consisting of a ServiceAccountTokenVolumeProjection. Cluster admins can use metric
`serviceaccount_stale_tokens_total` to monitor workloads that are depending on the extended
tokens. If there are no such workloads, turn off extended tokens by starting `kube-apiserver` with
flag `--service-account-extend-token-expiration=false`.
Check [Bound Service Account Tokens](https://github.com/kubernetes/enhancements/blob/master/keps/sig-auth/1205-bound-service-account-tokens/README.md)
for more details.
for more details.
- `ControllerManagerLeaderMigration`: Enables Leader Migration for
[kube-controller-manager](/docs/tasks/administer-cluster/controller-manager-leader-migration/#initial-leader-migration-configuration) and
[cloud-controller-manager](/docs/tasks/administer-cluster/controller-manager-leader-migration/#deploy-cloud-controller-manager) which allows a cluster operator to live migrate
[cloud-controller-manager](/docs/tasks/administer-cluster/controller-manager-leader-migration/#deploy-cloud-controller-manager)
which allows a cluster operator to live migrate
controllers from the kube-controller-manager into an external controller-manager
(e.g. the cloud-controller-manager) in an HA cluster without downtime.
- `CPUManager`: Enable container level CPU affinity support, see
[CPU Management Policies](/docs/tasks/administer-cluster/cpu-management-policies/).
- `CPUManagerPolicyAlphaOptions`: This allows fine-tuning of CPUManager policies, experimental, Alpha-quality options
- `CPUManagerPolicyAlphaOptions`: This allows fine-tuning of CPUManager policies,
experimental, Alpha-quality options
This feature gate guards *a group* of CPUManager options whose quality level is alpha.
This feature gate will never graduate to beta or stable.
- `CPUManagerPolicyBetaOptions`: This allows fine-tuning of CPUManager policies, experimental, Beta-quality options
- `CPUManagerPolicyBetaOptions`: This allows fine-tuning of CPUManager policies,
experimental, Beta-quality options
This feature gate guards *a group* of CPUManager options whose quality level is beta.
This feature gate will never graduate to stable.
- `CPUManagerPolicyOptions`: Allow fine-tuning of CPUManager policies.
- `CRIContainerLogRotation`: Enable container log rotation for CRI container runtime. The default max size of a log file is 10MB and the
default max number of log files allowed for a container is 5. These values can be configured in the kubelet config.
See the [logging at node level](/docs/concepts/cluster-administration/logging/#logging-at-the-node-level) documentation for more details.
- `CRIContainerLogRotation`: Enable container log rotation for CRI container runtime.
The default max size of a log file is 10MB and the default max number of
log files allowed for a container is 5.
These values can be configured in the kubelet config.
See [logging at node level](/docs/concepts/cluster-administration/logging/#logging-at-the-node-level)
for more details.
- `CSIBlockVolume`: Enable external CSI volume drivers to support block storage.
See the [`csi` raw block volume support](/docs/concepts/storage/volumes/#csi-raw-block-volume-support)
documentation for more details.
See [`csi` raw block volume support](/docs/concepts/storage/volumes/#csi-raw-block-volume-support)
for more details.
- `CSIDriverRegistry`: Enable all logic related to the CSIDriver API object in
csi.storage.k8s.io.
- `CSIInlineVolume`: Enable CSI Inline volumes support for pods.
@@ -643,7 +652,8 @@ Each feature gate is designed for enabling/disabling a specific feature:
AzureDisk CSI plugin. Requires CSIMigration and CSIMigrationAzureDisk feature
flags enabled and AzureDisk CSI plugin installed and configured on all nodes
in the cluster. This flag has been deprecated in favor of the
`InTreePluginAzureDiskUnregister` feature flag which prevents the registration of in-tree AzureDisk plugin.
`InTreePluginAzureDiskUnregister` feature flag which prevents the registration
of in-tree AzureDisk plugin.
- `CSIMigrationAzureFile`: Enables shims and translation logic to route volume
operations from the Azure-File in-tree plugin to AzureFile CSI plugin.
Supports falling back to in-tree AzureFile plugin for mount operations to
@@ -666,19 +676,13 @@ Each feature gate is designed for enabling/disabling a specific feature:
Does not support falling back for provision operations, for those the CSI
plugin must be installed and configured. Requires CSIMigration feature flag
enabled.
- `csiMigrationRBD`: Enables shims and translation logic to route volume
operations from the RBD in-tree plugin to Ceph RBD CSI plugin. Requires
CSIMigration and csiMigrationRBD feature flags enabled and Ceph CSI plugin
installed and configured in the cluster. This flag has been deprecated in
favor of the
`InTreePluginRBDUnregister` feature flag which prevents the registration of
in-tree RBD plugin.
- `CSIMigrationGCEComplete`: Stops registering the GCE-PD in-tree plugin in
kubelet and volume controllers and enables shims and translation logic to
route volume operations from the GCE-PD in-tree plugin to PD CSI plugin.
Requires CSIMigration and CSIMigrationGCE feature flags enabled and PD CSI
plugin installed and configured on all nodes in the cluster. This flag has
been deprecated in favor of the `InTreePluginGCEUnregister` feature flag which prevents the registration of in-tree GCE PD plugin.
been deprecated in favor of the `InTreePluginGCEUnregister` feature flag which
prevents the registration of in-tree GCE PD plugin.
- `CSIMigrationOpenStack`: Enables shims and translation logic to route volume
operations from the Cinder in-tree plugin to Cinder CSI plugin. Supports
falling back to in-tree Cinder plugin for mount operations to nodes that have
@@ -691,7 +695,14 @@ Each feature gate is designed for enabling/disabling a specific feature:
volume operations from the Cinder in-tree plugin to Cinder CSI plugin.
Requires CSIMigration and CSIMigrationOpenStack feature flags enabled and Cinder
CSI plugin installed and configured on all nodes in the cluster. This flag has
been deprecated in favor of the `InTreePluginOpenStackUnregister` feature flag which prevents the registration of in-tree openstack cinder plugin.
been deprecated in favor of the `InTreePluginOpenStackUnregister` feature flag
which prevents the registration of in-tree openstack cinder plugin.
- `csiMigrationRBD`: Enables shims and translation logic to route volume
operations from the RBD in-tree plugin to Ceph RBD CSI plugin. Requires
CSIMigration and csiMigrationRBD feature flags enabled and Ceph CSI plugin
installed and configured in the cluster. This flag has been deprecated in
favor of the `InTreePluginRBDUnregister` feature flag which prevents the registration of
in-tree RBD plugin.
- `CSIMigrationvSphere`: Enables shims and translation logic to route volume operations
from the vSphere in-tree plugin to vSphere CSI plugin. Supports falling back
to in-tree vSphere plugin for mount operations to nodes that have the feature
@@ -704,11 +715,12 @@ Each feature gate is designed for enabling/disabling a specific feature:
from the vSphere in-tree plugin to vSphere CSI plugin. Requires CSIMigration and
CSIMigrationvSphere feature flags enabled and vSphere CSI plugin installed and
configured on all nodes in the cluster. This flag has been deprecated in favor
of the `InTreePluginvSphereUnregister` feature flag which prevents the registration of in-tree vsphere plugin.
of the `InTreePluginvSphereUnregister` feature flag which prevents the
registration of in-tree vsphere plugin.
- `CSIMigrationPortworx`: Enables shims and translation logic to route volume operations
from the Portworx in-tree plugin to Portworx CSI plugin.
Requires Portworx CSI driver to be installed and configured in the cluster, and feature gate set `CSIMigrationPortworx=true` in kube-controller-manager and kubelet configs.
- `CSINodeInfo`: Enable all logic related to the CSINodeInfo API object in csi.storage.k8s.io.
Requires Portworx CSI driver to be installed and configured in the cluster.
- `CSINodeInfo`: Enable all logic related to the CSINodeInfo API object in `csi.storage.k8s.io`.
- `CSIPersistentVolume`: Enable discovering and mounting volumes provisioned through a
[CSI (Container Storage Interface)](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/storage/container-storage-interface.md)
compatible volume plugin.
@@ -736,7 +748,9 @@ Each feature gate is designed for enabling/disabling a specific feature:
version 1 of the same controller is selected.
- `CustomCPUCFSQuotaPeriod`: Enable nodes to change `cpuCFSQuotaPeriod` in
[kubelet config](/docs/tasks/administer-cluster/kubelet-config-file/).
- `CustomResourceValidationExpressions`: Enable expression language validation in CRD which will validate customer resource based on validation rules written in `x-kubernetes-validations` extension.
- `CustomResourceValidationExpressions`: Enable expression language validation in CRD
which will validate customer resource based on validation rules written in
the `x-kubernetes-validations` extension.
- `CustomPodDNS`: Enable customizing the DNS settings for a Pod using its `dnsConfig` property.
Check [Pod's DNS Config](/docs/concepts/services-networking/dns-pod-service/#pods-dns-config)
for more details.
@@ -819,7 +833,8 @@ Each feature gate is designed for enabling/disabling a specific feature:
host mounts, or containers that are privileged or using specific non-namespaced
capabilities (e.g. `MKNODE`, `SYS_MODULE` etc.). This should only be enabled
if user namespace remapping is enabled in the Docker daemon.
- `ExternalPolicyForExternalIP`: Fix a bug where ExternalTrafficPolicy is not applied to Service ExternalIPs.
- `ExternalPolicyForExternalIP`: Fix a bug where ExternalTrafficPolicy is not
applied to Service ExternalIPs.
- `GCERegionalPersistentDisk`: Enable the regional PD feature on GCE.
- `GenericEphemeralVolume`: Enables ephemeral, inline volumes that support all features
of normal volumes (can be provided by third-party storage vendors, storage capacity tracking,
@@ -832,8 +847,10 @@ Each feature gate is designed for enabling/disabling a specific feature:
for more details.
- `GracefulNodeShutdownBasedOnPodPriority`: Enables the kubelet to check Pod priorities
when shutting down a node gracefully.
- `GRPCContainerProbe`: Enables the gRPC probe method for {Liveness,Readiness,Startup}Probe. See [Configure Liveness, Readiness and Startup Probes](/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-grpc-liveness-probe).
- `HonorPVReclaimPolicy`: Honor persistent volume reclaim policy when it is `Delete` irrespective of PV-PVC deletion ordering.
- `GRPCContainerProbe`: Enables the gRPC probe method for {Liveness,Readiness,Startup}Probe.
See [Configure Liveness, Readiness and Startup Probes](/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-grpc-liveness-probe).
- `HonorPVReclaimPolicy`: Honor persistent volume reclaim policy when it is `Delete`
irrespective of PV-PVC deletion ordering.
- `HPAContainerMetrics`: Enable the `HorizontalPodAutoscaler` to scale based on
metrics from individual containers in target pods.
- `HPAScaleToZero`: Enables setting `minReplicas` to 0 for `HorizontalPodAutoscaler`
@@ -845,10 +862,19 @@ Each feature gate is designed for enabling/disabling a specific feature:
- `HyperVContainer`: Enable
[Hyper-V isolation](https://docs.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/hyperv-container)
for Windows containers.
- `IdentifyPodOS`: Allows the Pod OS field to be specified. This helps in identifying the OS of the pod
authoritatively during the API server admission time. In Kubernetes {{< skew currentVersion >}}, the allowed values for the `pod.spec.os.name` are `windows` and `linux`.
- `IdentifyPodOS`: Allows the Pod OS field to be specified. This helps in identifying
the OS of the pod authoritatively during the API server admission time.
In Kubernetes {{< skew currentVersion >}}, the allowed values for the `pod.spec.os.name`
are `windows` and `linux`.
- `ImmutableEphemeralVolumes`: Allows for marking individual Secrets and ConfigMaps as
immutable for better safety and performance.
- `IndexedJob`: Allows the [Job](/docs/concepts/workloads/controllers/job/)
controller to manage Pod completions per completion index.
- `IngressClassNamespacedParams`: Allow namespace-scoped parameters reference in
`IngressClass` resource. This feature adds two fields - `Scope` and `Namespace`
to `IngressClass.spec.parameters`.
- `Initializers`: Allow asynchronous coordination of object creation using the
Initializers admission plugin.
- `InTreePluginAWSUnregister`: Stops registering the aws-ebs in-tree plugin in kubelet
and volume controllers.
- `InTreePluginAzureDiskUnregister`: Stops registering the azuredisk in-tree plugin in kubelet
@@ -865,13 +891,6 @@ Each feature gate is designed for enabling/disabling a specific feature:
and volume controllers.
- `InTreePluginvSphereUnregister`: Stops registering the vSphere in-tree plugin in kubelet
and volume controllers.
- `IndexedJob`: Allows the [Job](/docs/concepts/workloads/controllers/job/)
controller to manage Pod completions per completion index.
- `IngressClassNamespacedParams`: Allow namespace-scoped parameters reference in
`IngressClass` resource. This feature adds two fields - `Scope` and `Namespace`
to `IngressClass.spec.parameters`.
- `Initializers`: Allow asynchronous coordination of object creation using the
Initializers admission plugin.
- `IPv6DualStack`: Enable [dual stack](/docs/concepts/services-networking/dual-stack/)
support for IPv6.
- `JobMutableNodeSchedulingDirectives`: Allows updating node scheduling directives in
@@ -889,17 +908,21 @@ Each feature gate is designed for enabling/disabling a specific feature:
a file specified using a config file.
See [setting kubelet parameters via a config file](/docs/tasks/administer-cluster/kubelet-config-file/)
for more details.
- `KubeletCredentialProviders`: Enable kubelet exec credential providers for image pull credentials.
- `KubeletInUserNamespace`: Enables support for running kubelet in a {{<glossary_tooltip text="user namespace" term_id="userns">}}.
- `KubeletCredentialProviders`: Enable kubelet exec credential providers for
image pull credentials.
- `KubeletInUserNamespace`: Enables support for running kubelet in a
{{<glossary_tooltip text="user namespace" term_id="userns">}}.
See [Running Kubernetes Node Components as a Non-root User](/docs/tasks/administer-cluster/kubelet-in-userns/).
- `KubeletPluginsWatcher`: Enable probe-based plugin watcher utility to enable kubelet
to discover plugins such as [CSI volume drivers](/docs/concepts/storage/volumes/#csi).
- `KubeletPodResources`: Enable the kubelet's pod resources gRPC endpoint. See
[Support Device Monitoring](https://github.com/kubernetes/enhancements/blob/master/keps/sig-node/606-compute-device-assignment/README.md)
for more details.
- `KubeletPodResourcesGetAllocatable`: Enable the kubelet's pod resources `GetAllocatableResources` functionality.
This API augments the [resource allocation reporting](/docs/concepts/extend-kubernetes/compute-storage-net/device-plugins/#monitoring-device-plugin-resources)
with informations about the allocatable resources, enabling clients to properly track the free compute resources on a node.
- `KubeletPodResourcesGetAllocatable`: Enable the kubelet's pod resources
`GetAllocatableResources` functionality. This API augments the
[resource allocation reporting](/docs/concepts/extend-kubernetes/compute-storage-net/device-plugins/#monitoring-device-plugin-resources)
with informations about the allocatable resources, enabling clients to properly
track the free compute resources on a node.
- `LegacyNodeRoleBehavior`: When disabled, legacy behavior in service load balancers and
node disruption will ignore the `node-role.kubernetes.io/master` label in favor of the
feature-specific labels provided by `NodeDisruptionExclusion` and `ServiceNodeExclusion`.
@@ -918,18 +941,22 @@ Each feature gate is designed for enabling/disabling a specific feature:
based on logarithmic bucketing of pod timestamps.
- `MemoryManager`: Allows setting memory affinity for a container based on
NUMA topology.
- `MemoryQoS`: Enable memory protection and usage throttle on pod / container using cgroup v2 memory controller.
- `MemoryQoS`: Enable memory protection and usage throttle on pod / container using
cgroup v2 memory controller.
- `MixedProtocolLBService`: Enable using different protocols in the same `LoadBalancer` type
Service instance.
- `MountContainers`: Enable using utility containers on host as the volume mounter.
- `MountPropagation`: Enable sharing volume mounted by one container to other containers or pods.
For more details, please see [mount propagation](/docs/concepts/storage/volumes/#mount-propagation).
- `NamespaceDefaultLabelName`: Configure the API Server to set an immutable {{< glossary_tooltip text="label" term_id="label" >}}
`kubernetes.io/metadata.name` on all namespaces, containing the namespace name.
- `NetworkPolicyEndPort`: Enable use of the field `endPort` in NetworkPolicy objects, allowing the selection of a port range instead of a single port.
- `NamespaceDefaultLabelName`: Configure the API Server to set an immutable
{{< glossary_tooltip text="label" term_id="label" >}} `kubernetes.io/metadata.name`
on all namespaces, containing the namespace name.
- `NetworkPolicyEndPort`: Enable use of the field `endPort` in NetworkPolicy objects,
allowing the selection of a port range instead of a single port.
- `NodeDisruptionExclusion`: Enable use of the Node label `node.kubernetes.io/exclude-disruption`
which prevents nodes from being evacuated during zone failures.
- `NodeLease`: Enable the new Lease API to report node heartbeats, which could be used as a node health signal.
- `NodeLease`: Enable the new Lease API to report node heartbeats, which could be used
as a node health signal.
- `NodeSwap`: Enable the kubelet to allocate swap memory for Kubernetes workloads on a node.
Must be used with `KubeletConfiguration.failSwapOn` set to false.
For more details, please see [swap memory](/docs/concepts/architecture/nodes/#swap-memory)
@@ -937,23 +964,23 @@ Each feature gate is designed for enabling/disabling a specific feature:
- `OpenAPIEnums`: Enables populating "enum" fields of OpenAPI schemas in the
spec returned from the API server.
- `OpenAPIV3`: Enables the API server to publish OpenAPI v3.
- `PVCProtection`: Enable the prevention of a PersistentVolumeClaim (PVC) from
being deleted when it is still used by any Pod.
- `PodDeletionCost`: Enable the [Pod Deletion Cost](/docs/concepts/workloads/controllers/replicaset/#pod-deletion-cost)
feature which allows users to influence ReplicaSet downscaling order.
- `PersistentLocalVolumes`: Enable the usage of `local` volume type in Pods.
Pod affinity has to be specified if requesting a `local` volume.
- `PodAndContainerStatsFromCRI`: Configure the kubelet to gather container and pod stats from the CRI container runtime
rather than gathering them from cAdvisor.
- `PodAndContainerStatsFromCRI`: Configure the kubelet to gather container and
pod stats from the CRI container runtime rather than gathering them from cAdvisor.
- `PodDisruptionBudget`: Enable the [PodDisruptionBudget](/docs/tasks/run-application/configure-pdb/) feature.
- `PodAffinityNamespaceSelector`: Enable the [Pod Affinity Namespace Selector](/docs/concepts/scheduling-eviction/assign-pod-node/#namespace-selector)
and [CrossNamespacePodAffinity](/docs/concepts/policy/resource-quotas/#cross-namespace-pod-affinity-quota) quota scope features.
- `PodAffinityNamespaceSelector`: Enable the
[Pod Affinity Namespace Selector](/docs/concepts/scheduling-eviction/assign-pod-node/#namespace-selector)
and [CrossNamespacePodAffinity](/docs/concepts/policy/resource-quotas/#cross-namespace-pod-affinity-quota)
quota scope features.
- `PodOverhead`: Enable the [PodOverhead](/docs/concepts/scheduling-eviction/pod-overhead/)
feature to account for pod overheads.
- `PodPriority`: Enable the descheduling and preemption of Pods based on their
[priorities](/docs/concepts/scheduling-eviction/pod-priority-preemption/).
- `PodReadinessGates`: Enable the setting of `PodReadinessGate` field for extending
Pod readiness evaluation. See [Pod readiness gate](/docs/concepts/workloads/pods/pod-lifecycle/#pod-readiness-gate)
Pod readiness evaluation. See [Pod readiness gate](/docs/concepts/workloads/pods/pod-lifecycle/#pod-readiness-gate)
for more details.
- `PodSecurity`: Enables the `PodSecurity` admission plugin.
- `PodShareProcessNamespace`: Enable the setting of `shareProcessNamespace` in a Pod for sharing
@@ -964,25 +991,27 @@ Each feature gate is designed for enabling/disabling a specific feature:
the cluster.
- `ProbeTerminationGracePeriod`: Enable [setting probe-level
`terminationGracePeriodSeconds`](/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#probe-level-terminationgraceperiodseconds)
on pods. See the [enhancement proposal](https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/2238-liveness-probe-grace-period) for more details.
on pods. See the [enhancement proposal](https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/2238-liveness-probe-grace-period)
for more details.
- `ProcMountType`: Enables control over the type proc mounts for containers
by setting the `procMount` field of a SecurityContext.
- `ProxyTerminatingEndpoints`: Enable the kube-proxy to handle terminating
endpoints when `ExternalTrafficPolicy=Local`.
- `PVCProtection`: Enable the prevention of a PersistentVolumeClaim (PVC) from
being deleted when it is still used by any Pod.
- `QOSReserved`: Allows resource reservations at the QoS level preventing pods
at lower QoS levels from bursting into resources requested at higher QoS levels
(memory only for now).
- `ReadWriteOncePod`: Enables the usage of `ReadWriteOncePod` PersistentVolume
access mode.
- `RecoverVolumeExpansionFailure`: Enables users to edit their PVCs to smaller sizes so as they can recover from previously issued
volume expansion failures. See
[Recovering from Failure when Expanding Volumes](/docs/concepts/storage/persistent-volumes/#recovering-from-failure-when-expanding-volumes)
- `RecoverVolumeExpansionFailure`: Enables users to edit their PVCs to smaller
sizes so as they can recover from previously issued volume expansion failures.
See [Recovering from Failure when Expanding Volumes](/docs/concepts/storage/persistent-volumes/#recovering-from-failure-when-expanding-volumes)
for more details.
- `RemainingItemCount`: Allow the API servers to show a count of remaining
items in the response to a
[chunking list request](/docs/reference/using-api/api-concepts/#retrieving-large-results-sets-in-chunks).
- `RemoveSelfLink`: Deprecates and removes `selfLink` from ObjectMeta and
ListMeta.
- `RemoveSelfLink`: Deprecates and removes `selfLink` from ObjectMeta and ListMeta.
- `RequestManagement`: Enables managing request concurrency with prioritization and fairness
at each API server. Deprecated by `APIPriorityAndFairness` since 1.17.
- `ResourceLimitsPriorityFunction`: Enable a scheduler priority function that
@@ -997,7 +1026,8 @@ Each feature gate is designed for enabling/disabling a specific feature:
[Bound Service Account Tokens](https://github.com/kubernetes/enhancements/blob/master/keps/sig-auth/1205-bound-service-account-tokens/README.md)
for more details.
- `RotateKubeletClientCertificate`: Enable the rotation of the client TLS certificate on the kubelet.
See [kubelet configuration](/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/#kubelet-configuration) for more details.
See [kubelet configuration](/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/#kubelet-configuration)
for more details.
- `RotateKubeletServerCertificate`: Enable the rotation of the server TLS certificate on the kubelet.
See [kubelet configuration](/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/#kubelet-configuration)
for more details.
@@ -1009,7 +1039,8 @@ Each feature gate is designed for enabling/disabling a specific feature:
instead of the DaemonSet controller.
- `SCTPSupport`: Enables the _SCTP_ `protocol` value in Pod, Service,
Endpoints, EndpointSlice, and NetworkPolicy definitions.
- `SeccompDefault`: Enables the use of `RuntimeDefault` as the default seccomp profile for all workloads.
- `SeccompDefault`: Enables the use of `RuntimeDefault` as the default seccomp profile
for all workloads.
The seccomp profile is specified in the `securityContext` of a Pod and/or a Container.
- `SelectorIndex`: Allows label and field based indexes in API server watch
cache to accelerate list operations.
@@ -1023,7 +1054,8 @@ Each feature gate is designed for enabling/disabling a specific feature:
- `ServiceInternalTrafficPolicy`: Enables the `internalTrafficPolicy` field on Services
- `ServiceLBNodePortControl`: Enables the `allocateLoadBalancerNodePorts` field on Services.
- `ServiceLoadBalancerClass`: Enables the `loadBalancerClass` field on Services. See
[Specifying class of load balancer implementation](/docs/concepts/services-networking/service/#load-balancer-class) for more details.
[Specifying class of load balancer implementation](/docs/concepts/services-networking/service/#load-balancer-class)
for more details.
- `ServiceLoadBalancerFinalizer`: Enable finalizer protection for Service load balancers.
- `ServiceNodeExclusion`: Enable the exclusion of nodes from load balancers
created by a cloud provider. A node is eligible for exclusion if labelled with
@@ -126,7 +126,6 @@ of provisioning.
2. [Token authentication file](#token-authentication-file)
Bootstrap tokens are a simpler and more easily managed method to authenticate kubelets, and do not require any additional flags when starting kube-apiserver.
Using bootstrap tokens is currently __beta__ as of Kubernetes version 1.12.
Whichever method you choose, the requirement is that the kubelet be able to authenticate as a user with the rights to:
@@ -39,6 +39,11 @@ complete -F __start_kubectl k
source <(kubectl completion zsh) # setup autocomplete in zsh into the current shell
echo "[[ $commands[kubectl] ]] && source <(kubectl completion zsh)" >> ~/.zshrc # add autocomplete permanently to your zsh shell
```
### A Note on --all-namespaces
Appending `--all-namespaces` happens frequently enough where you should be aware of the shorthand for `--all-namespaces`:
```kubectl -A```
## Kubectl context and configuration
@@ -97,10 +102,10 @@ kubectl apply -f https://git.io/vPieo # create resource(s) from url
kubectl create deployment nginx --image=nginx # start a single instance of nginx
# create a Job which prints "Hello World"
kubectl create job hello --image=busybox -- echo "Hello World"
kubectl create job hello --image=busybox:1.28 -- echo "Hello World"
# create a CronJob that prints "Hello World" every minute
kubectl create cronjob hello --image=busybox --schedule="*/1 * * * *" -- echo "Hello World"
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World"
kubectl explain pods # get the documentation for pod manifests
@@ -113,7 +118,7 @@ metadata:
spec:
containers:
- name: busybox
image: busybox
image: busybox:1.28
args:
- sleep
- "1000000"
@@ -125,7 +130,7 @@ metadata:
spec:
containers:
- name: busybox
image: busybox
image: busybox:1.28
args:
- sleep
- "1000"
@@ -315,7 +320,7 @@ kubectl logs my-pod -c my-container --previous # dump pod container logs (s
kubectl logs -f my-pod # stream pod logs (stdout)
kubectl logs -f my-pod -c my-container # stream pod container logs (stdout, multi-container case)
kubectl logs -f -l name=myLabel --all-containers # stream all pods logs with label name=myLabel (stdout)
kubectl run -i --tty busybox --image=busybox -- sh # Run pod as interactive shell
kubectl run -i --tty busybox --image=busybox:1.28 -- sh # Run pod as interactive shell
kubectl run nginx --image=nginx -n mynamespace # Start a single instance of nginx pod in the namespace of mynamespace
kubectl run nginx --image=nginx # Run pod nginx and write its spec into a file called pod.yaml
--dry-run=client -o yaml > pod.yaml
@@ -495,8 +495,10 @@ based on setting `securityContext` within the Pod's `.spec`.
## Annotations used for audit
- [`pod-security.kubernetes.io/exempt`](/docs/reference/labels-annotations-taints/audit-annotations/#pod-security-kubernetes-io-exempt)
- [`pod-security.kubernetes.io/enforce-policy`](/docs/reference/labels-annotations-taints/audit-annotations/#pod-security-kubernetes-io-enforce-policy)
- [`authorization.k8s.io/decision`](/docs/reference/labels-annotations-taints/audit-annotations/#authorization-k8s-io-decision)
- [`authorization.k8s.io/reason`](/docs/reference/labels-annotations-taints/audit-annotations/#authorization-k8s-io-reason)
- [`pod-security.kubernetes.io/audit-violations`](/docs/reference/labels-annotations-taints/audit-annotations/#pod-security-kubernetes-io-audit-violations)
- [`pod-security.kubernetes.io/enforce-policy`](/docs/reference/labels-annotations-taints/audit-annotations/#pod-security-kubernetes-io-enforce-policy)
- [`pod-security.kubernetes.io/exempt`](/docs/reference/labels-annotations-taints/audit-annotations/#pod-security-kubernetes-io-exempt)
See more details on the [Audit Annotations](/docs/reference/labels-annotations-taints/audit-annotations/) page.
@@ -56,4 +56,20 @@ that was transgressed as well as the specific policies on the fields that were
violated from the PodSecurity enforcement.
See [Pod Security Standards](/docs/concepts/security/pod-security-standards/)
for more information.
for more information.
## authorization.k8s.io/decision
Example: `authorization.k8s.io/decision: "forbid"`
This annotation indicates whether or not a request was authorized in Kubernetes audit logs.
See [Auditing](/docs/tasks/debug-application-cluster/audit/) for more information.
## authorization.k8s.io/reason
Example: `authorization.k8s.io/decision: "Human-readable reason for the decision"`
This annotation gives reason for the [decision](#authorization-k8s-io-decision) in Kubernetes audit logs.
See [Auditing](/docs/tasks/debug-application-cluster/audit/) for more information.
@@ -205,35 +205,10 @@ See documentation for other libraries for how they authenticate.
## Accessing the API from a Pod
When accessing the API from a pod, locating and authenticating
to the apiserver are somewhat different.
to the API server are somewhat different.
The recommended way to locate the apiserver within the pod is with
the `kubernetes.default.svc` DNS name, which resolves to a Service IP which in turn
will be routed to an apiserver.
The recommended way to authenticate to the apiserver is with a
[service account](/docs/tasks/configure-pod-container/configure-service-account/) credential. By kube-system, a pod
is associated with a service account, and a credential (token) for that
service account is placed into the filesystem tree of each container in that pod,
at `/var/run/secrets/kubernetes.io/serviceaccount/token`.
If available, a certificate bundle is placed into the filesystem tree of each
container at `/var/run/secrets/kubernetes.io/serviceaccount/ca.crt`, and should be
used to verify the serving certificate of the apiserver.
Finally, the default namespace to be used for namespaced API operations is placed in a file
at `/var/run/secrets/kubernetes.io/serviceaccount/namespace` in each container.
From within a pod the recommended ways to connect to API are:
- Run `kubectl proxy` in a sidecar container in the pod, or as a background
process within the container. This proxies the
Kubernetes API to the localhost interface of the pod, so that other processes
in any container of the pod can access it.
- Use the Go client library, and create a client using the `rest.InClusterConfig()` and `kubernetes.NewForConfig()` functions.
They handle locating and authenticating to the apiserver. [example](https://git.k8s.io/client-go/examples/in-cluster-client-configuration/main.go)
In each case, the credentials of the pod are used to communicate securely with the apiserver.
Please check [Accessing the API from within a Pod](/docs/tasks/run-application/access-api-from-pod/)
for more details.
## Accessing services running on the cluster
@@ -68,7 +68,7 @@ pod/nginx-701339712-e0qfq 1/1 Running 0 35s
You should be able to access the new `nginx` service from other Pods. To access the `nginx` Service from another Pod in the `default` namespace, start a busybox container:
```console
kubectl run busybox --rm -ti --image=busybox -- /bin/sh
kubectl run busybox --rm -ti --image=busybox:1.28 -- /bin/sh
```
In your shell, run the following command:
@@ -111,7 +111,7 @@ networkpolicy.networking.k8s.io/access-nginx created
When you attempt to access the `nginx` Service from a Pod without the correct labels, the request times out:
```console
kubectl run busybox --rm -ti --image=busybox -- /bin/sh
kubectl run busybox --rm -ti --image=busybox:1.28 -- /bin/sh
```
In your shell, run the command:
@@ -130,7 +130,7 @@ wget: download timed out
You can create a Pod with the correct labels to see that the request is allowed:
```console
kubectl run busybox --rm -ti --labels="access=true" --image=busybox -- /bin/sh
kubectl run busybox --rm -ti --labels="access=true" --image=busybox:1.28 -- /bin/sh
```
In your shell, run the command:
@@ -4,31 +4,27 @@ content_type: task
---
<!-- overview -->
This page shows how to configure and enable the ip-masq-agent.
This page shows how to configure and enable the `ip-masq-agent`.
## {{% heading "prerequisites" %}}
{{< include "task-tutorial-prereqs.md" >}} {{< version-check >}}
<!-- discussion -->
## IP Masquerade Agent User Guide
The ip-masq-agent configures iptables rules to hide a pod's IP address behind the cluster node's IP address. This is typically done when sending traffic to destinations outside the cluster's pod [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) range.
The `ip-masq-agent` configures iptables rules to hide a pod's IP address behind the cluster node's IP address. This is typically done when sending traffic to destinations outside the cluster's pod [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) range.
### **Key Terms**
* **NAT (Network Address Translation)**
Is a method of remapping one IP address to another by modifying either the source and/or destination address information in the IP header. Typically performed by a device doing IP routing.
* **Masquerading**
A form of NAT that is typically used to perform a many to one address translation, where multiple source IP addresses are masked behind a single address, which is typically the device doing the IP routing. In Kubernetes this is the Node's IP address.
* **CIDR (Classless Inter-Domain Routing)**
Based on the variable-length subnet masking, allows specifying arbitrary-length prefixes. CIDR introduced a new method of representation for IP addresses, now commonly known as **CIDR notation**, in which an address or routing prefix is written with a suffix indicating the number of bits of the prefix, such as 192.168.2.0/24.
* **Link Local**
A link-local address is a network address that is valid only for communications within the network segment or the broadcast domain that the host is connected to. Link-local addresses for IPv4 are defined in the address block 169.254.0.0/16 in CIDR notation.
* **NAT (Network Address Translation)**
Is a method of remapping one IP address to another by modifying either the source and/or destination address information in the IP header. Typically performed by a device doing IP routing.
* **Masquerading**
A form of NAT that is typically used to perform a many to one address translation, where multiple source IP addresses are masked behind a single address, which is typically the device doing the IP routing. In Kubernetes this is the Node's IP address.
* **CIDR (Classless Inter-Domain Routing)**
Based on the variable-length subnet masking, allows specifying arbitrary-length prefixes. CIDR introduced a new method of representation for IP addresses, now commonly known as **CIDR notation**, in which an address or routing prefix is written with a suffix indicating the number of bits of the prefix, such as 192.168.2.0/24.
* **Link Local**
A link-local address is a network address that is valid only for communications within the network segment or the broadcast domain that the host is connected to. Link-local addresses for IPv4 are defined in the address block 169.254.0.0/16 in CIDR notation.
The ip-masq-agent configures iptables rules to handle masquerading node/pod IP addresses when sending traffic to destinations outside the cluster node's IP and the Cluster IP range. This essentially hides pod IP addresses behind the cluster node's IP address. In some environments, traffic to "external" addresses must come from a known machine address. For example, in Google Cloud, any traffic to the internet must come from a VM's IP. When containers are used, as in Google Kubernetes Engine, the Pod IP will be rejected for egress. To avoid this, we must hide the Pod IP behind the VM's own IP address - generally known as "masquerade". By default, the agent is configured to treat the three private IP ranges specified by [RFC 1918](https://tools.ietf.org/html/rfc1918) as non-masquerade [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing). These ranges are 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. The agent will also treat link-local (169.254.0.0/16) as a non-masquerade CIDR by default. The agent is configured to reload its configuration from the location */etc/config/ip-masq-agent* every 60 seconds, which is also configurable.
@@ -36,14 +32,20 @@ The ip-masq-agent configures iptables rules to handle masquerading node/pod IP a
The agent configuration file must be written in YAML or JSON syntax, and may contain three optional keys:
* **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:** A time interval at which the agent attempts to reload config from disk. For example: '30s', where 's' means seconds, 'ms' means milliseconds, etc...
* `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`: A time interval at which the agent attempts to reload config from disk.
For example: '30s', where 's' means seconds, 'ms' means milliseconds.
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:
```
```shell
iptables -t nat -L IP-MASQ-AGENT
```
```none
RETURN all -- anywhere 169.254.0.0/16 /* ip-masq-agent: cluster-local traffic should not be subject to MASQUERADE */ ADDRTYPE match dst-type !LOCAL
RETURN all -- anywhere 10.0.0.0/8 /* ip-masq-agent: cluster-local traffic should not be subject to MASQUERADE */ ADDRTYPE match dst-type !LOCAL
RETURN all -- anywhere 172.16.0.0/12 /* ip-masq-agent: cluster-local traffic should not be subject to MASQUERADE */ ADDRTYPE match dst-type !LOCAL
@@ -52,33 +54,35 @@ MASQUERADE all -- anywhere anywhere /* ip-masq-agent:
```
By default, in GCE/Google Kubernetes Engine starting with Kubernetes version 1.7.0, if network policy is enabled or you are using a cluster CIDR not in the 10.0.0.0/8 range, the ip-masq-agent will run in your cluster. If you are running in another environment, you can add the ip-masq-agent [DaemonSet](/docs/concepts/workloads/controllers/daemonset/) to your cluster:
By default, in GCE/Google Kubernetes Engine, if network policy is enabled or
you are using a cluster CIDR not in the 10.0.0.0/8 range, the `ip-masq-agent`
will run in your cluster. If you are running in another environment,
you can add the `ip-masq-agent` [DaemonSet](/docs/concepts/workloads/controllers/daemonset/)
to your cluster.
<!-- steps -->
## Create an ip-masq-agent
To create an ip-masq-agent, run the following kubectl command:
`
```shell
kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/ip-masq-agent/master/ip-masq-agent.yaml
`
```
You must also apply the appropriate node label to any nodes in your cluster that you want the agent to run on.
`
kubectl label nodes my-node beta.kubernetes.io/masq-agent-ds-ready=true
`
```shell
kubectl label nodes my-node node.kubernetes.io/masq-agent-ds-ready=true
```
More information can be found in the ip-masq-agent documentation [here](https://github.com/kubernetes-sigs/ip-masq-agent)
In most cases, the default set of rules should be sufficient; however, if this is not the case for your cluster, you can create and apply a [ConfigMap](/docs/tasks/configure-pod-container/configure-pod-configmap/) to customize the IP ranges that are affected. For example, to allow only 10.0.0.0/8 to be considered by the ip-masq-agent, you can create the following [ConfigMap](/docs/tasks/configure-pod-container/configure-pod-configmap/) in a file called "config".
{{< note >}}
It is important that the file is called config since, by default, that will be used as the key for lookup by the ip-masq-agent:
It is important that the file is called config since, by default, that will be used as the key for lookup by the `ip-masq-agent`:
```
```yaml
nonMasqueradeCIDRs:
- 10.0.0.0/8
resyncInterval: 60s
@@ -87,15 +91,18 @@ resyncInterval: 60s
Run the following command to add the config map to your cluster:
```
```shell
kubectl create configmap ip-masq-agent --from-file=config --namespace=kube-system
```
This will update a file located at */etc/config/ip-masq-agent* which is periodically checked every *resyncInterval* and applied to the cluster node.
This will update a file located at `/etc/config/ip-masq-agent` which is periodically checked every `resyncInterval` and applied to the cluster node.
After the resync interval has expired, you should see the iptables rules reflect your changes:
```
```shell
iptables -t nat -L IP-MASQ-AGENT
```
```none
Chain IP-MASQ-AGENT (1 references)
target prot opt source destination
RETURN all -- anywhere 169.254.0.0/16 /* ip-masq-agent: cluster-local traffic should not be subject to MASQUERADE */ ADDRTYPE match dst-type !LOCAL
@@ -103,9 +110,9 @@ RETURN all -- anywhere 10.0.0.0/8 /* ip-masq-agent:
MASQUERADE all -- anywhere anywhere /* ip-masq-agent: outbound traffic should be subject to MASQUERADE (this match must come after cluster-local CIDR matches) */ ADDRTYPE match dst-type !LOCAL
```
By default, the link local range (169.254.0.0/16) is also handled by the ip-masq agent, which sets up the appropriate iptables rules. To have the ip-masq-agent ignore link local, you can set *masqLinkLocal* to true in the config map.
By default, the link local range (169.254.0.0/16) is also handled by the ip-masq agent, which sets up the appropriate iptables rules. To have the ip-masq-agent ignore link local, you can set `masqLinkLocal` to true in the ConfigMap.
```
```yaml
nonMasqueradeCIDRs:
- 10.0.0.0/8
resyncInterval: 60s
@@ -81,13 +81,13 @@ kubectl describe pod liveness-exec
The output indicates that no liveness probes have failed yet:
```
FirstSeen LastSeen Count From SubobjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
24s 24s 1 {default-scheduler } Normal Scheduled Successfully assigned liveness-exec to worker0
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Pulling pulling image "k8s.gcr.io/busybox"
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Pulled Successfully pulled image "k8s.gcr.io/busybox"
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Created Created container with docker id 86849c15382e; Security:[seccomp=unconfined]
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Started Started container with docker id 86849c15382e
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 11s default-scheduler Successfully assigned default/liveness-exec to node01
Normal Pulling 9s kubelet, node01 Pulling image "k8s.gcr.io/busybox"
Normal Pulled 7s kubelet, node01 Successfully pulled image "k8s.gcr.io/busybox"
Normal Created 7s kubelet, node01 Created container liveness
Normal Started 7s kubelet, node01 Started container liveness
```
After 35 seconds, view the Pod events again:
@@ -100,14 +100,15 @@ At the bottom of the output, there are messages indicating that the liveness
probes have failed, and the containers have been killed and recreated.
```
FirstSeen LastSeen Count From SubobjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
37s 37s 1 {default-scheduler } Normal Scheduled Successfully assigned liveness-exec to worker0
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Pulling pulling image "k8s.gcr.io/busybox"
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Pulled Successfully pulled image "k8s.gcr.io/busybox"
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Created Created container with docker id 86849c15382e; Security:[seccomp=unconfined]
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Started Started container with docker id 86849c15382e
2s 2s 1 {kubelet worker0} spec.containers{liveness} Warning Unhealthy Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 57s default-scheduler Successfully assigned default/liveness-exec to node01
Normal Pulling 55s kubelet, node01 Pulling image "k8s.gcr.io/busybox"
Normal Pulled 53s kubelet, node01 Successfully pulled image "k8s.gcr.io/busybox"
Normal Created 53s kubelet, node01 Created container liveness
Normal Started 53s kubelet, node01 Started container liveness
Warning Unhealthy 10s (x3 over 20s) kubelet, node01 Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
Normal Killing 10s kubelet, node01 Container liveness failed liveness probe, will be restarted
```
Wait another 30 seconds, and verify that the container has been restarted:
@@ -218,6 +218,7 @@ Use the option `--from-env-file` to create a ConfigMap from an env-file, for exa
# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.io/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties
wget https://kubernetes.io/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties
# The env-file `game-env-file.properties` looks like below
cat configure-pod-container/configmap/game-env-file.properties
@@ -255,17 +256,10 @@ data:
lives: "3"
```
{{< caution >}}
When passing `--from-env-file` multiple times to create a ConfigMap from multiple data sources, only the last env-file is used.
{{< /caution >}}
The behavior of passing `--from-env-file` multiple times is demonstrated by:
Starting with Kubernetes v1.23, `kubectl` supports the `--from-env-file` argument to be
specified multiple times to create a ConfigMap from multiple data sources.
```shell
# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.io/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties
# Create the configmap
kubectl create configmap config-multi-env-files \
--from-env-file=configure-pod-container/configmap/game-env-file.properties \
--from-env-file=configure-pod-container/configmap/ui-env-file.properties
@@ -288,8 +282,11 @@ metadata:
resourceVersion: "810136"
uid: 252c4572-eb35-11e7-887b-42010a8002b8
data:
allowed: '"true"'
color: purple
enemies: aliens
how: fairlyNice
lives: "3"
textmode: "true"
```
@@ -110,7 +110,7 @@ specify the `-i`/`--interactive` argument, `kubectl` will automatically attach
to the console of the Ephemeral Container.
```shell
kubectl debug -it ephemeral-demo --image=busybox --target=ephemeral-demo
kubectl debug -it ephemeral-demo --image=busybox:1.28 --target=ephemeral-demo
```
```
@@ -182,7 +182,7 @@ but you need debugging utilities not included in `busybox`. You can simulate
this scenario using `kubectl run`:
```shell
kubectl run myapp --image=busybox --restart=Never -- sleep 1d
kubectl run myapp --image=busybox:1.28 --restart=Never -- sleep 1d
```
Run this command to create a copy of `myapp` named `myapp-debug` that adds a
@@ -225,7 +225,7 @@ To simulate a crashing application, use `kubectl run` to create a container
that immediately exits:
```
kubectl run --image=busybox myapp -- false
kubectl run --image=busybox:1.28 myapp -- false
```
You can see using `kubectl describe pod myapp` that this container is crashing:
@@ -283,7 +283,7 @@ additional utilities.
As an example, create a Pod using `kubectl run`:
```
kubectl run myapp --image=busybox --restart=Never -- sleep 1d
kubectl run myapp --image=busybox:1.28 --restart=Never -- sleep 1d
```
Now use `kubectl debug` to make a copy and change its container image
@@ -201,7 +201,7 @@ spec:
spec:
containers:
- name: c
image: busybox
image: busybox:1.28
command: ["sh", "-c", "echo Processing URL {{ url }} && sleep 5"]
restartPolicy: Never
{% endfor %}
@@ -48,7 +48,8 @@ While running in a Pod, the Kubernetes apiserver is accessible via a Service nam
do this automatically.
The recommended way to authenticate to the API server is with a
[service account](/docs/tasks/configure-pod-container/configure-service-account/) credential. By default, a Pod
[service account](/docs/tasks/configure-pod-container/configure-service-account/)
credential. By default, a Pod
is associated with a service account, and a credential (token) for that
service account is placed into the filesystem tree of each container in that Pod,
at `/var/run/secrets/kubernetes.io/serviceaccount/token`.
@@ -152,7 +152,7 @@ runs in an infinite loop, sending queries to the php-apache service.
```shell
# Run this in a separate terminal
# so that the load generation continues and you can carry on with the rest of the steps
kubectl run -i --tty load-generator --rm --image=busybox --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"
kubectl run -i --tty load-generator --rm --image=busybox:1.28 --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"
```
Now run:
@@ -337,9 +337,9 @@ APIs, cluster administrators must ensure that:
* For external metrics, this is the `external.metrics.k8s.io` API. It may be provided by the custom metrics adapters provided above.
For more information on these different metrics paths and how they differ please see the relevant design proposals for
[the HPA V2](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/autoscaling/hpa-v2.md),
[custom.metrics.k8s.io](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/instrumentation/custom-metrics-api.md)
and [external.metrics.k8s.io](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/instrumentation/external-metrics-api.md).
[the HPA V2](https://github.com/kubernetes/design-proposals-archive/blob/main/autoscaling/hpa-v2.md),
[custom.metrics.k8s.io](https://github.com/kubernetes/design-proposals-archive/blob/main/instrumentation/custom-metrics-api.md)
and [external.metrics.k8s.io](https://github.com/kubernetes/design-proposals-archive/blob/main/instrumentation/external-metrics-api.md).
For examples of how to use them see [the walkthrough for using custom metrics](/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/#autoscaling-on-multiple-metrics-and-custom-metrics)
and [the walkthrough for using external metrics](/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/#autoscaling-on-metrics-not-related-to-kubernetes-objects).
@@ -52,7 +52,7 @@ For example, to download version {{< param "fullversion" >}} on Linux, type:
Validate the kubectl binary against the checksum file:
```bash
echo "$(<kubectl.sha256) kubectl" | sha256sum --check
echo "$(cat kubectl.sha256) kubectl" | sha256sum --check
```
If valid, the output is:
@@ -212,7 +212,7 @@ Below are the procedures to set up autocompletion for Bash, Fish, and Zsh.
Validate the kubectl-convert binary against the checksum file:
```bash
echo "$(<kubectl-convert.sha256) kubectl-convert" | sha256sum --check
echo "$(cat kubectl-convert.sha256) kubectl-convert" | sha256sum --check
```
If valid, the output is:
@@ -69,7 +69,7 @@ The following methods exist for installing kubectl on macOS:
Validate the kubectl binary against the checksum file:
```bash
echo "$(<kubectl.sha256) kubectl" | shasum -a 256 --check
echo "$(cat kubectl.sha256) kubectl" | shasum -a 256 --check
```
If valid, the output is:
@@ -205,7 +205,7 @@ Below are the procedures to set up autocompletion for Bash, Fish, and Zsh.
Validate the kubectl-convert binary against the checksum file:
```bash
echo "$(<kubectl-convert.sha256) kubectl-convert" | shasum -a 256 --check
echo "$(cat kubectl-convert.sha256) kubectl-convert" | shasum -a 256 --check
```
If valid, the output is:
@@ -264,7 +264,7 @@ metadata:
spec:
containers:
- name: hello
image: busybox
image: busybox:1.28
command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]
EOF
pod/hello-apparmor-2 created
@@ -119,7 +119,7 @@ clusterip ClusterIP 10.0.170.92 <none> 80/TCP 51s
And hitting the `ClusterIP` from a pod in the same cluster:
```shell
kubectl run busybox -it --image=busybox --restart=Never --rm
kubectl run busybox -it --image=busybox:1.28 --restart=Never --rm
```
The output is similar to this:
```
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: count
image: busybox
image: busybox:1.28
args:
- /bin/sh
- -c
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: count
image: busybox
image: busybox:1.28
args:
- /bin/sh
- -c
@@ -22,13 +22,13 @@ spec:
- name: varlog
mountPath: /var/log
- name: count-log-1
image: busybox
image: busybox:1.28
args: [/bin/sh, -c, 'tail -n+1 -f /var/log/1.log']
volumeMounts:
- name: varlog
mountPath: /var/log
- name: count-log-2
image: busybox
image: busybox:1.28
args: [/bin/sh, -c, 'tail -n+1 -f /var/log/2.log']
volumeMounts:
- name: varlog
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: count
image: busybox
image: busybox:1.28
args:
- /bin/sh
- -c
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: busybox-cnt01
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt01; sleep 10;done"]
resources:
@@ -16,7 +16,7 @@ spec:
memory: "200Mi"
cpu: "500m"
- name: busybox-cnt02
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt02; sleep 10;done"]
resources:
@@ -24,7 +24,7 @@ spec:
memory: "100Mi"
cpu: "100m"
- name: busybox-cnt03
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt03; sleep 10;done"]
resources:
@@ -32,6 +32,6 @@ spec:
memory: "200Mi"
cpu: "500m"
- name: busybox-cnt04
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt04; sleep 10;done"]
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: busybox-cnt01
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt01; sleep 10;done"]
resources:
@@ -16,7 +16,7 @@ spec:
memory: "200Mi"
cpu: "500m"
- name: busybox-cnt02
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt02; sleep 10;done"]
resources:
@@ -24,7 +24,7 @@ spec:
memory: "100Mi"
cpu: "100m"
- name: busybox-cnt03
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt03; sleep 10;done"]
resources:
@@ -32,6 +32,6 @@ spec:
memory: "200Mi"
cpu: "500m"
- name: busybox-cnt04
image: busybox
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt04; sleep 10;done"]
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: busybox-cnt01
image: busybox
image: busybox:1.28
resources:
limits:
memory: "300Mi"
@@ -10,7 +10,7 @@ spec:
spec:
containers:
- name: hello
image: busybox
image: busybox:1.28
imagePullPolicy: IfNotPresent
command:
- /bin/sh
@@ -13,6 +13,6 @@ spec:
spec:
containers:
- name: c
image: busybox
image: busybox:1.28
command: ["sh", "-c", "echo Processing item $ITEM && sleep 5"]
restartPolicy: Never
+1 -1
View File
@@ -5,6 +5,6 @@ metadata:
spec:
containers:
- name: count
image: busybox
image: busybox:1.28
args: [/bin/sh, -c,
'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done']
@@ -14,7 +14,7 @@ spec:
# These containers are run during pod initialization
initContainers:
- name: install
image: busybox
image: busybox:1.28
command:
- wget
- "-O"
@@ -10,7 +10,7 @@ spec:
command:
- sh
- -c
image: busybox
image: busybox:1.28
env:
- name: SERVICE_PORT
value: "80"
@@ -9,5 +9,5 @@ metadata:
spec:
containers:
- name: hello
image: busybox
image: busybox:1.28
command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]
@@ -12,7 +12,7 @@ spec:
emptyDir: {}
containers:
- name: sec-ctx-demo
image: busybox
image: busybox:1.28
command: [ "sh", "-c", "sleep 1h" ]
volumeMounts:
- name: sec-ctx-vol
@@ -8,7 +8,7 @@ spec:
- name: nginx
image: nginx
- name: shell
image: busybox
image: busybox:1.28
securityContext:
capabilities:
add:
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: container-test
image: busybox
image: busybox:1.28
volumeMounts:
- name: all-in-one
mountPath: "/projected-volume"
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: container-test
image: busybox
image: busybox:1.28
volumeMounts:
- name: all-in-one
mountPath: "/projected-volume"
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: container-test
image: busybox
image: busybox:1.28
volumeMounts:
- name: token-vol
mountPath: "/service-account"
@@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: test-projected-volume
image: busybox
image: busybox:1.28
args:
- sleep
- "86400"
@@ -15,7 +15,7 @@ spec:
- "bar.remote"
containers:
- name: cat-hosts
image: busybox
image: busybox:1.28
command:
- cat
args:
@@ -0,0 +1,63 @@
---
title: Límites de Volumen específicos del Nodo
content_type: concept
---
<!-- overview -->
Esta página describe la cantidad máxima de Volúmenes que se pueden adjuntar a un Nodo para varios proveedores de nube.
Los proveedores de la nube como Google, Amazon y Microsoft suelen tener un límite en la cantidad de Volúmenes que se pueden adjuntar a un Nodo. Es importante que Kubernetes respete esos límites. De lo contrario, los Pods planificados en un Nodo podrían quedarse atascados esperando que los Volúmenes se conecten.
<!-- body -->
## Límites predeterminados de Kubernetes
El Planificador de Kubernetes tiene límites predeterminados en la cantidad de Volúmenes que se pueden adjuntar a un Nodo:
<table>
<tr><th>Servicio de almacenamiento en la nube</th><th>Volúmenes máximos por Nodo</th></tr>
<tr><td><a href="https://aws.amazon.com/ebs/">Amazon Elastic Block Store (EBS)</a></td><td>39</td></tr>
<tr><td><a href="https://cloud.google.com/persistent-disk/">Google Persistent Disk</a></td><td>16</td></tr>
<tr><td><a href="https://azure.microsoft.com/en-us/services/storage/main-disks/">Microsoft Azure Disk Storage</a></td><td>16</td></tr>
</table>
## Límites personalizados
Puede cambiar estos límites configurando el valor de la variable de entorno KUBE_MAX_PD_VOLS y luego iniciando el Planificador. Los controladores CSI pueden tener un procedimiento diferente, consulte su documentación sobre cómo personalizar sus límites.
Tenga cuidado si establece un límite superior al límite predeterminado. Consulte la documentación del proveedor de la nube para asegurarse de que los Nodos realmente puedan admitir el límite que establezca.
El límite se aplica a todo el clúster, por lo que afecta a todos los Nodos.
## Límites de Volumen dinámico
{{< feature-state state="stable" for_k8s_version="v1.17" >}}
Los límites de Volumen dinámico son compatibles con los siguientes tipos de Volumen.
- Amazon EBS
- Google Persistent Disk
- Azure Disk
- CSI
Para los Volúmenes administrados por in-tree plugins de Volumen, Kubernetes determina automáticamente el tipo de Nodo y aplica la cantidad máxima adecuada de Volúmenes para el Nodo. Por ejemplo:
* En
<a href="https://cloud.google.com/compute/">Google Compute Engine</a>,
se pueden adjuntar hasta 127 Volúmenes a un Nodo, [según el tipo de Nodo](https://cloud.google.com/compute/docs/disks/#pdnumberlimits).
* Para los discos de Amazon EBS en los tipos de instancias M5,C5,R5,T3 y Z1D, Kubernetes permite que solo se adjunten 25 Volúmenes a un Nodo. Para otros tipos de instancias en
<a href="https://aws.amazon.com/ec2/">Amazon Elastic Compute Cloud (EC2)</a>,
Kubernetes permite adjuntar 39 Volúmenes a un Nodo.
* En Azure, se pueden conectar hasta 64 discos a un Nodo, según el tipo de Nodo. Para obtener más detalles, consulte [Sizes for virtual machines in Azure](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes).
* Si un controlador de almacenamiento CSI anuncia una cantidad máxima de Volúmenes para un Nodo (usando `NodeGetInfo`), el {{< glossary_tooltip text="kube-scheduler" term_id="kube-scheduler" >}} respeta ese límite.
Consulte las [especificaciones de CSI](https://github.com/container-storage-interface/spec/blob/master/spec.md#nodegetinfo) para obtener más información.
* Para los Volúmenes administrados por in-tree plugins que han sido migrados a un controlador CSI, la cantidad máxima de Volúmenes será la que informe el controlador CSI.
@@ -149,6 +149,7 @@ volumeMounts:
最後に`hostPath`を設定します:
```yaml
...
volumes:
- name: audit
hostPath:
path: /etc/kubernetes/audit-policy.yaml
@@ -158,7 +159,6 @@ volumeMounts:
hostPath:
path: /var/log/audit.log
type: FileOrCreate
```
### Webhookバックエンド
@@ -3,7 +3,6 @@ layout: blog
title: "Atualizado: Perguntas frequentes (FAQ) sobre a remoção do Dockershim"
date: 2022-02-17
slug: dockershim-faq
aliases: [ '/dockershim' ]
---
**Esta é uma atualização do artigo original [FAQ sobre a depreciação do Dockershim](/blog/2020/12/02/dockershim-faq/),
+2 -2
View File
@@ -1,2 +1,2 @@
Файлы в этой диркетории были импортированы из других источников.
Не редактируйте их напрямую, вместо этого заменяйте их более новыми версиями.
Файлы в этой директории были импортированы из других источников.
Не редактируйте их напрямую, вместо этого заменяйте их более новыми версиями.
@@ -25,4 +25,4 @@
Открытость новым идеям и изученная технологическая эволюция делают Kubernetes более сильным проектом. Постоянное совершенствование, лидерство слуг, наставничество и уважение-вот основы культуры проекта Kubernetes. Лидеры сообщества Kubernetes обязаны находить, спонсировать и продвигать новых членов сообщества. Лидеры должны ожидать, что они отойдут в сторону. Члены сообщества должны ожидать, что они сделают шаг вперед.
**"Culture eats strategy for breakfast." --Peter Drucker**
**"Культура съедает стратегию на завтрак" — Питер Друкер**
@@ -2,6 +2,5 @@
title: "Кластерная Архитектура"
weight: 30
description: >
The architectural concepts behind Kubernetes.
---
Архитектурные концепции, лежащие в основе Kubernetes.
---
@@ -8,7 +8,7 @@ weight: 40
{{< feature-state state="beta" for_k8s_version="v1.11" >}}
Технологии облачной инфраструктуры позволяет запускать Kubernetes в общедоступных, частных и гибридных облаках. Kubernetes верит в автоматизированную, управляемую API инфраструктуру без жесткой связи между компонентами.
Технологии облачной инфраструктуры позволяют запускать Kubernetes в общедоступных, частных и гибридных облаках. Kubernetes верит в автоматизированную, управляемую API инфраструктуру без жесткой связи между компонентами.
{{< glossary_definition term_id="cloud-controller-manager" length="all" prepend="Диспетчер облачных контроллеров">}}
@@ -33,7 +33,7 @@ weight: 40
Контроллеры внутри диспетчера облачных контроллеров включают в себя:
### Контролер узла
### Контроллер узла
Контроллер узла отвечает за создание объектов {{< glossary_tooltip text="узла" term_id="node" >}} при создании новых серверов в вашей облачной инфраструктуре. Контроллер узла получает информацию о работающих хостах внутри вашей арендуемой инфраструктуры облачного провайдера.
Контроллер узла выполняет следующие функции:
@@ -41,13 +41,13 @@ weight: 40
1. Инициализация объектов узла для каждого сервера, которые контроллер получает через API облачного провайдера.
2. Аннотирование и маркировка объектов узла специфичной для облака информацией, такой как регион узла и доступные ему ресурсы (процессор, память и т.д.).
3. Получение имени хоста и сетевых адресов.
4. Проверка работоспособности узла. В случае, если узел перестает отвечать на запросы, этот контроллер проверяет с помощью API вашего облачного провайдера, был ли сервер деактивирован / удален / прекращен. Если узел был удален из облака, контроллер удлаяет объект узла из вашего Kubernetes кластера.
4. Проверка работоспособности узла. В случае, если узел перестает отвечать на запросы, этот контроллер проверяет с помощью API вашего облачного провайдера, был ли сервер деактивирован / удален / прекращен. Если узел был удален из облака, контроллер удаляет объект узла из вашего Kubernetes кластера.
Некоторые облачные провайдеры реализуют его разделение на контроллер узла и отдельный контроллер жизненного цикла узла.
### Контролер маршрута
### Контроллер маршрута
Контролер маршрута отвечает за соответствующую настройку маршрутов в облаке, чтобы контейнеры на разных узлах кластера Kubernetes могли взаимодействовать друг с другом.
Контроллер маршрута отвечает за соответствующую настройку маршрутов в облаке, чтобы контейнеры на разных узлах кластера Kubernetes могли взаимодействовать друг с другом.
В зависимости от облачного провайдера, контроллер маршрута способен также выделять блоки IP-адресов для сети Pod-ов.
@@ -61,7 +61,7 @@ weight: 40
### Контроллер узла {#authorization-node-controller}
Контроллер узла работает только с объектом узла. Он требует полного доступа для и изменения объектов узла.
Контроллер узла работает только с объектом узла. Он требует полного доступа на чтение и изменение объектов узла.
`v1/Node`:
@@ -73,9 +73,9 @@ weight: 40
- Watch
- Delete
### Контролер маршрута {#authorization-route-controller}
### Контроллер маршрута {#authorization-route-controller}
Контролер маршрута прослушивает создание объектов узла и соответствующим образом настраивает маршруты. Для этого требуется получить доступ к объектам узла.
Контроллер маршрута прослушивает создание объектов узла и соответствующим образом настраивает маршруты. Для этого требуется получить доступ к объектам узла.
`v1/Node`:
@@ -99,7 +99,7 @@ weight: 40
### Другие {#authorization-miscellaneous}
Реализация ядра диспетчера облачных контроллеров требует доступ для создания создания объектов событий, а для обеспечения безопасной работы требуется доступ к созданию сервисных учетных записей (ServiceAccounts).
Реализация ядра диспетчера облачных контроллеров требует доступ для создания объектов событий, а для обеспечения безопасной работы требуется доступ к созданию сервисных учетных записей (ServiceAccounts).
`v1/Event`:
@@ -111,7 +111,7 @@ weight: 40
- Create
The {{< glossary_tooltip term_id="rbac" text="RBAC" >}} ClusterRole для диспетчера облачных контроллеров выглядит так:
{{< glossary_tooltip term_id="rbac" text="RBAC" >}} ClusterRole для диспетчера облачных контроллеров выглядит так:
```yaml
apiVersion: rbac.authorization.k8s.io/v1
@@ -179,7 +179,7 @@ rules:
## {{% heading "whatsnext" %}}
[Администрирование диспетчера облачных контроллеров](/docs/tasks/administer-cluster/running-cloud-controller/#cloud-controller-manager)
содержит инструкции по запуску и управлению диспетером облачных контроллеров.
содержит инструкции по запуску и управлению диспетчером облачных контроллеров.
Хотите знать, как реализовать свой собственный диспетчер облачных контроллеров или расширить проект?
@@ -11,21 +11,21 @@ aliases:
<!-- overview -->
Этот документ каталог связь между плоскостью управления (apiserver) и кластером Kubernetes. Цель состоит в том, чтобы позволить пользователям настраивать свою установку для усиления сетевой конфигурации, чтобы кластер мог работать в ненадежной сети (или на полностью общедоступных IP-адресах облачного провайдера).
Этот документ описывает связь между плоскостью управления (apiserver) и кластером Kubernetes. Цель состоит в том, чтобы позволить пользователям настраивать свою установку для усиления сетевой конфигурации, чтобы кластер мог работать в ненадежной сети (или на полностью общедоступных IP-адресах облачного провайдера).
<!-- body -->
## Связь между плоскостью управления и узлом
В Kubernetes имеется API шаблон "hub-and-spoke". Все используемые API из узлов (или которые запускают pod-ы) завершает apiserver. Ни один из других компонентов плоскости управления не предназначен для предоставления удаленных сервисов. Apiserver настроен на прослушивание удаленных подключений через безопасный порт HTTPS. (обычно 443) с одной или несколькими включенными формами [идентификации](/docs/reference/access-authn-authz/authentication/) клиена.
В Kubernetes имеется API шаблон «ступица и спица» (hub-and-spoke). Все используемые API из узлов (или которые запускают pod-ы) завершает apiserver. Ни один из других компонентов плоскости управления не предназначен для предоставления удаленных сервисов. Apiserver настроен на прослушивание удаленных подключений через безопасный порт HTTPS (обычно 443) с одной или несколькими включенными формами [аутентификации](/docs/reference/access-authn-authz/authentication/) клиента.
Должна быть включена одна или несколько форм [идентификации](/docs/reference/access-authn-authz/authorization/), особенно если разрешены [анонимные запросы](/docs/reference/access-authn-authz/authentication/#anonymous-requests) или [service account tokens](/docs/reference/access-authn-authz/authentication/#service-account-tokens).
Должна быть включена одна или несколько форм [авторизации](/docs/reference/access-authn-authz/authorization/), особенно, если разрешены [анонимные запросы](/docs/reference/access-authn-authz/authentication/#anonymous-requests) или [ServiceAccount токены](/docs/reference/access-authn-authz/authentication/#service-account-tokens).
Узлы должны быть снабжены общедоступным корневым сертификатом для кластера, чтобы они могли безопасно подключаться к apiserver-у вместе с действительными учетными данными клиента. Хороший подход заключается в том, что учетные данные клиента, предоставляемые kubelet, имеют форму клиентского сертификата. См. Информацию о загрузке Kubelet TLS [kubelet TLS bootstrapping](/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/) для автоматической подготовки клиентских сертификатов kubelet.
Узлы должны быть снабжены публичным корневым сертификатом для кластера, чтобы они могли безопасно подключаться к apiserver-у вместе с действительными учетными данными клиента. Хороший подход заключается в том, чтобы учетные данные клиента, предоставляемые kubelet-у, имели форму клиентского сертификата. См. Информацию о загрузке kubelet TLS [kubelet TLS bootstrapping](/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/) для автоматической подготовки клиентских сертификатов kubelet.
pod-ы, которые хотят подключиться к apiserver, могут сделать это безопасно, используя учетную запись службы, чтобы Kubernetes автоматически вводил общедоступный корневой сертификат и действительный токен-носитель в pod при его создании.
Служба `kubernetes` (в пространстве имен `default`) is настроен с виртуальным IP-адресом, который перенаправляет (через kube-proxy) к endpoint HTTPS apiserver-а.
Pod-ы, которые хотят подключиться к apiserver, могут сделать это безопасно, используя ServiceAccount, чтобы Kubernetes автоматически вводил общедоступный корневой сертификат и действительный токен-носитель в pod при его создании.
Служба `kubernetes` (в пространстве имен `default`) настроена с виртуальным IP-адресом, который перенаправляет (через kube-proxy) на HTTPS эндпоинт apiserver-а.
Компоненты уровня управления также взаимодействуют с кластером apiserver-а через защищенный порт.
@@ -33,7 +33,7 @@ pod-ы, которые хотят подключиться к apiserver, мог
## Узел к плоскости управления
Существуют две пути взаимодействия от плоскости управления (apiserver) к узлам. Первый - от apiserver-а до kubelet процесса, который выполняется на каждом узле кластера. Второй - от apiserver к любому узлу, pod-у или службе через промежуточную функциональность apiserver-а.
Существуют два пути связи плоскости управления (apiserver) с узлами. Первый - от apiserver-а до kubelet процесса, который выполняется на каждом узле кластера. Второй - от apiserver к любому узлу, pod-у или службе через промежуточную функциональность apiserver-а.
### apiserver в kubelet
@@ -43,21 +43,21 @@ pod-ы, которые хотят подключиться к apiserver, мог
* Прикрепление (через kubectl) к запущенным pod-ам.
* Обеспечение функциональности переадресации портов kubelet.
Эти соединения заверщаются в kubelet в endpoint HTTPS. По умолчанию apiserver не проверяет сертификат обслуживания kubelet-ов, что делает соединение подверженным к атаке человек по середине (man-in-the-middle) и **unsafe** запущенных в ненадежных или общедоступных сетях.
Эти соединения завершаются на HTTPS эндпоинте kubelet-a. По умолчанию apiserver не проверяет сертификат обслуживания kubelet-ов, что делает соединение подверженным к атаке «человек посередине» (man-in-the-middle) и **небезопасным** к запуску в ненадежных и/или общедоступных сетях.
Для проверки этого соединения, используется флаг `--kubelet-certificate-authority` чтобы предоставить apiserver-у набор корневых (root) сертификатов для проверки сертификата обслуживания kubelet-ов.
Для проверки этого соединения используется флаг `--kubelet-certificate-authority` чтобы предоставить apiserver-у набор корневых (root) сертификатов для проверки сертификата обслуживания kubelet-ов.
Если это не возможно, используйте [SSH-тунелирование](#ssh-tunnels) между apiserver-ом и kubelet, если это необходимо во избежании подключения по ненадежной или общедоступной сети.
Если это не возможно, используйте [SSH-тунелирование](#ssh-tunnels) между apiserver-ом и kubelet, если это необходимо, чтобы избежать подключения по ненадежной или общедоступной сети.
Наконец, Должны быть включены [пудентификация или авторизация Kubelet](/docs/reference/command-line-tools-reference/kubelet-authentication-authorization/) для защиты kubelet API.
Наконец, должны быть включены [аутентификация или авторизация kubelet](/docs/reference/command-line-tools-reference/kubelet-authentication-authorization/) для защиты kubelet API.
### apiserver для узлов, pod-ов, и служб
Соединение с apiserver-ом к узлу, pod-у или службе по умолчанию осушествяляется по обычному HTTP-соединению и поэтому не проходят проверку подлиности и не шифрование. Они могут быть запущены по защищенному HTTPS-соединению, добавив префикс `https:` к имени узла, pod-а или службы в URL-адресе API, но они не будут проверять сертификат предоставленный HTTPS endpoint, также не будут предоставлять учетные данные клиента. Таким образом, хотя соединение будет зашифровано, оно не обеспечит никаких гарантий целостности. Эти соединения **are not currently safe** запущенных в ненадежных или общедоступных сетях.
Соединения с apiserver к узлу, поду или сервису по умолчанию осуществляются по-обычному HTTP-соединению и поэтому не аутентифицируются, и не шифруются. Они могут быть запущены по защищенному HTTPS-соединению, после добавления префикса `https:` к имени узла, пода или сервиса в URL-адресе API, но они не будут проверять сертификат предоставленный HTTPS эндпоинтом, как и не будут предоставлять учетные данные клиента. Таким образом, хотя соединение будет зашифровано, оно не обеспечит никаких гарантий целостности. Эти соединения **в настоящее время небезопасны** для запуска в ненадежных или общедоступных сетях.
### SSH-тунели
### SSH-туннели
Kubernetes поддерживает SSH-туннели для защиты плоскости управления узлов от путей связи. В этой конфигурации apiserver инициирует SSH-туннель для каждого узла в кластере (подключается к ssh-серверу, прослушивая порт 22) и передает весь трафикпредназначенный для kubelet, узлу, pod-у или службе через тунель. Этот тунель гарантирует, что трафик не выводиться за пределы сети, в которой работает узел.
Kubernetes поддерживает SSH-туннели для защиты плоскости управления узлов от путей связи. В этой конфигурации apiserver инициирует SSH-туннель для каждого узла в кластере (подключается к ssh-серверу, прослушивая порт 22) и передает весь трафик предназначенный для kubelet, узлу, pod-у или службе через туннель. Этот туннель гарантирует, что трафик не выводится за пределы сети, в которой работает узел.
SSH-туннели в настоящее время устарели, поэтому вы не должны использовать их, если не знаете, что делаете. Служба подключения является заменой этого канала связи.
@@ -65,6 +65,6 @@ SSH-туннели в настоящее время устарели, поэто
{{< feature-state for_k8s_version="v1.18" state="beta" >}}
В качестве замены SSH-туннелям, служба подключения обеспечивает уровень полномочие TCP для плоскости управления кластерной связи. Служба подключения состоит из двух частей: сервер подключения в сети плоскости управления и агентов подключения в сети узлов. Агенты службы подключения инициируют подключения к серверу подключения и поддерживают сетевое подключение. После включения службы подключения, весь трафик с плоскости управления на узлы проходит через эти соединения.
В качестве замены SSH-туннелям, служба подключения обеспечивает уровень полномочия TCP для плоскости управления кластерной связи. Служба подключения состоит из двух частей: сервер подключения к сети плоскости управления и агентов подключения в сети узлов. Агенты службы подключения инициируют подключения к серверу подключения и поддерживают сетевое подключение. После включения службы подключения, весь трафик с плоскости управления на узлы проходит через эти соединения.
Следуйте инструкциям [Задача службы подключения](/docs/tasks/extend-kubernetes/setup-konnectivity/) чтобы настроить службу подключения в кластере.
Следуйте инструкциям [Задача службы подключения,](/docs/tasks/extend-kubernetes/setup-konnectivity/) чтобы настроить службу подключения в кластере.
@@ -10,8 +10,8 @@ weight: 30
Вот один из примеров контура управления: термостат в помещении.
Когда вы устанавливаете температуру, это говорит термостату о вашем *желаемом состоянии*. Фактическая температура в помещении - это
*текущее состояние*. Термостат действует так, чтобы приблизить текущее состояние к желаемому состоянию, путем включения или выключения оборудования.
Когда вы устанавливаете температуру, это говорит термостату о вашем *желаемом состоянии*. Фактическая температура в помещении - это
*текущее состояние*. Термостат действует так, чтобы приблизить текущее состояние к желаемому состоянию, путем включения или выключения оборудования.
{{< glossary_definition term_id="controller" length="short">}}
@@ -27,7 +27,7 @@ weight: 30
имеют поле спецификации, которое представляет желаемое состояние. Контроллер (ы) для этого ресурса несут ответственность за приближение текущего состояния к желаемому состоянию
Контроллер может выполнить это действие сам; чаще всего в Kubernetes,
контроллер будет отправляет сообщения на
контроллер отправляет сообщения на
{{< glossary_tooltip text="сервер API" term_id="kube-apiserver" >}} которые имеют
полезные побочные эффекты. Пример этого вы можете увидеть ниже.
@@ -40,7 +40,7 @@ weight: 30
Контроллер {{< glossary_tooltip term_id="job" >}} является примером встроенного контроллера Kubernetes. Встроенные контроллеры управляют состоянием, взаимодействуя с кластером сервера API.
Задание - это ресурс Kubernetes, который запускает
{{< glossary_tooltip term_id="pod" >}}, или возможно несколько Pod-ов, которые выполняют задание и затем останавливаются.
{{< glossary_tooltip term_id="pod" >}}, или возможно несколько Pod-ов, выполняющих задачу и затем останавливающихся.
(После [планирования](/docs/concepts/scheduling-eviction/), Pod объекты становятся частью желаемого состояния для kubelet).
@@ -50,9 +50,9 @@ weight: 30
{{< glossary_tooltip text="плоскости управления" term_id="control-plane" >}}
действуют на основе информации (имеются ли новые запланированные Pod-ы для запуска), и в итоге работа завершается.
После того, как вы создадите новое задание, желаемое состояние для этого задания будет завершено. Контроллер задания приближает текущее состояние этого задания к желаемому состоянию: создает Pod-ы, которые выполняют работу, которую вы хотели для этого задания, чтобы задание было ближе к завершению.
После того как вы создадите новое задание, желаемое состояние для этого задания будет завершено. Контроллер задания приближает текущее состояние этой задачи к желаемому состоянию: создает Pod-ы, выполняющие работу, которую вы хотели для этой задачи, чтобы задание было ближе к завершению.
Контроллеры также обровляют объекты которые их настраивают.
Контроллеры также обновляют объекты которые их настраивают.
Например: как только работа выполнена для задания, контроллер задания обновляет этот объект задание, чтобы пометить его как `Завершенный`.
(Это немного похоже на то, как некоторые термостаты выключают свет, чтобы указать, что теперь ваша комната имеет установленную вами температуру).
@@ -66,20 +66,20 @@ weight: 30
Контроллеры, которые взаимодействуют с внешним состоянием, находят свое желаемое состояние с сервера API, а затем напрямую взаимодействуют с внешней системой, чтобы приблизить текущее состояние.
(На самом деле существует [контроллер](https://github.com/kubernetes/autoscaler/), который горизонтально маштабирует узлы в вашем кластере.)
(На самом деле существует [контроллер](https://github.com/kubernetes/autoscaler/), который горизонтально масштабирует узлы в вашем кластере.)
Важным моментом здесь является то, что контроллер вносит некоторые изменения, чтобы вызвать желаемое состояние, а затем сообщает текущее состояние обратно на сервер API вашего кластера. Другие контуры управления могут наблюдать за этими отчетными данными и предпринимать собственные действия.
В примере с термостатом, если в помещении очень холодно, тогда другой контроллер может также включить обогреватель для защиты от замерзания. В кластерах Kubernetes, плоскость управления косвенно работает с инструментами управления IP-адресами,службами хранения данных, API облочных провайдеров и другими службами для релизации
В примере с термостатом, если в помещении очень холодно, тогда другой контроллер может также включить обогреватель для защиты от замерзания. В кластерах Kubernetes, плоскость управления косвенно работает с инструментами управления IP-адресами, службами хранения данных, API облачных провайдеров и другими службами для реализации
[расширения Kubernetes](/docs/concepts/extend-kubernetes/).
## Желаемое против текущего состояния {#desired-vs-current}
Kubernetes использует систему вида cloud-native и способен справлятся с постоянными изменениями.
Kubernetes использует систему вида cloud-native и способен справляться с постоянными изменениями.
Ваш кластер может изменяться в любой по мере выполнения работы и контуры управления автоматически устранают сбой. Это означает, что потенциально Ваш кластер никогда не достигнет стабильного состояния.
Ваш кластер может изменяться в любой по мере выполнения работы и контуры управления автоматически устраняют сбой. Это означает, что потенциально Ваш кластер никогда не достигнет стабильного состояния.
Пока контроллеры вашего кластера работают и могут вносить полезные изменения, не имеет значения, является ли общее состояние стабильным или нет.
Пока контроллеры вашего кластера работают и могут вносить полезные изменения, не имеет значения, является ли общее состояние стабильным или нет.
## Дизайн
@@ -90,7 +90,7 @@ Kubernetes использует систему вида cloud-native и спос
{{< note >}}
Существует несколько контроллеров, которые создают или обновляют один и тот же тип объекта. За кулисами контроллеры Kubernetes следят за тем, чтобы обращать внимание только на ресурсы, связанные с их контролирующим ресурсом.
Например, у вас могут быть развертывания и задания; они оба создают Pod-ы. Контроллер заданий не удаляет Pod-ы созданные вашим развертиыванием, потому что имеется информационные ({{< glossary_tooltip term_id="label" text="метки" >}})
Например, у вас могут быть развертывания и задания; они оба создают Pod-ы. Контроллер заданий не удаляет Pod-ы созданные вашим развертыванием, потому что имеется информационные ({{< glossary_tooltip term_id="label" text="метки" >}})
которые могут быть использованы контроллерами тем самым показывая отличие Pod-ов.
{{< /note >}}
@@ -102,7 +102,7 @@ Kubernetes поставляется с набором встроенных ко
Kubernetes позволяет вам запускать устойчивую плоскость управления, так что в случае отказа одного из встроенных контроллеров работу берет на себя другая часть плоскости управления.
Вы можете найти контроллеры, которые работают вне плоскости управления, чтобы расширить Kubernetes.
Или, если вы хотите, можете написать новый контроллер самостоятельно. Вы можете запустить свой собственный контроллер виде наборов Pod-ов,
Или, если вы хотите, можете написать новый контроллер самостоятельно. Вы можете запустить свой собственный контроллер в виде наборов Pod-ов,
или внешнее в Kubernetes. Что подойдет лучше всего, будет зависеть от того, что делает этот конкретный контроллер.
@@ -23,7 +23,7 @@ weight: 50
Многие объекты в Kubernetes ссылаются друг на друга через [*ссылки владельцев*](/docs/concepts/overview/working-with-objects/owners-dependents/).
Ссылки владельцев сообщают плоскости управления какие объекты зависят от других.
Kubernetes использует ссылки владельцев, чтобы предоставить плоскости управления и другим API
клиентам, возможность очистить связанные ресурсы передудалением объекта. В большинстве случаев, Kubernetes автоматический управляет ссылками владельцев.
клиентам, возможность очистить связанные ресурсы перед удалением объекта. В большинстве случаев, Kubernetes автоматический управляет ссылками владельцев.
Владелец отличается от [меток и селекторов](/docs/concepts/overview/working-with-objects/labels/)
которые также используют некоторые ресурсы. Например, рассмотрим
@@ -36,15 +36,15 @@ Kubernetes использует ссылки владельцев, чтобы п
{{< note >}}
Ссылки на владельцев перекрестных пространств имен запрещены по дизайну.
Зависимости пространства имен могут указывать на область действия кластера или владельцев пространства имен.
Владелец пространства имен **должен** быть в том же пространстве имен что и зависимости.
Если это не возможно, cсылка владельца считается отсутствующей и зависимый объект подлежит удалению, как только будет проверено отсутствие всех владельцев.
Владелец пространства имен **должен** быть в том же пространстве имен, что и зависимости.
Если это не возможно, ссылка владельца считается отсутствующей и зависимый объект подлежит удалению, как только будет проверено отсутствие всех владельцев.
Зависимости области действия кластер может указывать только владельцев области действия кластера.
В версии v1.20+, если зависимость с областью действия кластера указывает на пространство имен как владелец,
тогда он рассматривается как имеющий неразрешимую ссылку на владельца и не может быть обработан сборщиком мусора.
В версии v1.20+, если сборщик мусора обнаружит недопустимое перекрестное пространство имен `ownerReference`,
или зависящие от облости действия кластера `ownerReference` ссылка на тип пространства имен, предупреждающее событие с причиной `OwnerRefInvalidNamespace` и `involvedObject` сообщающеся о не действительной зависимости.
или зависящие от области действия кластера `ownerReference` ссылка на тип пространства имен, предупреждающее событие с причиной `OwnerRefInvalidNamespace` и `involvedObject` сообщающее о недействительной зависимости.
Вы можете проверить наличие такого рода событий, выполнив `kubectl get events -A --field-selector=reason=OwnerRefInvalidNamespace`.
{{< /note >}}
@@ -52,22 +52,22 @@ Kubernetes использует ссылки владельцев, чтобы п
Kubernetes проверяет и удаляет объекты, на которые больше нет ссылок владельцев, так же как и pod-ов, оставленных после удаления ReplicaSet. Когда Вы удаляете объект, вы можете контролировать автоматический ли Kubernetes удаляет зависимые объекты автоматически в процессе вызова *каскадного удаления*. Существует два типа каскадного удаления, а именно:
* Каскадное удалени Foreground
* Каскадное удаление Foreground
* Каскадное удаление Background
Вы так же можете управлять как и когда сборщик мусора удаляет ресурсы, на которые ссылаются владельцы с помощью Kubernetes {{<glossary_tooltip text="finalizers" term_id="finalizer">}}.
### Каскадное удалени Foreground {#foreground-deletion}
### Каскадное удаление Foreground {#foreground-deletion}
В Каскадном удалени Foreground, объект владельца, который вы удаляете, сначало переходить в состояние *в процессе удаления*. В этом состоянии с объектом-владельцем происходить следующее:
В Каскадном удалении Foreground, объект владельца, который вы удаляете, сначала переходить в состояние *в процессе удаления*. В этом состоянии с объектом-владельцем происходить следующее:
* Сервер Kubernetes API устанавливает полю объекта `metadata.deletionTimestamp`
время, когда объект был помечен для удаления.
* Сервер Kubernetes API так же устанавливает метку `metadata.finalizers`для поля
`foregroundDeletion`.
* Объект остается видимым блогодоря Kubernetes API пока процесс удаления не завершиться
* Объект остается видимым благодаря Kubernetes API пока процесс удаления не завершиться
После того, как владелец объекта переходит в состояние прогресса удаления, контроллер удаляет зависимые объекты. После удаления всех зависимых объектов, контроллер удаляет объект владельца. На этом этапе, объект больше не отображается в Kubernetes API.
После того как владелец объекта переходит в состояние прогресса удаления, контроллер удаляет зависимые объекты. После удаления всех зависимых объектов, контроллер удаляет объект владельца. На этом этапе, объект больше не отображается в Kubernetes API.
Во время каскадного удаления foreground, единственным зависимым, которые блокируют удаления владельца, являются те, у кого имеется поле `ownerReference.blockOwnerDeletion=true`.
Чтобы узнать больше. Смотрите [Использование каскадного удаления foreground](/docs/tasks/administer-cluster/use-cascading-deletion/#use-foreground-cascading-deletion).
@@ -80,16 +80,16 @@ Kubernetes проверяет и удаляет объекты, на котор
### Осиротевшие зависимости
Когда Kubernetes удаляет владельца объекта, оставшиеся зависимости называются *осиротевшыми* объектами. По умолчанию, Kubernetes удаляет зависимые объекты. Чтобы узнать, как переопределить это повидение смотрите [Удаление объектов владельца и осиротевших зависимостей](/docs/tasks/administer-cluster/use-cascading-deletion/#set-orphan-deletion-policy).
Когда Kubernetes удаляет владельца объекта, оставшиеся зависимости называются *осиротевшими* объектами. По умолчанию, Kubernetes удаляет зависимые объекты. Чтобы узнать, как переопределить это поведение смотрите [Удаление объектов владельца и осиротевших зависимостей](/docs/tasks/administer-cluster/use-cascading-deletion/#set-orphan-deletion-policy).
## Сбор мусора из неиспользуемых контейнеров и изобробразов {#containers-images}
## Сбор мусора из неиспользуемых контейнеров и изображений {#containers-images}
{{<glossary_tooltip text="kubelet" term_id="kubelet">}} выполняет сбор мусора для неиспользуемых образов каждые пять минут и для неиспользуемых контейнеров каждую минуту. Вам следует избегать использования внешних инструментов для сборки мусора, так как они могут
нарушить поведение kubelet и удалить контейнеры, которые должны существовать.
Чтобы настроить параметры для сборшика мусора для неиспользуемого контейнера и сборки мусора образа, подстройте
Чтобы настроить параметры для сборщика мусора для неиспользуемого контейнера и сборки мусора образа, подстройте
kubelet использую [конфигурационный файл](/docs/tasks/administer-cluster/kubelet-config-file/)
и измените параметры, связанные со сборшиком мусора используя тип ресурса
и измените параметры, связанные со сборщиком мусора используя тип ресурса
[`KubeletConfiguration`](/docs/reference/config-api/kubelet-config.v1beta1/#kubelet-config-k8s-io-v1beta1-KubeletConfiguration).
### Жизненный цикл контейнерных образов Container image lifecycle
@@ -99,19 +99,19 @@ Kubernetes управляет жизненным циклом всех обра
* `HighThresholdPercent`
* `LowThresholdPercent`
Использование диска выше настроенного значения `HighThresholdPercent` запускает сборку мусора, которая удаляет образы в порядке основанном на последнем использовании, начиная с самого старого. kubelet удлаяет образы до тех пор, пока использование диска не достигнет значения `LowThresholdPercent`.
Использование диска выше настроенного значения `HighThresholdPercent` запускает сборку мусора, которая удаляет образы в порядке основанном на последнем использовании, начиная с самого старого. Kubelet удаляет образы до тех пор, пока использование диска не достигнет значения `LowThresholdPercent`.
### Сборщик мусора контейнерных образов {#container-image-garbage-collection}
kubelet собирает не используемые контейнеры на основе следующих переменных, которые вы можете определить:
Kubelet собирает не используемые контейнеры на основе следующих переменных, которые вы можете определить:
* `MinAge`: минимальный возраст, при котором kubelet может начать собирать мусор контейнеров. Отключить, установив значение `0`.
* `MaxPerPodContainer`: максимальное количество некативныз контейнеров, которое может быть у каджой пары Pod-ов. Отключить, установив значение меньше чем `0`.
* `MaxPerPodContainer`: максимальное количество неактивных контейнеров, которое может быть у каждой пары Pod-ов. Отключить, установив значение меньше чем `0`.
* `MaxContainers`: максимальное количество не используемых контейнеров, которые могут быть в кластере. Отключить, установив значение меньше чем `0`.
В дополнение к этим переменным, kubelet собирает неопознанные и удаленные контейнеры, обычно начиная с самого старого.
`MaxPerPodContainer` и `MaxContainer` могут потенциально конфликтовать друг с другом в ситуациях, когда требуется максимальное количество контейнеров в Pod-е (`MaxPerPodContainer`) выйдет за пределы допустимого общего количества глобальных не используемых контейнеров (`MaxContainers`). В этой ситуации kubelet регулирует `MaxPodPerContainer` для устранения конфликта. наихудшим сценарием было бы понизить `MaxPerPodContainer` да `1` и изгнать самые старые контейнеры.
`MaxPerPodContainer` и `MaxContainer` могут потенциально конфликтовать друг с другом в ситуациях, когда требуется максимальное количество контейнеров в Pod-е (`MaxPerPodContainer`) выйдет за пределы допустимого общего количества глобальных не используемых контейнеров (`MaxContainers`). В этой ситуации kubelet регулирует `MaxPodPerContainer` для устранения конфликта. Наихудшим сценарием было бы понизить `MaxPerPodContainer` да `1` и изгнать самые старые контейнеры.
Кроме того, владельцы контейнеров в pod-е могут быть удалены, как только они становятся старше чем `MinAge`.
{{<note>}}
@@ -120,7 +120,7 @@ Kubelet собирает мусор только у контейнеров, ко
## Настройка сборщик мусора {#configuring-gc}
Вы можете настроить сборку мусора ресурсов, настроив параметры, специфичные для контроллеров, управляющих этими ресурсами. В последующих страницах показанно, как настроить сборку мусора:
Вы можете настроить сборку мусора ресурсов, настроив параметры, специфичные для контроллеров, управляющих этими ресурсами. В последующих страницах показано, как настроить сборку мусора:
* [Настройка каскадного удаления объектов Kubernetes](/docs/tasks/administer-cluster/use-cascading-deletion/)
* [Настройка очистки завершенных заданий](/docs/concepts/workloads/controllers/ttlafterfinished/)
+27 -27
View File
@@ -32,7 +32,7 @@ Kubernetes запускает ваши приложения, помещая ко
1. Kubelet на узле саморегистрируется в плоскости управления
2. Вы или другой пользователь вручную добавляете объект Узла
После того, как вы создадите объект Узла или kubelet на узле самозарегистируется,
После того как вы создадите объект Узла или kubelet на узле самозарегистируется,
плоскость управления проверяет, является ли новый объект Узла валидным (правильным). Например, если вы
попробуете создать Узел при помощи следующего JSON манифеста:
@@ -50,9 +50,9 @@ Kubernetes запускает ваши приложения, помещая ко
```
Kubernetes создает внутри себя объект Узла (представление). Kubernetes проверяет,
что kubelet зарегистрировался на API сервере, который совпадает с значением поля `metadata.name` Узла.
что kubelet зарегистрировался на API сервере, который совпадает со значением поля `metadata.name` Узла.
Если узел здоров (если все необходимые сервисы запущены),
он имеет право на запуск Пода. В противном случае, этот узел игнорируется для любой активности кластера
он имеет право на запуск Пода. В противном случае этот узел игнорируется для любой активности кластера
до тех пор, пока он не станет здоровым.
{{< note >}}
@@ -62,13 +62,13 @@ Kubernetes сохраняет объект для невалидного Узл
остановить проверку доступности узла.
{{< /note >}}
Имя объекта Узла дожно быть валидным
Имя объекта Узла должно быть валидным
[именем поддомена DNS](/ru/docs/concepts/overview/working-with-objects/names#имена-поддоменов-dns).
### Саморегистрация Узлов
Когда kubelet флаг `--register-node` имеет значение _true_ (по умолчанию), то kubelet будет пытаться
зарегистрировать себя на API сервере. Это наиболее предпочтительная модель, используемая большиством дистрибутивов.
зарегистрировать себя на API сервере. Это наиболее предпочтительная модель, используемая большинством дистрибутивов.
Для саморегистрации kubelet запускается со следующими опциями:
@@ -94,16 +94,16 @@ kubelet'ы имеют право только создавать/изменят
Когда вы хотите создать объекты Узла вручную, установите kubelet флаг `--register-node=false`.
Вы можете изменять объекты Узла независимо от настройки `--register-node`.
Например, вы можете установить метки на существующем Узле или пометить его неназначаемым.
Например, вы можете установить метки на существующем Узле или пометить его не назначаемым.
Вы можете использовать метки на Узлах в сочетании с селекторами узла на Подах для управления планированием.
Например, вы можете ограничить Под иметь право на запуск только на группе доступных узлов.
Например, вы можете ограничить Под, иметь право на запуск только на группе доступных узлов.
Маркировка узла как неназначаемого предотвращает размещение планировщиком новых подов на этом Узле,
Маркировка узла как не назначаемого предотвращает размещение планировщиком новых подов на этом Узле,
но не влияет на существующие Поды на Узле. Это полезно в качестве
подготовительного шага перед перезагрузкой узла или другим обслуживанием.
Чтобы отметить Узел неназначемым, выполните:
Чтобы отметить Узел не назначаемым, выполните:
```shell
kubectl cordon $NODENAME
@@ -111,7 +111,7 @@ kubectl cordon $NODENAME
{{< note >}}
Поды, являющиеся частью {{< glossary_tooltip term_id="daemonset" >}} допускают
запуск на неназначаемом Узле. DaemonSets обычно обеспечивает локальные сервисы узла,
запуск на не назначаемом Узле. DaemonSets обычно обеспечивает локальные сервисы узла,
которые должны запускаться на Узле, даже если узел вытесняется для запуска приложений.
{{< /note >}}
@@ -157,7 +157,7 @@ kubectl describe node <insert-node-name-here>
{{< note >}}
Если вы используете инструменты командной строки для вывода сведений об блокированном узле,
то Условие включает `SchedulingDisabled`. `SchedulingDisabled` не является Условием в Kubernetes API;
вместо этого блокированные узлы помечены как Неназначемые в их спецификации.
вместо этого блокированные узлы помечены как Не назначаемые в их спецификации.
{{< /note >}}
Состояние узла представлено в виде JSON объекта. Например, следующая структура описывает здоровый узел:
@@ -203,8 +203,8 @@ kubectl describe node <insert-node-name-here>
Описывает ресурсы, доступные на узле: CPU, память и максимальное количество подов,
которые могут быть запланированы на узле.
Поля в блоке capasity указывают общее количество ресурсов, которые есть на Узле.
Блок allocatable указывает количество ресурсовна Узле,
Поля в блоке capacity указывают общее количество ресурсов, которые есть на Узле.
Блок allocatable указывает количество ресурсов на Узле,
которые доступны для использования обычными Подами.
Вы можете прочитать больше о емкости и выделяемых ресурсах, изучая, как [зарезервировать вычислительные ресурсы](/docs/tasks/administer-cluster/reserve-compute-resources/#node-allocatable) на Узле.
@@ -212,7 +212,7 @@ kubectl describe node <insert-node-name-here>
### Информация (Info)
Описывает общую информацию об узле, такую как версия ядра, версия Kubernetes (версии kubelet и kube-proxy), версия Docker (если используется) и название ОС.
Эта информация соберается Kubelet'ом на узле.
Эта информация собирается Kubelet'ом на узле.
### Контроллер узла
@@ -247,16 +247,16 @@ ConditionUnknown, когда узел становится недоступны
[Lease объект](/docs/reference/generated/kubernetes-api/{{< latest-version >}}/#lease-v1-coordination-k8s-io).
Каждый узел имеет связанный с ним Lease объект в `kube-node-lease`
{{< glossary_tooltip term_id="namespace" text="namespace">}}.
Lease - это легковестный ресурс, который улучшает производительность
Lease - это легковесный ресурс, который улучшает производительность
сердцебиений узла при масштабировании кластера.
Kubelet отвечает за создание и обновление `NodeStatus` и Lease объекта.
Kubelet отвечает за создание и обновление `NodeStatus` и Lease объекта.
- Kubelet обновляет `NodeStatus` либо когда происходит изменение статуса,
либо если в течение настронного интервала обновления не было. По умолчанию
либо если в течение настроенного интервала обновления не было. По умолчанию
интервал для обновлений `NodeStatus` составляет 5 минут (намного больше,
чем 40-секундный стандартный таймаут для недоступных узлов).
- Kubelet созадет и затем обновляет свой Lease объект каждый 10 секунд
- Kubelet создает и затем обновляет свой Lease объект каждый 10 секунд
(интервал обновления по умолчанию). Lease обновления происходят независимо от
`NodeStatus` обновлений. Если обновление Lease завершается неудачно,
kubelet повторяет попытку с экспоненциальным откатом, начинающимся с 200 миллисекунд и ограниченным 7 секундами.
@@ -265,7 +265,7 @@ Kubelet отвечает за создание и обновление `NodeStat
В большинстве случаев контроллер узла ограничивает скорость выселения
до `--node-eviction-rate` (по умолчанию 0,1) в секунду, что означает,
что он не выселяет поды с узлов быстрее чем c 1 узела в 10 секунд.
что он не выселяет поды с узлов быстрее чем с одного узла в 10 секунд.
Поведение выселения узла изменяется, когда узел в текущей зоне доступности
становится нездоровым. Контроллер узла проверяет, какой процент узлов в зоне
@@ -288,26 +288,26 @@ Kubelet отвечает за создание и обновление `NodeStat
выселяет поды с нормальной скоростью `--node-eviction-rate`. Крайний случай - когда все зоны
полностью нездоровы (т.е. в кластере нет здоровых узлов). В таком случае
контроллер узла предполагает, что существует некоторая проблема с подключением к мастеру,
и останавеливает все выселения, пока какое-нибудь подключение не будет восстановлено.
и останавливает все выселения, пока какое-нибудь подключение не будет восстановлено.
Контроллер узла также отвечает за выселение подов, запущенных на узлах с
`NoExecute` ограничениями, за исключением тех подов, которые сопротивляются этим ограничениям.
Контроллер узла так же добавляет {{< glossary_tooltip text="ограничения" term_id="taint" >}}
соотвествующие проблемам узла, таким как узел недоступен или не готов. Это означает,
соответствующие проблемам узла, таким как узел недоступен или не готов. Это означает,
что планировщик не будет размещать поды на нездоровых узлах.
{{< caution >}}
`kubectl cordon` помечает узел как 'неназначемый', что имеет побочный эфект от контроллера сервисов,
`kubectl cordon` помечает узел как 'не назначаемый', что имеет побочный эффект от контроллера сервисов,
удаляющего узел из любых списков целей LoadBalancer узла, на которые он ранее имел право,
эффектино убирая входящий трафик балансировщика нагрузки с блокированного узла(ов).
эффективно убирая входящий трафик балансировщика нагрузки с блокированного узла(ов).
{{< /caution >}}
### Емкость узла
Объекты узла отслеживают информацию о емкости ресурсов узла (например,
объем доступной памяти и количество CPU).
Узлы, которые [самостоятельно зарегистировались](#саморегистрация-узлов) сообщают
о свое емкости во время регистрации. Если вы [вручную](#ручное-администрирование-узла)
Узлы, которые [самостоятельно зарегистрировались](#саморегистрация-узлов), сообщают
о своей емкости во время регистрации. Если вы [вручную](#ручное-администрирование-узла)
добавляете узел, то вам нужно задать информацию о емкости узла при его добавлении.
{{< glossary_tooltip text="Планировщик" term_id="kube-scheduler" >}} Kubernetes гарантирует,
@@ -318,7 +318,7 @@ Kubelet отвечает за создание и обновление `NodeStat
а также исключает любые процессы, запущенные вне контроля kubelet.
{{< note >}}
Если вы явно хотите зарезервировать ресурсы для процессов, не связанныз с Подами, смотрите раздел
Если вы явно хотите зарезервировать ресурсы для процессов, не связанных с Подами, смотрите раздел
[зарезервировать ресурсы для системных демонов](/docs/tasks/administer-cluster/reserve-compute-resources/#system-reserved).
{{< /note >}}
@@ -339,4 +339,4 @@ Kubelet отвечает за создание и обновление `NodeStat
* Подробнее про [Узлы](https://git.k8s.io/community/contributors/design-proposals/architecture/architecture.md#the-kubernetes-node)
of the architecture design document.
* Подробнее про [ограничения и допуски](/docs/concepts/configuration/taint-and-toleration/).
* Подробнее про [автомаштабирование кластера](/docs/tasks/administer-cluster/cluster-management/#cluster-autoscaling).
* Подробнее про [авто масштабирование кластера](/docs/tasks/administer-cluster/cluster-management/#cluster-autoscaling).
@@ -11,7 +11,7 @@ no_list: true
---
<!-- overview -->
Обзор администрирования кластера предназначен для всех, кто создает или администрирует кластер Kubernetes. Это предполагает некоторое знакомство с основными [концепциями] (/docs/concepts/) Kubernetes.
Обзор администрирования кластера предназначен для всех, кто создает или администрирует кластер Kubernetes. Это предполагает некоторое знакомство с основными [концепциями](/docs/concepts/) Kubernetes.
<!-- body -->
@@ -19,19 +19,19 @@ no_list: true
См. Руководства в разделе [настройка](/docs/setup/) для получения примеров того, как планировать, устанавливать и настраивать кластеры Kubernetes. Решения, перечисленные в этой статье, называются *distros*.
{{< note >}}
{{< note >}}
не все дистрибутивы активно поддерживаются. Выбирайте дистрибутивы, протестированные с последней версией Kubernetes.
{{< /note >}}
Прежде чем выбрать руководство, вот некоторые соображения:
- Вы хотите опробовать Kubernetes на вашем компьюторе или собрать многоузловой кластер высокой доступности? Выбирайте дистрибутивы, наиболее подходящие для ваших нужд.
- будете ли вы использовать **размещенный кластер Kubernetes**, такой как [Google Kubernetes Engine](https://cloud.google.com/kubernetes-engine/) или **разместите собственный кластер**?
- Будет ли ваш кластер **в помещений** или **в облаке (IaaS)**? Kubernetes не поддерживает напрямую гибридные кластеры. Вместо этого вы можете настроить несколько кластеров.
- **Если вы будете настроаивать Kubernetes в помещений (локально)**, подумайте, какая [сетевая модель](/docs/concepts/cluster-administration/networking/) подходит лучше всего.
- Будете ли вы запускать Kubernetes на **оборудований "bare metal"** или на **вирутальных машинах (VMs)**?
- Вы хотите **запустить кластер** или планируете **активно разворачивать код проекта Kubernetes**? В последнем случае выберите активно разрабатываемый дистрибутив. Некоторые дистрибутивы используют только двоичные выпуски, но предлагают болле широкий выбор.
- Ознакомьтесь с [компонентами](/docs/concepts/overview/components/) необходивые для запуска кластера.
- Вы хотите опробовать Kubernetes на вашем компьютере или собрать много узловой кластер высокой доступности? Выбирайте дистрибутивы, наиболее подходящие для ваших нужд.
- Будете ли вы использовать **размещенный кластер Kubernetes**, такой, как [Google Kubernetes Engine](https://cloud.google.com/kubernetes-engine/) или **разместите собственный кластер**?
- Будет ли ваш кластер **в помещении** или **в облаке (IaaS)**? Kubernetes не поддерживает напрямую гибридные кластеры. Вместо этого вы можете настроить несколько кластеров.
- **Если вы будете настраивать Kubernetes в помещении (локально)**, подумайте, какая [сетевая модель](/docs/concepts/cluster-administration/networking/) подходит лучше всего.
- Будете ли вы запускать Kubernetes на **оборудований "bare metal"** или на **виртуальных машинах (VMs)**?
- Вы хотите **запустить кластер** или планируете **активно разворачивать код проекта Kubernetes**? В последнем случае выберите активно разрабатываемый дистрибутив. Некоторые дистрибутивы используют только двоичные выпуски, но предлагают более широкий выбор.
- Ознакомьтесь с [компонентами](/docs/concepts/overview/components/) необходимые для запуска кластера.
## Управление кластером
@@ -54,7 +54,7 @@ no_list: true
* [Использование контроллеров допуска](/docs/reference/access-authn-authz/admission-controllers/) explains plug-ins which intercepts requests to the Kubernetes API server after authentication and authorization.
* [Использование Sysctls в кластере Kubernetes](/docs/tasks/administer-cluster/sysctl-cluster/) описывает администратору, как использовать sysctlинструмент командной строки для установки параметров ядра.
* [Использование Sysctls в кластере Kubernetes](/docs/tasks/administer-cluster/sysctl-cluster/) описывает администратору, как использовать sysctl инструмент командной строки для установки параметров ядра.
* [Аудит](/docs/tasks/debug-application-cluster/audit/) описывает, как взаимодействовать с журналами аудита Kubernetes.
@@ -13,33 +13,33 @@ content_type: concept
<!-- body -->
## Сеть и сетевыя политика
## Сеть и сетевая политика
* [ACI](https://www.github.com/noironetworks/aci-containers) обеспечивает интегрированную сеть контейнеров и сетевую безопасность с помощью Cisco ACI.
* [Antrea](https://antrea.io/) работает на уровне 3, обеспечивая сетевые службы и службы безопасности для Kubernetes, используя Open vSwitch в качестве уровня сетевых данных.
* [Calico](https://docs.projectcalico.org/latest/introduction/) Calico поддерживает гибкий набор сетевых опций, поэтому вы можете выбрать наиболее эффективный вариант для вашей ситуации, включая сети без оверлея и оверлейные сети, с или без BGP. Calico использует тот же механизм для обеспечения соблюдения сетевой политики для хостов, модулей и (при использовании Istio и Envoy) приложений на уровне сервисной сети (mesh layer).
* [Canal](https://github.com/tigera/canal/tree/master/k8s-install) объединяет Flannel и Calico, обеспечивая сеть и сетевую политик.
* [Canal](https://github.com/tigera/canal/tree/master/k8s-install) объединяет Flannel и Calico, обеспечивая сеть и сетевую политику.
* [Cilium](https://github.com/cilium/cilium) - это плагин сети L3 и сетевой политики, который может прозрачно применять политики HTTP/API/L7. Поддерживаются как режим маршрутизации, так и режим наложения/инкапсуляции, и он может работать поверх других подключаемых модулей CNI.
* [CNI-Genie](https://github.com/Huawei-PaaS/CNI-Genie) позволяет Kubernetes легко подключаться к выбору плагинов CNI, таких как Calico, Canal, Flannel, Romana или Weave.
* [Contrail](https://www.juniper.net/us/en/products-services/sdn/contrail/contrail-networking/), основан на [Tungsten Fabric](https://tungsten.io), представляет собой платформу для виртуализации мультиоблачных сетей с открытым исходным кодом и управления политиками. Contrail и Tungsten Fabric are интегрированы с системами оркестровки, такими как Kubernetes, OpenShift, OpenStack и Mesos, и обеспечивают режимы изоляции для виртуальных машин, контейнеров/pod-ов и рабочих нагрузок без операционной системы.
* [Contrail](https://www.juniper.net/us/en/products-services/sdn/contrail/contrail-networking/), основан на [Tungsten Fabric](https://tungsten.io), представляет собой платформу для виртуализации мультиоблачных сетей с открытым исходным кодом и управления политиками. Contrail и Tungsten Fabric интегрированы с системами оркестрации, такими как Kubernetes, OpenShift, OpenStack и Mesos, и обеспечивают режимы изоляции для виртуальных машин, контейнеров/подов и рабочих нагрузок без операционной системы.
* [Flannel](https://github.com/flannel-io/flannel#deploying-flannel-manually) - это поставщик оверлейной сети, который можно использовать с Kubernetes.
* [Knitter](https://github.com/ZTE/Knitter/) - это плагин для поддержки нескольких сетевых интерфейсов Kubernetes pod-ов.
* Multus - это плагин Multi для поддержки нексольких сетейв Kubernetes для поддержки всех CNI плагинов (наприме: Calico, Cilium, Contiv, Flannel), в дополнение к рабочим нагрузкам основанных на SRIOV, DPDK, OVS-DPDK и VPP в Kubernetes.
* [OVN-Kubernetes](https://github.com/ovn-org/ovn-kubernetes/) - это сетевой провайдер для Kubernetes основанный на [OVN (Open Virtual Network)](https://github.com/ovn-org/ovn/), реализация виртуалной сети a появившейся в результате проекта Open vSwitch (OVS). OVN-Kubernetes обеспечивает сетевую реализацию на основе наложения для Kubernetes, включая реализацию балансировки нагрузки и сетевой политики на основе OVS.
* [OVN4NFV-K8S-Plugin](https://github.com/opnfv/ovn4nfv-k8s-plugin) - это подключаемый модуль контроллера CNI на основе OVN для обеспечения облачной цепочки сервисных функций (SFC), несколько наложеных сетей OVN, динамического создания подсети, динамического создания виртуальных сетей, сети поставщика VLAN, сети прямого поставщика и подключаемого к другим Multi Сетевые плагины, идеально подходящие для облачных рабочих нагрузок на периферии в сети с несколькими кластерами.
* [Knitter](https://github.com/ZTE/Knitter/) - это плагин для поддержки нескольких сетевых интерфейсов Kubernetes подов.
* [Multus](https://github.com/k8snetworkplumbingwg/multus-cni) - это плагин Multi для работы с несколькими сетями в Kubernetes, который поддерживает большинство самых популярных [CNI](https://github.com/containernetworking/cni) (например: Calico, Cilium, Contiv, Flannel), в дополнение к рабочим нагрузкам основанных на SRIOV, DPDK, OVS-DPDK и VPP в Kubernetes.
* [OVN-Kubernetes](https://github.com/ovn-org/ovn-kubernetes/) - это сетевой провайдер для Kubernetes основанный на [OVN (Open Virtual Network)](https://github.com/ovn-org/ovn/), реализация виртуальной сети, появившийся в результате проекта Open vSwitch (OVS). OVN-Kubernetes обеспечивает сетевую реализацию на основе наложения для Kubernetes, включая реализацию балансировки нагрузки и сетевой политики на основе OVS.
* [OVN4NFV-K8S-Plugin](https://github.com/opnfv/ovn4nfv-k8s-plugin) - это подключаемый модуль контроллера CNI на основе OVN для обеспечения облачной цепочки сервисных функций (SFC), несколько наложенных сетей OVN, динамического создания подсети, динамического создания виртуальных сетей, сети поставщика VLAN, сети прямого поставщика и подключаемого к другим Multi Сетевые плагины, идеально подходящие для облачных рабочих нагрузок на периферии в сети с несколькими кластерами.
* [NSX-T](https://docs.vmware.com/en/VMware-NSX-T/2.0/nsxt_20_ncp_kubernetes.pdf) плагин для контейнера (NCP) обеспечивающий интеграцию между VMware NSX-T и контейнерами оркестраторов, таких как Kubernetes, а так же интеграцию между NSX-T и контейнеров на основе платформы CaaS/PaaS, таких как Pivotal Container Service (PKS) и OpenShift.
* [Nuage](https://github.com/nuagenetworks/nuage-kubernetes/blob/v5.1.1-1/docs/kubernetes-1-installation.rst) - эта платформа SDN, которая обеспечивает сетевое взаимодействие на основе политик между Kubernetes Pod-ами и не Kubernetes окружением с отображением и мониторингом безопасности.
* [Romana](https://romana.io) - это сетевое решение уровня 3 для pod сетей, которое также поддерживает [NetworkPolicy API](/docs/concepts/services-networking/network-policies/). Подробности установки Kubeadm доступны [здесь](https://github.com/romana/romana/tree/master/containerize).
* [Weave Net](https://www.weave.works/docs/net/latest/kubernetes/kube-addon/) обеспечивает сетевуюи политику сетей, будет работать в сетевого раздела и не требует внешней базы данных.
* [Nuage](https://github.com/nuagenetworks/nuage-kubernetes/blob/v5.1.1-1/docs/kubernetes-1-installation.rst) - эта платформа SDN, которая обеспечивает сетевое взаимодействие на основе политик между Kubernetes подами и не Kubernetes окружением, с отображением и мониторингом безопасности.
* [Romana](https://romana.io) - это сетевое решение уровня 3 для сетей подов, которое также поддерживает [NetworkPolicy API](/docs/concepts/services-networking/network-policies/). Подробности установки Kubeadm доступны [здесь](https://github.com/romana/romana/tree/master/containerize).
* [Weave Net](https://www.weave.works/docs/net/latest/kubernetes/kube-addon/) предоставляет сеть и обеспечивает сетевую политику, будет работать на обеих сторонах сетевого раздела и не требует внешней базы данных.
## Обнаружение служб
* [CoreDNS](https://coredns.io) - это гибкий, расширяемый DNS-сервер, который может быть [установлен](https://github.com/coredns/deployment/tree/master/kubernetes) в качестве внутрикластерного DNS для pod-ов.
* [CoreDNS](https://coredns.io) - это гибкий, расширяемый DNS-сервер, который может быть [установлен](https://github.com/coredns/deployment/tree/master/kubernetes) в качестве внутрикластерного DNS для подов.
## Визуализация и контроль
* [Dashboard](https://github.com/kubernetes/dashboard#kubernetes-dashboard) - это веб-интерфейс панели инструментов для Kubernetes.
* [Weave Scope](https://www.weave.works/documentation/scope-latest-installing/#k8s) - это инструмент для графической визуализации ваших контейнеров, pod-ов, сервисов и т.д. Используйте его вместе с [учетной записью Weave Cloud](https://cloud.weave.works/) или разместите пользовательский интерфейс самостоятельно.
* [Weave Scope](https://www.weave.works/documentation/scope-latest-installing/#k8s) - это инструмент для графической визуализации ваших контейнеров, подов, сервисов и т.д. Используйте его вместе с [учетной записью Weave Cloud](https://cloud.weave.works/) или разместите пользовательский интерфейс самостоятельно.
## Инфраструктура
@@ -49,4 +49,4 @@ content_type: concept
В устаревшем каталоге [cluster/addons](https://git.k8s.io/kubernetes/cluster/addons) задокументировано несколько других дополнений.
Ссылки на те, в хорошем состоянии, должны быть здесь. PR приветствуются!
Ссылки на те, в хорошем состоянии, должны быть здесь. Пул реквесты приветствуются!
@@ -36,7 +36,7 @@ Kubernetes как таковой состоит из множества комп
Все детали API документируется с использованием [OpenAPI](https://www.openapis.org/).
Начиная с Kubernetes 1.10, API-сервер Kubernetes основывается на спецификации OpenAPI через конечную точку `/openapi/v2`.
Нужный формат устанавливается через HTTP-заголовоки:
Нужный формат устанавливается через HTTP-заголовки:
Заголовок | Возможные значения
------ | ---------------
@@ -61,11 +61,11 @@ GET /swagger-2.0.0.pb-v1.gz | GET /openapi/v2 **Accept**: application/com.github
Чтобы упростить удаления полей или изменение ресурсов, Kubernetes поддерживает несколько версий API, каждая из которых доступна по собственному пути, например, `/api/v1` или `/apis/extensions/v1beta1`.
Мы выбрали версионирование API, а не конкретных ресурсов или полей, чтобы API отражал четкое и согласованное представление о системных ресурсах и их поведении, а также, чтобы разграничивать API, которые уже не поддерживаются и/или находятся в экспериментальной стадии. Схемы сериализации JSON и Protobuf следуют одним и тем же правилам по внесению изменений в схему, поэтому описание ниже охватывают оба эти формата.
Мы выбрали версионирование API, а не конкретных ресурсов или полей, чтобы API отражал четкое и согласованное представление о системных ресурсах и их поведении, а также, чтобы разграничивать API, которые уже не поддерживаются и/или находятся в экспериментальной стадии. Схемы сериализации JSON и Protobuf следуют одним и тем же правилам по внесению изменений в схему, поэтому описание ниже охватывают оба эти формата.
Обратите внимание, что версиоирование API и программное обеспечение косвенно связаны друг с другом. [Предложение по версионированию API и новых выпусков](https://git.k8s.io/community/contributors/design-proposals/release/versioning.md) описывает, как связаны между собой версии API с версиями программного обеспечения.
Обратите внимание, что версионирование API и программное обеспечение косвенно связаны друг с другом. [Предложение по версионированию API и новых выпусков](https://git.k8s.io/community/contributors/design-proposals/release/versioning.md) описывает, как связаны между собой версии API с версиями программного обеспечения.
Разные версии API имеют характеризуются разной уровнем стабильностью и поддержкой. Критерии каждого уровня более подробно описаны в [документации изменений API](https://git.k8s.io/community/contributors/devel/sig-architecture/api_changes.md#alpha-beta-and-stable-versions). Ниже приводится краткое изложение:
Разные версии API характеризуются разными уровнями стабильности и поддержки. Критерии каждого уровня более подробно описаны в [документации изменений API](https://git.k8s.io/community/contributors/devel/sig-architecture/api_changes.md#alpha-beta-and-stable-versions). Ниже приводится краткое изложение:
- Альфа-версии:
- Названия версий включают надпись `alpha` (например, `v1alpha1`).
@@ -79,7 +79,7 @@ GET /swagger-2.0.0.pb-v1.gz | GET /openapi/v2 **Accept**: application/com.github
- Поддержка функциональности в целом не будет прекращена, хотя кое-что может измениться.
- Схема и/или семантика объектов может стать несовместимой с более поздними бета-версиями или стабильными выпусками. Когда это случится, мы даем инструкции по миграции на следующую версию. Это обновление может включать удаление, редактирование и повторного создание API-объектов. Этот процесс может потребовать тщательного анализа. Кроме этого, это может привести к простою приложений, которые используют данную функциональность.
- Рекомендуется только для неосновного производственного использования из-за риска возникновения возможных несовместимых изменений с будущими версиями. Если у вас есть несколько кластеров, которые возможно обновить независимо, вы можете снять это ограничение.
- **Пожалуйста, попробуйте в действии бета-версии функциональности и поделитесь своими впечатлениями! После того, как функциональность выйдет из бета-версии, нам может быть нецелесообразно что-то дальше изменять.**
- **Пожалуйста, попробуйте в действии бета-версии функциональности и поделитесь своими впечатлениями! После того как функциональность выйдет из бета-версии, нам может быть нецелесообразно что-то дальше изменять.**
- Стабильные версии:
- Имя версии `vX`, где `vX` — целое число.
- Стабильные версии функциональностей появятся в новых версиях.
@@ -113,5 +113,3 @@ DaemonSets, Deployments, StatefulSet, NetworkPolicies, PodSecurityPolicies и Re
Например: чтобы включить deployments и daemonsets, используйте флаг `--runtime-config=extensions/v1beta1/deployments=true,extensions/v1beta1/daemonsets=true`.
{{< note >}}Включение/отключение отдельных ресурсов поддерживается только в API-группе `extensions/v1beta1` по историческим причинам.{{< /note >}}
+37 -39
View File
@@ -1,5 +1,5 @@
---
title: Участие для опытных
title: Существенный вклад
slug: advanced
content_type: concept
weight: 30
@@ -22,20 +22,20 @@ weight: 30
- Ежедневно проверять [открытые пулреквесты](https://github.com/kubernetes/website/pulls) для контроля качества и соблюдения рекомендаций по [оформлению](/docs/contribute/style/style-guide/) и [содержимому](/docs/contribute/style/content-guide/).
- В первую очередь просматривайте самые маленькие пулреквесты (`size/XS`), и только потом беритесь за самые большие (`size/XXL`).
- Проверяйте столько пулреквестов, сколько сможете.
- Проследить, что CLA подписан каждым участником.
- Проследите, что CLA подписан каждым участником.
- Помогайте новым участникам подписать [CLA](https://github.com/kubernetes/community/blob/master/CLA.md).
- Используйте [этот](https://github.com/zparnold/k8s-docs-pr-botherer) скрипт, чтобы автоматически напомнить участникам, не подписавшим CLA, чтобы они подписали CLA.
- Используйте [этот](https://github.com/zparnold/k8s-docs-pr-botherer) скрипт, чтобы автоматически напомнить участникам, не подписавшим CLA, подписать его.
- Оставить свое мнение о предложенных изменениях и поспособствовать в проведении технического обзора от членов других SIG-групп.
- Предложить исправления для измененного контента в PR.
- Если вы хотите убедиться в правильности контента, прокомментируйте PR и задайте уточняющие вопросы.
- Добавьте нужны метки с `sig/`.
- Если нужно, то назначьте рецензентов из секции `reviewers:` в фронтальной части файла.
- Добавьте нужные метки с `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.
- Ежедневно отсортируйте и пометьте новые заявки. Обратитесь к странице [Участие для опытных](/ru/docs/contribute/intermediate/) для получения информации по использованию метаданных SIG Docs.
### Полезные ссылки на GitHub для дежурных
@@ -43,9 +43,9 @@ weight: 30
- [Нет 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]).
- [Требуется 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 @<meister's_github-username>`. Если он направлен в старую ветку, помогите автору PR изменить на более подходящую ветку.
### Когда закрывать пулреквесты
@@ -57,7 +57,7 @@ weight: 30
- Закройте любой PR, если автор не отреагировал на комментарии или проверки в течение 2 или более недель.
Не бойтесь закрывать пулреквесты. Участники с лёгкостью открыть и возобновить незаконченную работу. Зачастую уведомление о закрытии стимулировать автора возобновить и закончить свой вклад.
Не бойтесь закрывать пулреквесты. Участники с лёгкостью могут открыть и возобновить незаконченную работу. Зачастую уведомление о закрытии стимулирует автора возобновить и завершить свою работу до конца.
Чтобы закрыть пулреквест, оставьте комментарий `/close` в PR.
@@ -71,8 +71,8 @@ weight: 30
[Члены](/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).
Если вы давно начали работать над документацией 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](https://kubernetes.slack.com).
Когда обсуждение состоялось, а SIG-группа согласилась с желаемым результатом, вы можете работать над предлагаемыми изменениями наиболее приемлемым способом. Например, обновление руководства по оформлению или функциональности сайта может включать открытие пулреквеста, а изменение, связанное с тестированием документации, может предполагать взаимодействие с sig-testing.
@@ -84,11 +84,11 @@ weight: 30
Представитель SIG Docs для данного выпуска координирует следующие задачи:
- Мониторинг электронной таблицы с отслеживанием функциональности на наличие новых или измененных возможностей, затрагивают документацию. Если документация для определенной функциональности не будет готова к выпуску, возможно, она не попадет в выпуск.
- Регулярное посещение встречи sig-release и обновлять информацию о статусе документации в выпуске.
- Мониторинг электронной таблицы с отслеживанием функциональности на наличие новых или измененных возможностей, затрагивающих документацию. Если документация для определенной функциональности не будет готова к выпуску, возможно, она не попадет в выпуск.
- Регулярное посещение встречи sig-release и обновление информации о статусе документации к выпуску.
- Проверка и вычитка документации по функциональности, подготовленной SIG-группой, ответственной за реализацию этой функциональности.
- Объединение связанных с выпуском пулреквестов и поддержка Git-ветки выпуска.
- Консультируйте других участников SIG Docs, которые хотят научиться выполнять эту роль в будущем. Это называется сопровождение (shadowing).
- Консультирование других участников SIG Docs, которые хотят научиться выполнять эту роль в будущем. Это называется сопровождение (shadowing).
- Публикация изменений в документации, связанные с выпуском при размещении артефактов.
Координация выпуска обычно занимает 3-4 месяца, а обязанности распределяются между утверждающими SIG Docs.
@@ -101,10 +101,10 @@ weight: 30
Обязанности амбассадоров новых участников включают в себя:
- Отвечать на вопросы новых участников на [Slack-канале Kubernetes #sig-docs](https://kubernetes.slack.com).
- Отвечать на вопросы новых участников в [Slack-канале Kubernetes #sig-docs](https://kubernetes.slack.com).
- Совместно работать с дежурным по PR, чтобы определять заявки, которые подойдут для решения новыми участниками.
- Консультировать новых участников в их PR.
- Помогать новых участникам в создании более сложных PR, чтобы они могли стать членами Kubernetes.
- Помогать новым участникам в создании более сложных PR, чтобы они могли стать членами Kubernetes.
- [Оказывать содействие участникам](/ru/docs/contribute/advanced/#поддержка-нового-участника) на их пути становления членом в Kubernetes.
Текущие амбассадоры новых участников объявляются на каждом собрании SIG Docs и на канале [#sig-docs в Kubernetes](https://kubernetes.slack.com).
@@ -115,7 +115,7 @@ weight: 30
Если участник сделал 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-docs [в Slack Kubernetes](https://kubernetes.slack.com) или в [списке рассылки SIG Docs](https://groups.google.com/forum/#!forum/kubernetes-sig-docs). Если вы осознали полезность работы автора заявки на членство, вы добровольно можете поддержать (спонсировать) его. Когда они подадут заявку на членство, отреагируйте на заявку "+1" и напишите подробный комментарий о том, почему вы считаете, что кандидат отлично вписывается в члены организации Kubernetes.
## Сопредседатель SIG
@@ -125,9 +125,9 @@ weight: 30
Сопредседатели должны соответствовать следующим требованиям:
- Быть утверждающим SIG Docs не меньше 6 месяцев
- [Руководить выпуском документации Kubernetes](/docs/contribute/advanced/#coordinate-docs-for-a-kubernetes-release) или сопровождать два выпуска
- Понимание рабочих процессов и инструментов SIG Docs: git, Hugo, локализация, блог
- Быть утверждающими 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 месяцев для выполнения обязанностей.
@@ -137,13 +137,13 @@ weight: 30
Обязанности включают в себя:
- Сосредоточить группу SIG Docs на достижении максимального счастья для разработчиков через отличную документацию
- Быть примером соблюдения [норм поведения сообщества]https://github.com/cncf/foundation/blob/master/code-of-conduct.md) и контролировать их выполнение членами SIG
- Изучение и внедрение передовых практик для SIG-группы, обновляя рекомендации по участию
- Планирование и проведение встреч SIG: еженедельные обновления информации, ежеквартальные ретроспективные/плановые совещания и многое другое
- Планирование и проведение спринтов по документации на мероприятиях KubeCon и других конференциях
- Сосредоточить группу 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
- Поддерживать нормальную работу SIG.
### Проведение продуктивных встреч
@@ -155,33 +155,33 @@ weight: 30
**Сформулируйте четкую повестку дня**:
- Определите конкретную цель встречи
- Опубликуйте программу дня заранее
- Определите конкретную цель встречи.
- Опубликуйте программу дня заранее.
Для еженедельных встреч скопируйте примечания из предыдущей недели в раздел "Past meetings".
**Работайте вместе для создания точных примечания**:
- Запишите обсуждение встречи
- Подумайте над тем, чтобы делегировать роль стенографист кому-нибудь другому
- Запишите обсуждение встречи.
- Подумайте над тем, чтобы делегировать роль стенографиста кому-нибудь другому.
**Определяйте решения по пунктам повестки четко и точно**:
- Записывайте решения по пунктам, кто будет ими заниматься и ожидаемую дату завершения
- Записывайте решения по пунктам, кто будет ими заниматься и ожидаемую дату завершения.
**Руководите обсуждением, когда это необходимо**:
- Если обсуждение выходит за пределы повестки дня, снова обратите внимание участников на обсуждаемую тему
- Найдите место для различных стилей ведения обсуждения, не отвлекаясь от темы обсуждения и уважая время людей
- Если обсуждение выходит за пределы повестки дня, снова обратите внимание участников на обсуждаемую тему.
- Найдите место для различных стилей ведения обсуждения, не отвлекаясь от темы обсуждения и уважая время людей.
**Уважайте время людей**:
- Начинайте и заканчивайте встречи своевременно
- Начинайте и заканчивайте встречи своевременно.
**Используйте Zoom эффективно**:
- Ознакомьтесь с [рекомендациями Zoom для Kubernetes](https://github.com/kubernetes/community/blob/master/communication/zoom-guidelines.md)
- Попробуйте попроситься быть ведущим в самом начале встречи, введя ключ ведущего
- Ознакомьтесь с [рекомендациями Zoom для Kubernetes](https://github.com/kubernetes/community/blob/master/communication/zoom-guidelines.md).
- Попробуйте попроситься быть ведущим в самом начале встречи, введя ключ ведущего.
<img src="/images/docs/contribute/claim-host.png" width="75%" alt="Исполнение роли ведущего в Zoom" />
@@ -192,5 +192,3 @@ weight: 30
Если нужно остановить запись, нажмите на кнопку Stop.
Запись автоматически загрузится на YouTube.
@@ -25,72 +25,72 @@ card:
### Контент, полученный из двух источников
Документация Kubernetes не содержит дублированный контент, полученный из разных мест (так называемый **контент из двумя источниками**). Контент из двух источников требует дублирования работы со стороны мейнтейнеров проекта и к тому же быстро теряет актуальность.
Документация Kubernetes не содержит дублированный контент, полученный из разных мест (так называемый **контент из двух источников**). Контент из двух источников требует дублирования работы со стороны мейнтейнеров проекта и к тому же быстро теряет актуальность.
Перед добавлением контента, задайте себе вопрос:
- Новая информация относится к действующему проекту CNCF ИЛИ проекту в организациях на GitHub kubernetes или kubernetes-sigs?
- Новая информация относится к действующему проекту CNCF или проекту в организациях на GitHub kubernetes или kubernetes-sigs?
- Если да, то:
- У этого проекта есть собственная документация?
- если да, то укажите ссылку на документацию проекта в документации Kubernetes
- если нет, добавьте информацию в репозиторий проекта (если это возможно), а затем укажите ссылку на неё в документации Kubernetes
- если да, то укажите ссылку на документацию проекта в документации Kubernetes.
- если нет, добавьте информацию в репозиторий проекта (если это возможно), а затем укажите ссылку на неё в документации Kubernetes.
- Если нет, то:
- Остановитесь!
- Добавление информации по продуктам от других разработчиков не допускается
- Добавление информации о продуктах от других разработчиков не допускается.
- Не разрешено ссылаться на документацию и сайты сторонних разработчиков.
### Разрешенная и запрещённая информация
Есть несколько условий, когда в документации Kubernetes может быть информация, относящиеся не к проектам Kubernetes.
Ниже перечислены основные категории по содержанию проектов, не касающихся к Kubernetes, а также приведены рекомендации о том, что разрешено, а что нет:
Ниже перечислены основные категории по содержанию проектов, не касающихся Kubernetes, а также приведены рекомендации о том, что разрешено, а что нет:
1. Инструкции по установке или эксплуатации Kubernetes, которые не связаны с проектами Kubernetes
1. Инструкции по установке или эксплуатации Kubernetes, которые не связаны с проектами Kubernetes.
- Разрешено:
- Ссылаться на документацию на CNCF-проекта или на проект в GitHub-организациях kubernetes или kubernetes-sigs
- Пример: для установки Kubernetes в процессе обучения нужно обязательно установить и настроить minikube, а также сослаться на соответствующую документацию minikube
- Добавление инструкций для проектов в организации kubernetes или kubernetes-sigs, если по ним нет инструкций
- Пример: добавление инструкций по установке и решению неполадок [kubadm](https://github.com/kubernetes/kubeadm)
- Ссылаться на документацию CNCF-проекта или на проект в GitHub-организациях kubernetes или kubernetes-sigs.
- Пример: для установки Kubernetes в процессе обучения нужно обязательно установить и настроить minikube, а также сослаться на соответствующую документацию minikube.
- Добавление инструкций для проектов в организации kubernetes или kubernetes-sigs, если по ним нет инструкций.
- Пример: добавление инструкций по установке и решению неполадок [kubeadm](https://github.com/kubernetes/kubeadm).
- Запрещено:
- Добавление информацию, которая повторяет документацию в другом репозитории
- Добавление информации, которая дублирует документацию в другом репозитории.
- Примеры:
- Добавление инструкций по установке и настройке minikube; Minikube имеет собственную [документацию](https://minikube.sigs.k8s.io/docs/), которая включают эти инструкции
- Добавление инструкций по установке Docker, CRI-O, containerd и других окружений для выполнения контейнеров в разных операционных системах
- Добавление инструкций по установке и настройке minikube; Minikube имеет собственную [документацию](https://minikube.sigs.k8s.io/docs/), которая включают эти инструкции.
- Добавление инструкций по установке Docker, CRI-O, containerd и других окружений для выполнения контейнеров в разных операционных системах.
- Добавление инструкций по установке Kubernetes в промышленных окружениях, используя разные проекты:
-Kubernetes Rebar Integrated Bootstrap (KRIB) — это проект стороннего разработчика, поэтому все содержимое находится репозитории разработчика.
- 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) или как этот проект разработан
- У проекта [Kubespray](https://kubespray.io) есть собственная документация.
- Добавление руководства, в котором объясняется, как выполнить задачу с использованием продукта определенного разработчика или проекта с открытым исходным кодом, не являющиеся CNCF-проектами или проектом в GitHub-организациях kubernetes, или kubernetes-sigs.
- Добавление руководства по использованию CNCF-проекта или проекта в GitHub-организациях kubernetes или kubernetes-sigs, если у проекта есть собственная документация.
1. Подробное описание технических аспектов по использованию стороннего проекта (не Kubernetes) или как этот проект разработан.
Добавление такого типа информации в документацию Kubernetes не допускается.
1. Информация стороннему проекту
1. Информация стороннему проекту.
- Разрешено:
- Добавление краткого введения о CNCF-проекте или проекте в GitHub-организациях kubernetes или kubernetes-sigs; этот абзац может содержать ссылки на проект
- Добавление краткого введения о CNCF-проекте или проекте в GitHub-организациях kubernetes или kubernetes-sigs; этот абзац может содержать ссылки на проект.
- Запрещено:
- Добавление информации по продукту определённого разработчика
- Добавление информации по проекту с открытым исходным кодом, который не является CNCF-проектом или проектом в GitHub-организациях kubernetes или kubnetes-sigs
- Добавление информации, дублирующего документацию из другого проекта, независимо от оригинального репозитория
- Пример: добавление документации для проекта [Kubernetes in Docker (KinD)](https://kind.sigs.k8s.io) в документацию Kubernetes
1. Только ссылки на сторонний проект
- Добавление информации по продукту определённого разработчика.
- Добавление информации по проекту с открытым исходным кодом, который не является CNCF-проектом или проектом в GitHub-организациях kubernetes или kubernetes-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
- Ссылаться на проекты в 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. Содержание учебных курсов
- Ссылаться на продукты стороннего разработчика.
- Ссылаться на прекращенные проекты 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/)
- Ссылаться на независимые от разработчиков учебные курсы 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 не содержит ссылок на сторонний контент
- Ссылаться на учебные онлайн-курсы, не относящиеся к 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/)
- Ссылаться на руководства определённых разработчиков вне зависимости от обучающей организации.
- Пример: добавление ссылок на такие курсы Linux Academy, как [Google Kubernetes Engine Deep Dive](https://linuxacademy.com/google-cloud-platform/training/course/name/google-kubernetes-engine-deep-dive) и [Amazon EKS Deep Dive](https://linuxacademy.com/course/amazon-eks-deep-dive/)
Если у вас есть вопросы по поводу допустимого контента, присоединяйтесь к каналу #sig-docs в [Slack Kubernetes](http://slack.k8s.io/)!
@@ -235,7 +235,7 @@ kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl
kubectl label pods my-pod new-label=awesome # Добавить метку
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # Добавить аннотацию
kubectl autoscale deployment foo --min=2 --max=10 # Автоматически промасштабировать развёртывание "foo"
kubectl autoscale deployment foo --min=2 --max=10 # Автоматически масштабировать развёртывание "foo" в диапазоне от 2 до 10 подов
```
## Обновление ресурсов
@@ -269,10 +269,10 @@ KUBE_EDITOR="nano" kubectl edit svc/docker-registry # Использовать
## Масштабирование ресурсов
```bash
kubectl scale --replicas=3 rs/foo # Промасштабировать набор реплик (replicaset) 'foo' до 3
kubectl scale --replicas=3 -f foo.yaml # Промасштабировать ресурс в "foo.yaml" до 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # Если количество реплик в развёртывании mysql равен 2, промасштабировать его до 3
kubectl scale --replicas=5 rc/foo rc/bar rc/baz # Промасштабировать несколько контроллеров репликации
kubectl scale --replicas=3 rs/foo # Масштабирование набора реплик (replicaset) 'foo' до 3
kubectl scale --replicas=3 -f foo.yaml # Масштабирование ресурса в "foo.yaml" до 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # Если количество реплик в развёртывании mysql равен 2, масштабировать его до 3
kubectl scale --replicas=5 rc/foo rc/bar rc/baz # Масштабирование нескольких контроллеров репликации до 5
```
## Удаление ресурсов
@@ -362,7 +362,7 @@ kubectl api-resources --api-group=extensions # Все ресурсы в API-гр
### Уровни детальности вывода и отладки в Kubectl
Уровни детальности вывода Kubectl регулируются с помощью флагов `-v` или `--v`, за которыми следует целое число, представляющее уровни логирования. Общие соглашения по логированиия Kubernetes и связанные с ними уровни описаны [здесь](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md).
Уровни детальности вывода Kubectl регулируются с помощью флагов `-v` или `--v`, за которыми следует целое число, представляющее уровни логирования. Общие соглашения по логированию Kubernetes и связанные с ними уровни описаны [здесь](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md).
Уровень детальности | Описание
@@ -70,7 +70,7 @@ kubectl run [-i] [--tty] --attach <name> --image=<image>
```
В отличие от `docker run ...`, если вы укажете `--attach`, то присоедините `stdin`, `stdout` and `stderr`. Нельзя проконтролировать, какие потоки прикрепляются (`docker -a ...`).
Чтобы отсоединиться от контейнера воспользуетесь комбинацией клавиш Ctrl+P, а затем Ctrl+Q.
Чтобы отсоединиться от контейнера, воспользуетесь комбинацией клавиш Ctrl+P, а затем Ctrl+Q.
Так как команда kubectl run запускает развёртывание для контейнера, то оно начнет перезапускаться, если завершить прикрепленный процесс по нажатию Ctrl+C, в отличие от команды `docker run -it`.
Для удаления объекта Deployment вместе с подами, необходимо выполнить команду `kubectl delete deployment <name>`.
@@ -90,7 +90,7 @@ kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.st
```
{{< note >}}
В Windows нужно заключить в _двойные_ кавычки JSONPath-шаблон, который содержит пробелы (не в одинарные, как в примерах выше для bash). Таким образом, любые литералы в таких шаблонов нужно оборачивать в одинарные кавычки или экранированные двойные кавычки. Например:
В Windows нужно заключить в _двойные_ кавычки JSONPath-шаблон, который содержит пробелы (не в одинарные, как в примерах выше для bash). Таким образом, любые литералы в таких шаблонах нужно оборачивать в одинарные кавычки или экранированные двойные кавычки. Например:
```cmd
kubectl get pods -o=jsonpath="{range .items[*]}{.metadata.name}{'\t'}{.status.startTime}{'\n'}{end}"
+47 -47
View File
@@ -158,14 +158,14 @@ kubectl [flags]
<td colspan="2">--default-not-ready-toleration-seconds int&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;По умолчанию: 300</td>
</tr>
<tr>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Указывает tolerationSeconds для допущения notReady:NoExecute, которое по умолчанию добавляется к каждому поду, у которого нет установлено такое допущение.</td>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Указывает tolerationSeconds для допущения notReady:NoExecute, которое по умолчанию добавляется к каждому поду, у которого не установлено такое допущение.</td>
</tr>
<tr>
<td colspan="2">--default-unreachable-toleration-seconds int&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;По умолчанию: 300</td>
</tr>
<tr>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Указывает tolerationSeconds для допущения unreachable:NoExecute, которое по умолчанию добавляется к каждому поду, у которого нет установлено такое допущение.</td>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Указывает tolerationSeconds для допущения unreachable:NoExecute, которое по умолчанию добавляется к каждому поду, у которого не установлено такое допущение.</td>
</tr>
<tr>
@@ -221,7 +221,7 @@ kubectl [flags]
<td colspan="2">--docker-tls-cert string&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;По умолчанию: "cert.pem"</td>
</tr>
<tr>
<td></td><td style="line-height: 130%; word-wrap: break-word;">путь к клиентскому сертификату</td>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Путь к клиентскому сертификату</td>
</tr>
<tr>
@@ -277,7 +277,7 @@ kubectl [flags]
<td colspan="2">--insecure-skip-tls-verify</td>
</tr>
<tr>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Если true, значит сертификат сервера не будет проверятся на достоверность. Это сделает подключения через HTTPS небезопасными.</td>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Если true, значит сертификат сервера не будет проверяться на достоверность. Это сделает подключения через HTTPS небезопасными.</td>
</tr>
<tr>
@@ -333,7 +333,7 @@ kubectl [flags]
<td colspan="2">--logtostderr&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;По умолчанию: true</td>
</tr>
<tr>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Логировать в стандартный поток ошибок вместо сохранения логов в файлы</td>
<td></td><td style="line-height: 130%; word-wrap: break-word;">Вывод логов в стандартный поток ошибок вместо сохранения их в файлы</td>
</tr>
<tr>
@@ -521,48 +521,48 @@ kubectl [flags]
## {{% heading "seealso" %}}
* [kubectl annotate](/docs/reference/generated/kubectl/kubectl-commands#annotate) - Обновить аннотации ресурса
* [kubectl api-resources](/docs/reference/generated/kubectl/kubectl-commands#api-resources) - Вывести доступные API-ресурсы на сервере
* [kubectl api-versions](/docs/reference/generated/kubectl/kubectl-commands#api-versions) - Вывести доступные API-версии на сервере в виде "group/version".
* [kubectl apply](/docs/reference/generated/kubectl/kubectl-commands#apply) - Внести изменения в конфигурацию ресурса из файла или потока stdin.
* [kubectl attach](/docs/reference/generated/kubectl/kubectl-commands#attach) - Присоединиться к запущенному контейнеру
* [kubectl auth](/docs/reference/generated/kubectl/kubectl-commands#auth) - Проверить разрешение на выполнение определённых действий
* [kubectl autoscale](/docs/reference/generated/kubectl/kubectl-commands#autoscale) - Автоматически промасштабировать Deployment, ReplicaSet или ReplicationController
* [kubectl certificate](/docs/reference/generated/kubectl/kubectl-commands#certificate) - Изменить сертификаты ресурсов.
* [kubectl cluster-info](/docs/reference/generated/kubectl/kubectl-commands#cluster-info) - Показать информацию по кластеру
* [kubectl completion](/docs/reference/generated/kubectl/kubectl-commands#completion) - Вывод кода автодополнения указанной командной оболочки (bash или zsh)
* [kubectl config](/docs/reference/generated/kubectl/kubectl-commands#config) - Изменить файлы kubeconfig
* [kubectl convert](/docs/reference/generated/kubectl/kubectl-commands#convert) - Конвертировать конфигурационные файлы в различные API-версии
* [kubectl cordon](/docs/reference/generated/kubectl/kubectl-commands#cordon) - Отметить узел как неназначаемый
* [kubectl cp](/docs/reference/generated/kubectl/kubectl-commands#cp) - Копировать файлы и директории в/из контейнеров.
* [kubectl create](/docs/reference/generated/kubectl/kubectl-commands#create) - Создать ресурс из файла или потока stdin.
* [kubectl delete](/docs/reference/generated/kubectl/kubectl-commands#delete) - Удалить ресурсы из файла, потока stdin, либо с помощью селекторов меток, имен, селекторов ресурсов или ресурсов
* [kubectl describe](/docs/reference/generated/kubectl/kubectl-commands#describe) - Показать подробную информацию о конкретном ресурсе или группе ресурсов
* [kubectl diff](/docs/reference/generated/kubectl/kubectl-commands#diff) - Сравнить действующую версию с новой (применяемой)
* [kubectl drain](/docs/reference/generated/kubectl/kubectl-commands#drain) - Вытеснить узел для подготовки к эксплуатации
* [kubectl edit](/docs/reference/generated/kubectl/kubectl-commands#edit) - Отредактировать ресурс на сервере
* [kubectl exec](/docs/reference/generated/kubectl/kubectl-commands#exec) - Выполнить команду в контейнере
* [kubectl explain](/docs/reference/generated/kubectl/kubectl-commands#explain) - Получить документацию ресурсов
* [kubectl expose](/docs/reference/generated/kubectl/kubectl-commands#expose) - Создать новый сервис Kubernetes из контроллера репликации, сервиса, развёртывания или пода
* [kubectl get](/docs/reference/generated/kubectl/kubectl-commands#get) - Вывести один или несколько ресурсов
* [kubectl kustomize](/docs/reference/generated/kubectl/kubectl-commands#kustomize) - Собрать ресурсы kustomization из директории или URL-адреса.
* [kubectl label](/docs/reference/generated/kubectl/kubectl-commands#label) - Обновить метки ресурса
* [kubectl logs](/docs/reference/generated/kubectl/kubectl-commands#logs) - Вывести логи контейнера в поде
* [kubectl options](/docs/reference/generated/kubectl/kubectl-commands#options) - Вывести список флагов, применяемых ко всем командам
* [kubectl patch](/docs/reference/generated/kubectl/kubectl-commands#patch) - Обновить один или несколько полей ресурса, используя стратегию слияния патча
* [kubectl plugin](/docs/reference/generated/kubectl/kubectl-commands#plugin) - Команда для работы с плагинами.
* [kubectl port-forward](/docs/reference/generated/kubectl/kubectl-commands#port-forward) - Переадресовать один или несколько локальных портов в под
* [kubectl proxy](/docs/reference/generated/kubectl/kubectl-commands#proxy) - Запустить прокси на API-сервер Kubernetes
* [kubectl replace](/docs/reference/generated/kubectl/kubectl-commands#replace) - Заменить ресурс из определения в файле или потоке stdin.
* [kubectl rollout](/docs/reference/generated/kubectl/kubectl-commands#rollout) - Управление плавающим обновлением ресурса
* [kubectl run](/docs/reference/generated/kubectl/kubectl-commands#run) - Запустить указанный образ в кластере
* [kubectl scale](/docs/reference/generated/kubectl/kubectl-commands#scale) - Задать новый размер для Deployment, ReplicaSet или Replication Controller.
* [kubectl set](/docs/reference/generated/kubectl/kubectl-commands#set) - Конфигурировать ресурсы в объектах
* [kubectl taint](/docs/reference/generated/kubectl/kubectl-commands#taint) - Обновить ограничения для одного или нескольких узлов
* [kubectl top](/docs/reference/generated/kubectl/kubectl-commands#top) - Показать информацию по использованию системных ресурсов (процессор, память, диск)
* [kubectl uncordon](/docs/reference/generated/kubectl/kubectl-commands#uncordon) - Отметить узел как назначаемый
* [kubectl version](/docs/reference/generated/kubectl/kubectl-commands#version) - Вывести информацию о версии клиента и сервера
* [kubectl wait](/docs/reference/generated/kubectl/kubectl-commands#wait) - Экспериментально: ожидать выполнения определенного условия в одном или нескольких ресурсах.
* [kubectl annotate](/docs/reference/generated/kubectl/kubectl-commands#annotate) - Обновить аннотации ресурса.
* [kubectl api-resources](/docs/reference/generated/kubectl/kubectl-commands#api-resources) - Вывести доступные API-ресурсы на сервере.
* [kubectl api-versions](/docs/reference/generated/kubectl/kubectl-commands#api-versions) - Вывести доступные API-версии на сервере в виде "group/version".
* [kubectl apply](/docs/reference/generated/kubectl/kubectl-commands#apply) - Внести изменения в конфигурацию ресурса из файла или потока stdin.
* [kubectl attach](/docs/reference/generated/kubectl/kubectl-commands#attach) - Присоединиться к запущенному контейнеру.
* [kubectl auth](/docs/reference/generated/kubectl/kubectl-commands#auth) - Проверить разрешение на выполнение определённых действий.
* [kubectl autoscale](/docs/reference/generated/kubectl/kubectl-commands#autoscale) - Автоматически масштабировать Deployment, ReplicaSet или ReplicationController.
* [kubectl certificate](/docs/reference/generated/kubectl/kubectl-commands#certificate) - Изменить сертификаты ресурсов.
* [kubectl cluster-info](/docs/reference/generated/kubectl/kubectl-commands#cluster-info) - Показать информацию по кластеру.
* [kubectl completion](/docs/reference/generated/kubectl/kubectl-commands#completion) - Вывод кода автодополнения указанной командной оболочки (bash или zsh).
* [kubectl config](/docs/reference/generated/kubectl/kubectl-commands#config) - Изменить файлы kubeconfig.
* [kubectl convert](/docs/reference/generated/kubectl/kubectl-commands#convert) - Конвертировать конфигурационные файлы в различные API-версии.
* [kubectl cordon](/docs/reference/generated/kubectl/kubectl-commands#cordon) - Отметить узел как неназначаемый.
* [kubectl cp](/docs/reference/generated/kubectl/kubectl-commands#cp) - Копировать файлы и директории в/из контейнеров.
* [kubectl create](/docs/reference/generated/kubectl/kubectl-commands#create) - Создать ресурс из файла или потока stdin.
* [kubectl delete](/docs/reference/generated/kubectl/kubectl-commands#delete) - Удалить ресурсы из файла, потока stdin, либо с помощью селекторов меток, имен, селекторов ресурсов или ресурсов.
* [kubectl describe](/docs/reference/generated/kubectl/kubectl-commands#describe) - Показать подробную информацию о конкретном ресурсе или группе ресурсов.
* [kubectl diff](/docs/reference/generated/kubectl/kubectl-commands#diff) - Сравнить действующую версию с новой (применяемой).
* [kubectl drain](/docs/reference/generated/kubectl/kubectl-commands#drain) - Вытеснить узел для подготовки к эксплуатации.
* [kubectl edit](/docs/reference/generated/kubectl/kubectl-commands#edit) - Отредактировать ресурс на сервере.
* [kubectl exec](/docs/reference/generated/kubectl/kubectl-commands#exec) - Выполнить команду в контейнере.
* [kubectl explain](/docs/reference/generated/kubectl/kubectl-commands#explain) - Получить документацию ресурсов.
* [kubectl expose](/docs/reference/generated/kubectl/kubectl-commands#expose) - Создать новый сервис Kubernetes из контроллера репликации, сервиса, развёртывания или пода.
* [kubectl get](/docs/reference/generated/kubectl/kubectl-commands#get) - Вывести один или несколько ресурсов.
* [kubectl kustomize](/docs/reference/generated/kubectl/kubectl-commands#kustomize) - Собрать ресурсы kustomization из директории или URL-адреса.
* [kubectl label](/docs/reference/generated/kubectl/kubectl-commands#label) - Обновить метки ресурса.
* [kubectl logs](/docs/reference/generated/kubectl/kubectl-commands#logs) - Вывести логи контейнера в поде.
* [kubectl options](/docs/reference/generated/kubectl/kubectl-commands#options) - Вывести список флагов, применяемых ко всем командам.
* [kubectl patch](/docs/reference/generated/kubectl/kubectl-commands#patch) - Обновить один или несколько полей ресурса, используя стратегию слияния патча.
* [kubectl plugin](/docs/reference/generated/kubectl/kubectl-commands#plugin) - Команда для работы с плагинами.
* [kubectl port-forward](/docs/reference/generated/kubectl/kubectl-commands#port-forward) - Переадресовать один или несколько локальных портов в под.
* [kubectl proxy](/docs/reference/generated/kubectl/kubectl-commands#proxy) - Запустить прокси на API-сервер Kubernetes.
* [kubectl replace](/docs/reference/generated/kubectl/kubectl-commands#replace) - Заменить ресурс из определения в файле или потоке stdin.
* [kubectl rollout](/docs/reference/generated/kubectl/kubectl-commands#rollout) - Управление плавающим обновлением ресурса.
* [kubectl run](/docs/reference/generated/kubectl/kubectl-commands#run) - Запустить указанный образ в кластере.
* [kubectl scale](/docs/reference/generated/kubectl/kubectl-commands#scale) - Задать новый размер для Deployment, ReplicaSet или Replication Controller.
* [kubectl set](/docs/reference/generated/kubectl/kubectl-commands#set) - Конфигурировать ресурсы в объектах.
* [kubectl taint](/docs/reference/generated/kubectl/kubectl-commands#taint) - Обновить ограничения для одного или нескольких узлов.
* [kubectl top](/docs/reference/generated/kubectl/kubectl-commands#top) - Показать информацию по использованию системных ресурсов (процессор, память, диск).
* [kubectl uncordon](/docs/reference/generated/kubectl/kubectl-commands#uncordon) - Отметить узел как назначаемый.
* [kubectl version](/docs/reference/generated/kubectl/kubectl-commands#version) - Вывести информацию о версии клиента и сервера.
* [kubectl wait](/docs/reference/generated/kubectl/kubectl-commands#wait) - Экспериментально: ожидать выполнения определенного условия в одном или нескольких ресурсах.
@@ -52,7 +52,7 @@ kubectl [command] [TYPE] [NAME] [flags]
* Выбор ресурсов по одному или нескольким файлов: `-f file1 -f file2 -f file<#>`
* [Используйте YAML вместо JSON](/docs/concepts/configuration/overview/#general-configuration-tips), так так YAML удобнее для пользователей, особенно в конфигурационных файлов.<br/>
* [Используйте YAML вместо JSON](/docs/concepts/configuration/overview/#general-configuration-tips), так как YAML удобнее для пользователей, особенно в конфигурационных файлах.<br/>
Пример: `kubectl get pod -f ./pod.yaml`
* `flags`: определяет дополнительные флаги. Например, вы можете использовать флаги `-s` или `--server`, чтобы указать адрес и порт API-сервера Kubernetes.<br/>
@@ -162,7 +162,7 @@ kubectl [command] [TYPE] [NAME] [flags]
### Форматирование вывода
Стандартный формат вывода всех команд `kubectl` представлен в человекочитаемом текстовом формате. Чтобы вывести подробности в определенном формате можно добавить флаги `-o` или `--output` к команде `kubectl`.
Стандартный формат вывода всех команд `kubectl` представлен в понятном для человека текстовом формате. Чтобы вывести подробности в определенном формате можно добавить флаги `-o` или `--output` к команде `kubectl`.
#### Синтаксис
@@ -229,7 +229,7 @@ submit-queue 610995
`kubectl` может получать информацию об объектах с сервера.
Это означает, что для любого указанного ресурса сервер вернет столбцы и строки по этому ресурсу, которые отобразит клиент.
Благодаря тому, что сервер инкапсулирует реализацию вывода, гарантируется единообразный и человекочитаемый вывод на всех клиентах, использующих один и тот же кластер.
Благодаря тому, что сервер инкапсулирует реализацию вывода, гарантируется единообразный и понятный для человека вывод на всех клиентах, использующих один и тот же кластер.
Эта функциональность включена по умолчанию, начиная с `kubectl` 1.11 и выше. Чтобы отключить ее, добавьте флаг `--server-print=false` в команду `kubectl get`.
@@ -340,7 +340,7 @@ kubectl delete pods,services -l name=<label-name>
kubectl delete pods --all
```
`kubectl exec` - Выполнить команду в контейнера пода.
`kubectl exec` - Выполнить команду в контейнере пода.
```shell
# Получить вывод от запущенной команды 'date' в поде <pod-name>. По умолчанию отображается вывод из первого контейнера.
@@ -0,0 +1,154 @@
---
layout: blog
title: 'Kubernetes 1.23IPv4/IPv6 双协议栈网络达到 GA'
date: 2021-12-08
slug: dual-stack-networking-ga
---
<!--
layout: blog
title: 'Kubernetes 1.23: Dual-stack IPv4/IPv6 Networking Reaches GA'
date: 2021-12-08
slug: dual-stack-networking-ga
-->
<!--
**Author:** Bridget Kromhout (Microsoft)
-->
**作者:** Bridget Kromhout (微软)
<!--
"When will Kubernetes have IPv6?" This question has been asked with increasing frequency ever since alpha support for IPv6 was first added in k8s v1.9. While Kubernetes has supported IPv6-only clusters since v1.18, migration from IPv4 to IPv6 was not yet possible at that point. At long last, [dual-stack IPv4/IPv6 networking](https://github.com/kubernetes/enhancements/tree/master/keps/sig-network/563-dual-stack/) has reached general availability (GA) in Kubernetes v1.23.
What does dual-stack networking mean for you? Lets take a look…
-->
“Kubernetes 何时支持 IPv6?” 自从 k8s v1.9 版本中首次添加对 IPv6 的 alpha 支持以来,这个问题的讨论越来越频繁。
虽然 Kubernetes 从 v1.18 版本开始就支持纯 IPv6 集群,但当时还无法支持 IPv4 迁移到 IPv6。
[IPv4/IPv6 双协议栈网络](https://github.com/kubernetes/enhancements/tree/master/keps/sig-network/563-dual-stack/)
在 Kubernetes v1.23 版本中进入正式发布(GA)阶段。
让我们来看看双协议栈网络对你来说意味着什么?
<!--
## Service API updates
-->
## 更新 Service API
<!--
[Services](/docs/concepts/services-networking/service/) were single-stack before 1.20, so using both IP families meant creating one Service per IP family. The user experience was simplified in 1.20, when Services were re-implemented to allow both IP families, meaning a single Service can handle both IPv4 and IPv6 workloads. Dual-stack load balancing is possible between services running any combination of IPv4 and IPv6.
-->
[Services](/zh/docs/concepts/services-networking/service/) 在 1.20 版本之前是单协议栈的,
因此,使用两个 IP 协议族意味着需为每个 IP 协议族创建一个 Service。在 1.20 版本中对用户体验进行简化,
重新实现了 Service 以支持两个 IP 协议族,这意味着一个 Service 就可以处理 IPv4 和 IPv6 协议。
对于 Service 而言,任意的 IPv4 和 IPv6 协议组合都可以实现负载均衡。
<!--
The Service API now has new fields to support dual-stack, replacing the single ipFamily field.
* You can select your choice of IP family by setting `ipFamilyPolicy` to one of three options: SingleStack, PreferDualStack, or RequireDualStack. A service can be changed between single-stack and dual-stack (within some limits).
* Setting `ipFamilies` to a list of families assigned allows you to set the order of families used.
* `clusterIPs` is inclusive of the previous `clusterIP` but allows for multiple entries, so its no longer necessary to run duplicate services, one in each of the two IP families. Instead, you can assign cluster IP addresses in both IP families.
-->
Service API 现在有了支持双协议栈的新字段,取代了单一的 ipFamily 字段。
* 你可以通过将 `ipFamilyPolicy` 字段设置为 `SingleStack``PreferDualStack`
`RequireDualStack` 来设置 IP 协议族。Service 可以在单协议栈和双协议栈之间进行转换(在某些限制内)。
* 设置 `ipFamilies` 为指定的协议族列表,可用来设置使用协议族的顺序。
* 'clusterIPs' 的能力在涵盖了之前的 'clusterIP'的情况下,还允许设置多个 IP 地址。
所以不再需要运行重复的 Service,在两个 IP 协议族中各运行一个。你可以在两个 IP 协议族中分配集群 IP 地址。
<!--
Note that Pods are also dual-stack. For a given pod, there is no possibility of setting multiple IP addresses in the same family.
-->
请注意,Pods 也是双协议栈的。对于一个给定的 Pod,不可能在同一协议族中设置多个 IP 地址。
<!--
## Default behavior remains single-stack
-->
## 默认行为仍然是单协议栈
<!--
Starting in 1.20 with the re-implementation of dual-stack services as alpha, the underlying networking for Kubernetes has included dual-stack whether or not a cluster was configured with the feature flag to enable dual-stack.
-->
从 1.20 版本开始,重新实现的双协议栈服务处于 Alpha 阶段,无论集群是否配置了启用双协议栈的特性标志,
Kubernetes 的底层网络都已经包括了双协议栈。
<!--
Kubernetes 1.23 removed that feature flag as part of graduating the feature to stable. Dual-stack networking is always available if you want to configure it. You can set your cluster network to operate as single-stack IPv4, as single-stack IPv6, or as dual-stack IPv4/IPv6.
-->
Kubernetes 1.23 删除了这个特性标志,说明该特性已经稳定。
如果你想要配置双协议栈网络,这一能力总是存在的。
你可以将集群网络设置为 IPv4 单协议栈 、IPv6 单协议栈或 IPV4/IPV6 双协议栈 。
<!--
While Services are set according to what you configure, Pods default to whatever the CNI plugin sets. If your CNI plugin assigns single-stack IPs, you will have single-stack unless `ipFamilyPolicy` specifies PreferDualStack or RequireDualStack. If your CNI plugin assigns dual-stack IPs, `pod.status.PodIPs` defaults to dual-stack.
-->
虽然 Service 是根据你的配置设置的,但 Pod 默认是由 CNI 插件设置的。
如果你的 CNI 插件分配单协议栈 IP,那么就是单协议栈,除非 `ipFamilyPolicy` 设置为 `PreferDualStack``RequireDualStack`
如果你的 CNI 插件分配双协议栈 IP,则 `pod.status.PodIPs` 默认为双协议栈。
<!--
Even though dual-stack is possible, it is not mandatory to use it. Examples in the documentation show the variety possible in [dual-stack service configurations](/docs/concepts/services-networking/dual-stack/#dual-stack-service-configuration-scenarios).
-->
尽管双协议栈是可用的,但并不强制你使用它。
在[双协议栈服务配置](/zh/docs/concepts/services-networking/dual-stack/#dual-stack-service-configuration-scenarios)
文档中的示例列出了可能出现的各种场景.
<!--
## Try dual-stack right now
-->
## 现在尝试双协议栈
<!--
While upstream Kubernetes now supports [dual-stack networking](/docs/concepts/services-networking/dual-stack/) as a GA or stable feature, each providers support of dual-stack Kubernetes may vary. Nodes need to be provisioned with routable IPv4/IPv6 network interfaces. Pods need to be dual-stack. The [network plugin](/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/) is what assigns the IP addresses to the Pods, so it's the network plugin being used for the cluster that needs to support dual-stack. Some Container Network Interface (CNI) plugins support dual-stack, as does kubenet.
-->
虽然现在上游 Kubernetes 支持[双协议栈网络](/zh/docs/concepts/services-networking/dual-stack/)
作为 GA 或稳定特性,但每个提供商对双协议栈 Kubernetes 的支持可能会有所不同。节点需要提供可路由的 IPv4/IPv6 网络接口。
Pod 需要是双协议栈的。[网络插件](/zh/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/)
是用来为 Pod 分配 IP 地址的,所以集群需要支持双协议栈的网络插件。一些容器网络接口(CNI)插件支持双协议栈,例如 kubenet。
<!--
Ecosystem support of dual-stack is increasing; you can create [dual-stack clusters with kubeadm](/docs/setup/production-environment/tools/kubeadm/dual-stack-support/), try a [dual-stack cluster locally with KIND](https://kind.sigs.k8s.io/docs/user/configuration/#ip-family), and deploy dual-stack clusters in cloud providers (after checking docs for CNI or kubenet availability).
-->
支持双协议栈的生态系统在不断壮大;你可以使用
[kubeadm 创建双协议栈集群](/zh/docs/setup/production-environment/tools/kubeadm/dual-stack-support/),
在本地尝试用 [KIND 创建双协议栈集群](https://kind.sigs.k8s.io/docs/user/configuration/#ip-family)
还可以将双协议栈集群部署到云上(在查阅 CNI 或 kubenet 可用性的文档之后)
<!--
## Get involved with SIG Network
-->
## 加入 Network SIG
<!--
SIG-Network wants to learn from community experiences with dual-stack networking to find out more about evolving needs and your use cases. The [SIG-network update video from KubeCon NA 2021](https://www.youtube.com/watch?v=uZ0WLxpmBbY&list=PLj6h78yzYM2Nd1U4RMhv7v88fdiFqeYAP&index=4) summarizes the SIGs recent updates, including dual-stack going to stable in 1.23.
-->
SIG-Network 希望从双协议栈网络的社区体验中学习,以了解更多不断变化的需求和你的用例信息。
[SIG-network 更新了来自 KubeCon 2021 北美大会的视频](https://www.youtube.com/watch?v=uZ0WLxpmBbY&list=PLj6h78yzYM2Nd1U4RMhv7v88fdiFqeYAP&index=4)
总结了 SIG 最近的更新,包括双协议栈将在 1.23 版本中稳定。
<!--
The current SIG-Network [KEPs](https://github.com/orgs/kubernetes/projects/10) and [issues](https://github.com/kubernetes/kubernetes/issues?q=is%3Aopen+is%3Aissue+label%3Asig%2Fnetwork) on GitHub illustrate the SIGs areas of emphasis. The [dual-stack API server](https://github.com/kubernetes/enhancements/issues/2438) is one place to consider contributing.
-->
当前 SIG-Network 在 GitHub 上的 [KEPs](https://github.com/orgs/kubernetes/projects/10) 和
[issues](https://github.com/kubernetes/kubernetes/issues?q=is%3Aopen+is%3Aissue+label%3Asig%2Fnetwork)
说明了该 SIG 的重点领域。[双协议栈 API 服务器](https://github.com/kubernetes/enhancements/issues/2438)
是一个考虑贡献的方向。
<!--
[SIG-Network meetings](https://github.com/kubernetes/community/tree/master/sig-network#meetings) are a friendly, welcoming venue for you to connect with the community and share your ideas. Looking forward to hearing from you!
-->
[SIG-Network 会议](https://github.com/kubernetes/community/tree/master/sig-network#meetings)
是一个友好、热情的场所,你可以与社区联系并分享你的想法。期待你的加入!
<!--
## Acknowledgments
-->
## 致谢
<!--
The dual-stack networking feature represents the work of many Kubernetes contributors. Thanks to all who contributed code, experience reports, documentation, code reviews, and everything in between. Bridget Kromhout details this community effort in [Dual-Stack Networking in Kubernetes](https://containerjournal.com/features/dual-stack-networking-in-kubernetes/). KubeCon keynotes by Tim Hockin & Khaled (Kal) Henidak in 2019 ([The Long Road to IPv4/IPv6 Dual-stack Kubernetes](https://www.youtube.com/watch?v=o-oMegdZcg4)) and by Lachlan Evenson in 2021 ([And Here We Go: Dual-stack Networking in Kubernetes](https://www.youtube.com/watch?v=lVrt8F2B9CM)) talk about the dual-stack journey, spanning five years and a great many lines of code.
-->
许多 Kubernetes 贡献者为双协议栈网络做出了贡献。感谢所有贡献了代码、经验报告、文档、代码审查以及其他工作的人。
Bridget Kromhout 在 [Kubernetes的双协议栈网络](https://containerjournal.com/features/dual-stack-networking-in-kubernetes/)
中详细介绍了这项社区工作。Tim Hockin 和 Khaled (Kal) Henidak 在 2019 年的 KubeCon 大会演讲
[Kubernetes 通往 IPv4/IPv6 双协议栈的漫漫长路](https://www.youtube.com/watch?v=o-oMegdZcg4)
和 Lachlan Evenson 在 2021 年演讲([我们来啦,Kubernetes 双协议栈网络](https://www.youtube.com/watch?v=o-oMegdZcg4)
中讨论了双协议栈的发展旅程,耗时 5 年和海量代码。
@@ -0,0 +1,208 @@
---
layout: blog
title: 'Kubernetes 1.23: StatefulSet PVC 自动删除 (alpha)'
date: 2021-12-16
slug: kubernetes-1-23-statefulset-pvc-auto-deletion
---
<!--
layout: blog
title: 'Kubernetes 1.23: StatefulSet PVC Auto-Deletion (alpha)'
date: 2021-12-16
slug: kubernetes-1-23-statefulset-pvc-auto-deletion
-->
<!--
**Author:** Matthew Cary (Google)
-->
**作者:** Matthew Cary (谷歌)
<!--
Kubernetes v1.23 introduced a new, alpha-level policy for
[StatefulSets](docs/concepts/workloads/controllers/statefulset/) that controls the lifetime of
[PersistentVolumeClaims](docs/concepts/storage/persistent-volumes/) (PVCs) generated from the
StatefulSet spec template for cases when they should be deleted automatically when the StatefulSet
is deleted or pods in the StatefulSet are scaled down.
-->
Kubernetes v1.23 为 [StatefulSets](/zh/docs/concepts/workloads/controllers/statefulset/)
引入了一个新的 alpha 级策略,用来控制由 StatefulSet 规约模板生成的
[PersistentVolumeClaims](/zh/docs/concepts/storage/persistent-volumes/) (PVCs) 的生命周期,
用于当删除 StatefulSet 或减少 StatefulSet 中的 Pods 数量时 PVCs 应该被自动删除的场景。
<!--
## What problem does this solve?
-->
## 它解决了什么问题?
<!--
A StatefulSet spec can include Pod and PVC templates. When a replica is first created, the
Kubernetes control plane creates a PVC for that replica if one does not already exist. The behavior
before Kubernetes v1.23 was that the control plane never cleaned up the PVCs created for
StatefulSets - this was left up to the cluster administrator, or to some add-on automation that
youd have to find, check suitability, and deploy. The common pattern for managing PVCs, either
manually or through tools such as Helm, is that the PVCs are tracked by the tool that manages them,
with explicit lifecycle. Workflows that use StatefulSets must determine on their own what PVCs are
created by a StatefulSet and what their lifecycle should be.
-->
StatefulSet 规约中可以包含 Pod 和 PVC 的模板。当副本先被创建时,如果 PVC 还不存在,
Kubernetes 控制面会为该副本自动创建一个 PVC。在 Kubernetes 1.23 版本之前,
控制面不会删除 StatefulSet 创建的 PVCs——这依赖集群管理员或你需要部署一些额外的适用的自动化工具来处理。
管理 PVC 的常见模式是通过手动或使用 Helm 等工具,PVC 的具体生命周期由管理它的工具跟踪。
使用 StatefulSet 时必须自行确定 StatefulSet 创建哪些 PVC,以及它们的生命周期应该是什么。
<!--
Before this new feature, when a StatefulSet-managed replica disappears, either because the
StatefulSet is reducing its replica count, or because its StatefulSet is deleted, the PVC and its
backing volume remains and must be manually deleted. While this behavior is appropriate when the
data is critical, in many cases the persistent data in these PVCs is either temporary, or can be
reconstructed from another source. In those cases, PVCs and their backing volumes remaining after
their StatefulSet or replicas have been deleted are not necessary, incur cost, and require manual
cleanup.
-->
在这个新特性之前,当一个 StatefulSet 管理的副本消失时,无论是因为 StatefulSet 减少了它的副本数,
还是因为它的 StatefulSet 被删除了,PVC 及其下层的卷仍然存在,需要手动删除。
当存储数据比较重要时,这样做是合理的,但在许多情况下,这些 PVC 中的持久化数据要么是临时的,
要么可以从另一个源端重建。在这些情况下,删除 StatefulSet 或减少副本后留下的 PVC 及其下层的卷是不必要的,
还会产生成本,需要手动清理。
<!--
## The new StatefulSet PVC retention policy
-->
## 新的 StatefulSet PVC 保留策略
<!--
If you enable the alpha feature, a StatefulSet spec includes a PersistentVolumeClaim retention
policy. This is used to control if and when PVCs created from a StatefulSets `volumeClaimTemplate`
are deleted. This first iteration of the retention policy contains two situations where PVCs may be
deleted.
-->
如果你启用这个新 alpha 特性,StatefulSet 规约中就可以包含 PersistentVolumeClaim 的保留策略。
该策略用于控制是否以及何时删除基于 StatefulSet 的 `volumeClaimTemplate` 属性所创建的 PVCs。
保留策略的首次迭代包含两种可能删除 PVC 的情况。
<!--
The first situation is when the StatefulSet resource is deleted (which implies that all replicas are
also deleted). This is controlled by the `whenDeleted` policy. The second situation, controlled by
`whenScaled` is when the StatefulSet is scaled down, which removes some but not all of the replicas
in a StatefulSet. In both cases the policy can either be `Retain`, where the corresponding PVCs are
not touched, or `Delete`, which means that PVCs are deleted. The deletion is done with a normal
[object deletion](/docs/concepts/architecture/garbage-collection/), so that, for example, all
retention policies for the underlying PV are respected.
-->
第一种情况是 StatefulSet 资源被删除时(这意味着所有副本也被删除),这由 `whenDeleted` 策略控制的。
第二种情况是 StatefulSet 缩小时,即删除 StatefulSet 部分副本,这由 `whenScaled` 策略控制。
在这两种情况下,策略即可以是 `Retain` 不涉及相应 PVCs 的改变,也可以是 `Delete` 即删除对应的 PVCs。
删除是通过普通的[对象删除](/zh/docs/concepts/architecture/garbage-collection/)完成的,
因此,的所有保留策略都会被遵照执行。
<!--
This policy forms a matrix with four cases. Ill walk through and give an example for each one.
-->
该策略形成包含四种情况的矩阵。我将逐一介绍,并为每一种情况给出一个例子。
<!--
* **`whenDeleted` and `whenScaled` are both `Retain`.** This matches the existing behavior for
StatefulSets, where no PVCs are deleted. This is also the default retention policy. Its
appropriate to use when data on StatefulSet volumes may be irreplaceable and should only be
deleted manually.
-->
* **`whenDeleted``whenScaled` 都是 `Retain`。** 这与 StatefulSets 的现有行为一致,
即不删除 PVCs。 这也是默认的保留策略。它适用于 StatefulSet
卷上的数据是不可替代的且只能手动删除的情况。
<!--
* **`whenDeleted` is `Delete` and `whenScaled` is `Retain`.** In this case, PVCs are deleted only when
the entire StatefulSet is deleted. If the StatefulSet is scaled down, PVCs are not touched,
meaning they are available to be reattached if a scale-up occurs with any data from the previous
replica. This might be used for a temporary StatefulSet, such as in a CI instance or ETL
pipeline, where the data on the StatefulSet is needed only during the lifetime of the
StatefulSet lifetime, but while the task is running the data is not easily reconstructible. Any
retained state is needed for any replicas that scale down and then up.
-->
* **`whenDeleted``Delete``whenScaled``Retain`。** 在这种情况下,
只有当整个 StatefulSet 被删除时,PVCs 才会被删除。
如果减少 StatefulSet 副本,PVCs 不会删除,这意味着如果增加副本时,可以从前一个副本重新连接所有数据。
这可能用于临时的 StatefulSet,例如在 CI 实例或 ETL 管道中,
StatefulSet 上的数据仅在 StatefulSet 生命周期内才需要,但在任务运行时数据不易重构。
任何保留状态对于所有先缩小后扩大的副本都是必需的。
<!--
* **`whenDeleted` and `whenScaled` are both `Delete`.** PVCs are deleted immediately when their
replica is no longer needed. Note this does not include when a Pod is deleted and a new version
rescheduled, for example when a node is drained and Pods need to migrate elsewhere. The PVC is
deleted only when the replica is no longer needed as signified by a scale-down or StatefulSet
deletion. This use case is for when data does not need to live beyond the life of its
replica. Perhaps the data is easily reconstructable and the cost savings of deleting unused PVCs
is more important than quick scale-up, or perhaps that when a new replica is created, any data
from a previous replica is not usable and must be reconstructed anyway.
-->
* **`whenDeleted``whenScaled` 都是 `Delete`。** 当其副本不再被需要时,PVCs 会立即被删除。
注意,这并不包括 Pod 被删除且有新版本被调度的情况,例如当节点被腾空而 Pod 需要迁移到别处时。
只有当副本不再被需要时,如按比例缩小或删除 StatefulSet 时,才会删除 PVC。
此策略适用于数据生命周期短于副本生命周期的情况。即数据很容易重构,
且删除未使用的 PVC 所节省的成本比快速增加副本更重要,或者当创建一个新的副本时,
来自以前副本的任何数据都不可用,必须重新构建。
<!--
* **`whenDeleted` is `Retain` and `whenScaled` is `Delete`.** This is similar to the previous case,
when there is little benefit to keeping PVCs for fast reuse during scale-up. An example of a
situation where you might use this is an Elasticsearch cluster. Typically you would scale that
workload up and down to match demand, whilst ensuring a minimum number of replicas (for example:
3). When scaling down, data is migrated away from removed replicas and there is no benefit to
retaining those PVCs. However, it can be useful to bring the entire Elasticsearch cluster down
temporarily for maintenance. If you need to take the Elasticsearch system offline, you can do
this by temporarily deleting the StatefulSet, and then bringing the Elasticsearch cluster back
by recreating the StatefulSet. The PVCs holding the Elasticsearch data will still exist and the
new replicas will automatically use them.
-->
* **`whenDeleted``Retain``whenScaled``Delete`。** 这与前一种情况类似,
在增加副本时用保留的 PVCs 快速重构几乎没有什么益处。例如 Elasticsearch 集群就是使用的这种方式。
通常,你需要增大或缩小工作负载来满足业务诉求,同时确保最小数量的副本(例如:3)。
当减少副本时,数据将从已删除的副本迁移出去,保留这些 PVCs 没有任何用处。
但是,这对临时关闭整个 Elasticsearch 集群进行维护时是很有用的。
如果需要使 Elasticsearch 系统脱机,可以通过临时删除 StatefulSet 来实现,
然后通过重新创建 StatefulSet 来恢复 Elasticsearch 集群。
保存 Elasticsearch 数据的 PVCs 不会被删除,新的副本将自动使用它们。
<!--
Visit the
[documentation](docs/concepts/workloads/controllers/statefulset/#persistentvolumeclaim-policies) to
see all the details.
-->
查阅[文档](/zh/docs/concepts/workloads/controllers/statefulset/#persistentvolumeclaim-policies)
获取更多详细信息。
<!--
## Whats next?
-->
## 下一步是什么?
<!--
Enable the feature and try it out! Enable the `StatefulSetAutoDeletePVC` feature gate on a cluster,
then create a StatefulSet using the new policy. Test it out and tell us what you think!
-->
启用该功能并尝试一下!在集群上启用 `StatefulSetAutoDeletePVC` 功能,然后使用新策略创建 StatefulSet。
测试一下,告诉我们你的体验!
<!--
I'm very curious to see if this owner reference mechanism works well in practice. For example, we
realized there is no mechanism in Kubernetes for knowing who set a reference, so its possible that
the StatefulSet controller may fight with custom controllers that set their own
references. Fortunately, maintaining the existing retention behavior does not involve any new owner
references, so default behavior will be compatible.
-->
我很好奇这个属主引用机制在实践中是否有效。例如,我们意识到 Kubernetes 中没有可以知道谁设置了引用的机制,
因此 StatefulSet 控制器可能会与设置自己的引用的自定义控制器发生冲突。
幸运的是,维护现有的保留行为不涉及任何新属主引用,因此默认行为是兼容的。
<!--
Please tag any issues you report with the label `sig/apps` and assign them to Matthew Cary
([@mattcary](https://github.com/mattcary) at GitHub).
-->
请用标签 `sig/apps` 标记你报告的任何问题,并将它们分配给 Matthew Cary
(在 GitHub上 [@mattcary](https://github.com/mattcary))。
<!--
Enjoy!
-->
尽情体验吧!
@@ -0,0 +1,299 @@
---
layout: blog
title: 'SIG Node CI 子项目庆祝测试改进两周年'
date: 2022-02-16
slug: sig-node-ci-subproject-celebrates
canonicalUrl: https://www.kubernetes.dev/blog/2022/02/16/sig-node-ci-subproject-celebrates-two-years-of-test-improvements/
---
<!--
---
layout: blog
title: 'SIG Node CI Subproject Celebrates Two Years of Test Improvements'
date: 2022-02-16
slug: sig-node-ci-subproject-celebrates
canonicalUrl: https://www.kubernetes.dev/blog/2022/02/16/sig-node-ci-subproject-celebrates-two-years-of-test-improvements/
url: /zh/blog/2022/02/sig-node-ci-subproject-celebrates
---
-->
**作者:** Sergey Kanzhelev (Google), Elana Hashman (Red Hat)
<!--**Authors:** Sergey Kanzhelev (Google), Elana Hashman (Red Hat)-->
<!--Ensuring the reliability of SIG Node upstream code is a continuous effort
that takes a lot of behind-the-scenes effort from many contributors.
There are frequent releases of Kubernetes, base operating systems,
container runtimes, and test infrastructure that result in a complex matrix that
requires attention and steady investment to "keep the lights on."
In May 2020, the Kubernetes node special interest group ("SIG Node") organized a new
subproject for continuous integration (CI) for node-related code and tests. Since its
inauguration, the SIG Node CI subproject has run a weekly meeting, and even the full hour
is often not enough to complete triage of all bugs, test-related PRs and issues, and discuss all
related ongoing work within the subgroup.-->
保证 SIG 节点上游代码的可靠性是一项持续的工作,需要许多贡献者在幕后付出大量努力。
Kubernetes、基础操作系统、容器运行时和测试基础架构的频繁发布,导致了一个复杂的矩阵,
需要关注和稳定的投资来“保持灯火通明”。2020 年 5 月,Kubernetes Node 特殊兴趣小组
(“SIG Node”)为节点相关代码和测试组织了一个新的持续集成(CI)子项目。自成立以来,SIG Node CI
子项目每周举行一次会议,即使一整个小时通常也不足以完成对所有缺陷、测试相关的 PR 和问题的分类,
并讨论组内所有相关的正在进行的工作。
<!--Over the past two years, we've fixed merge-blocking and release-blocking tests, reducing time to merge Kubernetes contributors' pull requests thanks to reduced test flakes. When we started, Node test jobs only passed 42% of the time, and through our efforts, we now ensure a consistent >90% job pass rate. We've closed 144 test failure issues and merged 176 pull requests just in kubernetes/kubernetes. And we've helped subproject participants ascend the Kubernetes contributor ladder, with 3 new org members, 6 new reviewers, and 2 new approvers.-->
在过去两年中,我们修复了阻塞合并和阻塞发布的测试,由于减少了测试缺陷,缩短了合并 Kubernetes
贡献者的拉取请求的时间。通过我们的努力,任务通过率由开始时 42% 提高至稳定大于 90% 。我们已经解决了 144 个测试失败问题,
并在 kubernetes/kubernetes 中合并了 176 个拉取请求。
我们还帮助子项目参与者提升了 Kubernetes 贡献者的等级,新增了 3 名组织成员、6 名评审员和 2 名审批员。
<!--The Node CI subproject is an approachable first stop to help new contributors
get started with SIG Node. There is a low barrier to entry for new contributors
to address high-impact bugs and test fixes, although there is a long
road before contributors can climb the entire contributor ladder:
it took over a year to establish two new approvers for the group.
The complexity of all the different components that power Kubernetes nodes
and its test infrastructure requires a sustained investment over a long period
for developers to deeply understand the entire system,
both at high and low levels of detail.-->
Node CI 子项目是一个可入门的第一站,帮助新参与者开始使用 SIG Node。对于新贡献者来说,
解决影响较大的缺陷和测试修复的门槛很低,尽管贡献者要攀登整个贡献者阶梯还有很长的路要走:
为该团队培养了两个新的审批人花了一年多的时间。为 Kubernetes 节点及其测试基础设施提供动力的所有
不同组件的复杂性要求开发人员在很长一段时间内进行持续投资,
以深入了解整个系统,从宏观到微观。
<!--We have several regular contributors at our meetings, however; our reviewers
and approvers pool is still small. It is our goal to continue to grow
contributors to ensure a sustainable distribution of work
that does not just fall to a few key approvers.-->
虽然在我们的会议上有几个比较固定的贡献者;但是我们的评审员和审批员仍然很少。
我们的目标是继续增加贡献者,以确保工作的可持续分配,而不仅仅是少数关键批准者。
<!--It's not always obvious how subprojects within SIGs are formed, operate,
and work. Each is unique to its sponsoring SIG and tailored to the projects
that the group is intended to support. As a group that has welcomed many
first-time SIG Node contributors, we'd like to share some of the details and
accomplishments over the past two years,
helping to demystify our inner workings and celebrate the hard work
of all our dedicated contributors!-->
SIG 中的子项目如何形成、运行和工作并不总是显而易见的。每一个都是其背后的 SIG 所独有的,
并根据该小组打算支持的项目量身定制。作为一个欢迎了许多第一次 SIG Node 贡献者的团队,
我们想分享过去两年的一些细节和成就,帮助揭开我们内部工作的神秘面纱,并庆祝我们所有专注贡献者的辛勤工作!
<!--## Timeline-->
## 时间线
<!--***May 2020.*** SIG Node CI group was formed on May 11, 2020, with more than
[30 volunteers](https://docs.google.com/document/d/1fb-ugvgdSVIkkuJ388_nhp2pBTy_4HEVg5848Xy7n5U/edit#bookmark=id.vsb8pqnf4gib)
signed up, to improve SIG Node CI signal and overall observability.
Victor Pickard focused on getting
[testgrid jobs](https://testgrid.k8s.io/sig-node) passing
when Ning Liao suggested forming a group around this effort and came up with
the [original group charter document](https://docs.google.com/document/d/1yS-XoUl6GjZdjrwxInEZVHhxxLXlTIX2CeWOARmD8tY/edit#heading=h.te6sgum6s8uf).
The SIG Node chairs sponsored group creation with Victor as a subproject lead.
Sergey Kanzhelev joined Victor shortly after as a co-lead.-->
***2020 年 5 月*** SIG Node CI 组于 2020 年 5 月 11 日成立,超过
[30 名志愿者](https://docs.google.com/document/d/1fb-ugvgdSVIkkuJ388_nhp2pBTy_4HEVg5848Xy7n5U/edit#bookmark=id.vsb8pqnf4gib)
注册,以改进 SIG Node CI 信号和整体可观测性。
Victor Pickard 专注于让 [testgrid 可以运行](https://testgrid.k8s.io/sig-node)
当时 Ning Liao 建议围绕这项工作组建一个小组,并提出
[最初的小组章程文件](https://docs.google.com/document/d/1yS-XoUl6GjZdjrwxInEZVHhxxLXlTIX2CeWOARmD8tY/edit#heading=h.te6sgum6s8uf) 。
SIG Node 赞助成立以 Victor 作为子项目负责人的小组。Sergey Kanzhelev 不久后就加入 Victor,担任联合领导人。
<!--At the kick-off meeting, we discussed which tests to concentrate on fixing first
and discussed merge-blocking and release-blocking tests, many of which were failing due
to infrastructure issues or buggy test code.-->
在启动会议上,我们讨论了应该首先集中精力修复哪些测试,并讨论了阻塞合并和阻塞发布的测试,
其中许多测试由于基础设施问题或错误的测试代码而失败。
<!--The subproject launched weekly hour-long meetings to discuss ongoing work
discussion and triage.-->
该子项目每周召开一小时的会议,讨论正在进行的工作会谈和分类。
<!--***June 2020.*** Morgan Bauer, Karan Goel, and Jorge Alarcon Ochoa were
recognized as reviewers for the SIG Node CI group for their contributions,
helping significantly with the early stages of the subproject.
David Porter and Roy Yang also joined the SIG test failures GitHub team.-->
***2020 年 6 月*** Morgan Bauer 、 Karan Goel 和 Jorge Alarcon Ochoa
因其贡献而被公认为 SIG Node CI 小组的评审员,为该子项目的早期阶段提供了重要帮助。
David Porter 和 Roy Yang 也加入了 SIG 检测失败的 GitHub 测试团队。
<!--***August 2020.*** All merge-blocking and release-blocking tests were passing,
with some flakes. However, only 42% of all SIG Node test jobs were green, as there
were many flakes and failing tests.-->
***2020 年 8 月*** 所有的阻塞合并和阻塞发布的测试都通过了,伴有一些逻辑问题。
然而,只有 42% 的 SIG Node 测试作业是绿色的,
因为有许多逻辑错误和失败的测试。
<!--***October 2020.*** Amim Knabben becomes a Kubernetes org member for his
contributions to the subproject.-->
***2020 年 10 月*** Amim Knabben 因对子项目的贡献成为 Kubernetes 组织成员。
<!--***January 2021.*** With healthy presubmit and critical periodic jobs passing,
the subproject discussed its goal for cleaning up the rest of periodic tests
and ensuring they passed without flakes.-->
***2021 年 1 月*** 随着健全的预提交和关键定期工作的通过,子项目讨论了清理其余定期测试并确保其顺利通过的目标。
<!--Elana Hashman joined the subproject, stepping up to help lead it after
Victor's departure.-->
Elana Hashman 加入了这个子项目,在 Victor 离开后帮助领导该项目。
<!--***February 2021.*** Artyom Lukianov becomes a Kubernetes org member for his
contributions to the subproject.-->
***2021 年 2 月*** Artyom Lukianov 因其对子项目的贡献成为 Kubernetes 组织成员。
<!--***August 2021.*** After SIG Node successfully ran a [bug scrub](https://groups.google.com/g/kubernetes-dev/c/w2ghO4ihje0/m/VeEql1LJBAAJ)
to clean up its bug backlog, the scope of the meeting was extended to
include bug triage to increase overall reliability, anticipating issues
before they affect the CI signal.-->
***2021 年 8 月*** 在 SIG Node 成功运行 [bug scrub](https://groups.google.com/g/kubernetes-dev/c/w2ghO4ihje0/m/VeEql1LJBAAJ)
以清理其累积的缺陷之后,会议的范围扩大到包括缺陷分类以提高整体可靠性,
在问题影响 CI 信号之前预测问题。
<!--Subproject leads Elana Hashman and Sergey Kanzhelev are both recognized as
approvers on all node test code, supported by SIG Node and SIG Testing.-->
子项目负责人 Elana Hashman 和 Sergey Kanzhelev 都被认为是所有节点测试代码的审批人,由 SIG node 和 SIG Testing 支持。
<!--***September 2021.*** After significant deflaking progress with serial tests in
the 1.22 release spearheaded by Francesco Romani, the subproject set a goal
for getting the serial job fully passing by the 1.23 release date.-->
***2021 年 9 月*** 在 Francesco Romani 牵头的 1.22 版本系列测试取得重大进展后,
该子项目设定了一个目标,即在 1.23 发布日期之前让串行任务完全通过。
<!--Mike Miranda becomes a Kubernetes org member for his contributions
to the subproject.-->
Mike Miranda 因其对子项目的贡献成为 Kubernetes 组织成员。
<!--***November 2021.*** Throughout 2021, SIG Node had no merge or
release-blocking test failures. Many flaky tests from past releases are removed
from release-blocking dashboards as they had been fully cleaned up.-->
***2021 年 11 月*** 在整个 2021 年, SIG Node 没有合并或发布的测试失败。
过去版本中的许多古怪测试都已从阻止发布的仪表板中删除,因为它们已被完全清理。
<!--Danielle Lancashire was recognized as a reviewer for SIG Node's subgroup, test code.-->
Danielle Lancashire 被公认为 SIG Node 子组测试代码的评审员。
<!--The final node serial tests were completely fixed. The serial tests consist of
many disruptive and slow tests which tend to be flakey and are hard
to troubleshoot. By the 1.23 release freeze, the last serial tests were
fixed and the job was passing without flakes.-->
最终节点系列测试已完全修复。系列测试由许多中断性和缓慢的测试组成,这些测试往往是碎片化的,很难排除故障。
到 1.23 版本冻结时,最后一次系列测试已修复,作业顺利通过。
<!--[![Slack announcement that Serial tests are green](serial-tests-green.png)](https://kubernetes.slack.com/archives/C0BP8PW9G/p1638211041322900)-->
[![宣布系列测试为绿色](serial-tests-green.png)](https://kubernetes.slack.com/archives/C0BP8PW9G/p1638211041322900)
<!--The 1.23 release got a special shout out for the tests quality and CI signal.
The SIG Node CI subproject was proud to have helped contribute to such
a high-quality release, in part due to our efforts in identifying
and fixing flakes in Node and beyond.-->
1.23 版本在测试质量和 CI 信号方面得到了特别的关注。SIG Node CI 子项目很自豪能够为这样一个高质量的发布做出贡献,
部分原因是我们在识别和修复节点内外的碎片方面所做的努力。
<!--[![Slack shoutout that release was mostly green](release-mostly-green.png)](https://kubernetes.slack.com/archives/C92G08FGD/p1637175755023200)-->
[![Slack 大声宣布发布的版本大多是绿色的](release-mostly-green.png)](https://kubernetes.slack.com/archives/C92G08FGD/p1637175755023200)
<!--***December 2021.*** An estimated 90% of test jobs were passing at the time of
the 1.23 release (up from 42% in August 2020).-->
***2021 年 12 月*** 在 1.23 版本发布时,估计有 90% 的测试工作通过了测试(2020 年 8 月为 42%)。
<!--Dockershim code was removed from Kubernetes. This affected nearly half of SIG Node's
test jobs and the SIG Node CI subproject reacted quickly and retargeted all the
tests. SIG Node was the first SIG to complete test migrations off dockershim,
providing examples for other affected SIGs. The vast majority of new jobs passed
at the time of introduction without further fixes required. The [effort of
removing dockershim](https://k8s.io/dockershim)) from Kubernetes is ongoing.
There are still some wrinkles from the dockershim removal as we uncover more
dependencies on dockershim, but we plan to stabilize all test jobs
by the 1.24 release.-->
Dockershim 代码已从 Kubernetes 中删除。这影响了 SIG Node 近一半的测试作业,
SIG Node CI 子项目反应迅速,并重新确定了所有测试的目标。
SIG Node 是第一个完成 dockershim 外测试迁移的 SIG ,为其他受影响的 SIG 提供了示例。
绝大多数新工作在引入时都已通过,无需进一步修复。
从 Kubernetes 中[将 dockershim 除名的工作](https://k8s.io/dockershim) 正在进行中。
随着我们发现 dockershim 对 dockershim 的依赖性越来越大,dockershim 的删除仍然存在一些问题,
但我们计划在 1.24 版本之前确保所有测试任务稳定。
<!--## Statistics-->
## 统计数据
<!--Our regular meeting attendees and subproject participants for the past few months:-->
我们过去几个月的定期会议与会者和子项目参与者:
- Aditi Sharma
- Artyom Lukianov
- Arnaud Meukam
- Danielle Lancashire
- David Porter
- Davanum Srinivas
- Elana Hashman
- Francesco Romani
- Matthias Bertschy
- Mike Miranda
- Paco Xu
- Peter Hunt
- Ruiwen Zhao
- Ryan Phillips
- Sergey Kanzhelev
- Skyler Clark
- Swati Sehgal
- Wenjun Wu
<!--The [kubernetes/test-infra](https://github.com/kubernetes/test-infra/) source code repository contains test definitions. The number of
Node PRs just in that repository:
- 2020 PRs (since May): [183](https://github.com/kubernetes/test-infra/pulls?q=is%3Apr+is%3Aclosed+label%3Asig%2Fnode+created%3A2020-05-01..2020-12-31+-author%3Ak8s-infra-ci-robot+)
- 2021 PRs: [264](https://github.com/kubernetes/test-infra/pulls?q=is%3Apr+is%3Aclosed+label%3Asig%2Fnode+created%3A2021-01-01..2021-12-31+-author%3Ak8s-infra-ci-robot+)-->
[kubernetes/test-infra](https://github.com/kubernetes/test-infra/) 源代码存储库包含测试定义。该存储库中的节点 PR 数:
- 2020 年 PR(自 5 月起):[183](https://github.com/kubernetes/test-infra/pulls?q=is%3Apr+is%3Aclosed+label%3Asig%2Fnode+created%3A2020-05-01..2020-12-31+-author%3Ak8s-infra-ci-robot+)
- 2021 年 PR[264](https://github.com/kubernetes/test-infra/pulls?q=is%3Apr+is%3Aclosed+label%3Asig%2Fnode+created%3A2021-01-01..2021-12-31+-author%3Ak8s-infra-ci-robot+)
<!--Triaged issues and PRs on CI board (including triaging away from the subgroup scope):
- 2020 (since May)[132](https://github.com/issues?q=project%3Akubernetes%2F43+created%3A2020-05-01..2020-12-31)
- 2021: [532](https//github.com/issues?q=project%3Akubernetes%2F43+created%3A2021-01-01..2021-12-31+)-->
CI 委员会上的问题和 PRs 分类(包括子组范围之外的分类):
- 2020 年(自 5 月起):[132](https://github.com/issues?q=project%3Akubernetes%2F43+created%3A2020-05-01..2020-12-31)
- 2021 年:[532](https://github.com/issues?q=project%3Akubernetes%2F43+created%3A2021-01-01..2021-12-31+)
<!--## Future-->
## 未来
<!--Just "keeping the lights on" is a bold task and we are committed to improving this experience.
We are working to simplify the triage and review processes for SIG Node.
Specifically, we are working on better test organization, naming,
and tracking:-->
只是“保持灯亮”是一项大胆的任务,我们致力于改善这种体验。
我们正在努力简化 SIG Node 的分类和审查流程。
具体来说,我们正在致力于更好的测试组织、命名和跟踪:
<!-- - https://github.com/kubernetes/enhancements/pull/3042
- https://github.com/kubernetes/test-infra/issues/24641
- [Kubernetes SIG-Node CI Testgrid Tracker](https://docs.google.com/spreadsheets/d/1IwONkeXSc2SG_EQMYGRSkfiSWNk8yWLpVhPm-LOTbGM/edit#gid=0)-->
- https://github.com/kubernetes/enhancements/pull/3042
- https://github.com/kubernetes/test-infra/issues/24641
- [Kubernetes SIG Node CI 测试网格跟踪器](https://docs.google.com/spreadsheets/d/1IwONkeXSc2SG_EQMYGRSkfiSWNk8yWLpVhPm-LOTbGM/edit#gid=0)
<!--We are also constantly making progress on improved tests debuggability and de-flaking.
If any of this interests you, we'd love for you to join us!
There's plenty to learn in debugging test failures, and it will help you gain
familiarity with the code that SIG Node maintains.-->
我们还在改进测试的可调试性和去剥落方面不断取得进展。
如果你对此感兴趣,我们很乐意您能加入我们!
在调试测试失败中有很多东西需要学习,它将帮助你熟悉 SIG Node 维护的代码。
<!--You can always find information about the group on the
[SIG Node](https://github.com/kubernetes/community/tree/master/sig-node) page.
We give group updates at our maintainer track sessions, such as
[KubeCon + CloudNativeCon Europe 2021](https://kccnceu2021.sched.com/event/iE8E/kubernetes-sig-node-intro-and-deep-dive-elana-hashman-red-hat-sergey-kanzhelev-google) 和
[KubeCon + CloudNative North America 2021](https://kccncna2021.sched.com/event/lV9D/kubenetes-sig-node-intro-and-deep-dive-elana-hashman-derek-carr-red-hat-sergey-kanzhelev-dawn-chen-google?iframe=no&w=100%&sidebar=yes&bg=no)。
Join us in our mission to keep the kubelet and other SIG Node components reliable and ensure smooth and uneventful releases!-->
你可以在 [SIG Node](https://github.com/kubernetes/community/tree/master/sig-node) 页面上找到有关该组的信息。
我们在我们的维护者轨道会议上提供组更新,例如:
[KubeCon + CloudNativeCon Europe 2021](https://kccnceu2021.sched.com/event/iE8E/kubernetes-sig-node-intro-and-deep-dive-elana-hashman-red-hat-sergey-kanzhelev-google) 和
[KubeCon + CloudNative North America 2021](https://kccncna2021.sched.com/event/lV9D/kubenetes-sig-node-intro-and-deep-dive-elana-hashman-derek-carr-red-hat-sergey-kanzhelev-dawn-chen-google?iframe=no&w=100%&sidebar=yes&bg=no)。
加入我们的使命,保持 kubelet 和其他 SIG Node 组件的可靠性,确保顺顺利利发布!
Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

@@ -3,7 +3,6 @@ layout: blog
title: "更新:弃用 Dockershim 的常见问题"
date: 2022-02-17
slug: dockershim-faq
aliases: [ '/dockershim' ]
---
<!--
layout: blog
@@ -0,0 +1,180 @@
---
layout: blog
title: "认识我们的贡献者 - 亚太地区(澳大利亚-新西兰地区)"
date: 2022-03-16T12:00:00+0000
slug: meet-our-contributors-au-nz-ep-02
canonicalUrl: https://www.kubernetes.dev/blog/2022/03/14/meet-our-contributors-au-nz-ep-02/
---
<!--
layout: blog
title: "Meet Our Contributors - APAC (Aus-NZ region)"
date: 2022-03-16T12:00:00+0000
slug: meet-our-contributors-au-nz-ep-02
canonicalUrl: https://www.kubernetes.dev/blog/2022/03/14/meet-our-contributors-au-nz-ep-02/
-->
<!--
**Authors & Interviewers:** [Anubhav Vardhan](https://github.com/anubha-v-ardhan), [Atharva Shinde](https://github.com/Atharva-Shinde), [Avinesh Tripathi](https://github.com/AvineshTripathi), [Brad McCoy](https://github.com/bradmccoydev), [Debabrata Panigrahi](https://github.com/Debanitrkl), [Jayesh Srivastava](https://github.com/jayesh-srivastava), [Kunal Verma](https://github.com/verma-kunal), [Pranshu Srivastava](https://github.com/PranshuSrivastava), [Priyanka Saggu](github.com/Priyankasaggu11929/), [Purneswar Prasad](https://github.com/PurneswarPrasad), [Vedant Kakde](https://github.com/vedant-kakde)
-->
**作者和采访者:**
[Anubhav Vardhan](https://github.com/anubha-v-ardhan),
[Atharva Shinde](https://github.com/Atharva-Shinde),
[Avinesh Tripathi](https://github.com/AvineshTripathi),
[Brad McCoy](https://github.com/bradmccoydev),
[Debabrata Panigrahi](https://github.com/Debanitrkl),
[Jayesh Srivastava](https://github.com/jayesh-srivastava),
[Kunal Verma](https://github.com/verma-kunal),
[Pranshu Srivastava](https://github.com/PranshuSrivastava),
[Priyanka Saggu](github.com/Priyankasaggu11929/),
[Purneswar Prasad](https://github.com/PurneswarPrasad),
[Vedant Kakde](https://github.com/vedant-kakde)
---
<!--
Good day, everyone 👋
-->
大家好👋
<!--
Welcome back to the second episode of the "Meet Our Contributors" blog post series for APAC.
-->
欢迎来到亚太地区的”认识我们的贡献者”博文系列第二期。
<!--
This post will feature four outstanding contributors from the Australia and New Zealand regions, who have played diverse leadership and community roles in the Upstream Kubernetes project.
-->
这篇文章将介绍来自澳大利亚和新西兰地区的四位杰出贡献者,
他们在上游 Kubernetes 项目中承担着不同子项目的领导者和社区贡献者的角色。
<!--
So, without further ado, let's get straight to the blog.
-->
闲话少说,让我们直接进入主题。
## [Caleb Woodbine](https://github.com/BobyMCbobs)
<!--
Caleb Woodbine is currently a member of the ii.nz organisation.
-->
Caleb Woodbine 目前是 ii.nz 组织的成员。
<!--
He began contributing to the Kubernetes project in 2018 as a member of the Kubernetes Conformance working group. His experience was positive, and he benefited from early guidance from [Hippie Hacker](https://github.com/hh), a fellow contributor from New Zealand.
-->
他于 2018 年作为 Kubernetes Conformance 工作组的成员开始为 Kubernetes 项目做贡献。
他积极向上,他从一位来自新西兰的贡献者 [Hippie Hacker](https://github.com/hh) 的早期指导中受益匪浅。
<!--
He has made major contributions to Kubernetes project since then through `SIG k8s-infra` and `k8s-conformance` working group.
-->
他在 `SIG k8s-infra``k8s-conformance` 工作组为 Kubernetes 项目做出了重大贡献。
<!--
Caleb is also a co-organizer of the [CloudNative NZ](https://www.meetup.com/cloudnative-nz/) community events, which aim to expand the reach of Kubernetes project throughout New Zealand in order to encourage technical education and improved employment opportunities.
-->
Caleb 也是 [CloudNative NZ](https://www.meetup.com/cloudnative-nz/)
社区活动的联合组织者,该活动旨在扩大 Kubernetes 项目在整个新西兰的影响力,以鼓励科技教育和改善就业机会。
<!--
> _There need to be more outreach in APAC and the educators and universities must pick up Kubernetes, as they are very slow and about 8+ years out of date. NZ tends to rather pay overseas than educate locals on the latest cloud tech Locally._
-->
> _亚太地区需要更多的外联活动,教育工作者和大学必须学习 Kubernetes,因为他们非常缓慢,
而且已经落后了8年多。新西兰倾向于在海外付费,而不是教育当地人最新的云技术。_
## [Dylan Graham](https://github.com/DylanGraham)
<!--
Dylan Graham is a cloud engineer from Adeliade, Australia. He has been contributing to the upstream Kubernetes project since 2018.
-->
Dylan Graham 是来自澳大利亚 Adeliade 的云计算工程师。自 2018 年以来,他一直在为上游 Kubernetes 项目做出贡献。
<!--
He stated that being a part of such a large-scale project was initially overwhelming, but that the community's friendliness and openness assisted him in getting through it.
-->
他表示,成为如此大项目的一份子,最初压力是比较大的,但社区的友好和开放帮助他度过了难关。
<!--
He began by contributing to the project documentation and is now mostly focused on the community support for the APAC region.
-->
开始在项目文档方面做贡献,现在主要致力于为亚太地区提供社区支持。
<!--
He believes that consistent attendance at community/project meetings, taking on project tasks, and seeking community guidance as needed can help new aspiring developers become effective contributors.
-->
他相信,持续参加社区/项目会议,承担项目任务,并在需要时寻求社区指导,可以帮助有抱负的新开发人员成为有效的贡献者。
<!--
> _The feeling of being a part of a large community is really special. I've met some amazing people, even some before the pandemic in real life :)_
-->
> _成为大社区的一份子感觉真的很特别。我遇到了一些了不起的人,甚至是在现实生活中疫情发生之前。_
## [Hippie Hacker](https://github.com/hh)
<!--
Hippie has worked for the CNCF.io as a Strategic Initiatives contractor from New Zealand for almost 5+ years. He is an active contributor to k8s-infra, API conformance testing, Cloud provider conformance submissions, and apisnoop.cncf.io domains of the upstream Kubernetes & CNCF projects.
-->
Hippie 来自新西兰,曾在 CNCF.io 作为战略计划承包商工作 5 年多。他是 k8s-infra、
API 一致性测试、云提供商一致性提交以及上游 Kubernetes 和 CNCF 项目 apisnoop.cncf.io 域的积极贡献者。
<!--
He recounts their early involvement with the Kubernetes project, which began roughly 5 years ago when their firm, ii.nz, demonstrated [network booting from a Raspberry Pi using PXE and running Gitlab in-cluster to install Kubernetes on servers](https://ii.nz/post/bringing-the-cloud-to-your-community/).
-->
他讲述了他们早期参与 Kubernetes 项目的情况,该项目始于大约 5 年前,当时他们的公司 ii.nz
演示了[使用 PXE 从 Raspberry Pi 启动网络,并在集群中运行Gitlab,以便在服务器上安装 Kubernetes ](https://ii.nz/post/bringing-the-cloud-to-your-community/)
<!--
He describes their own contributing experience as someone who, at first, tried to do all of the hard lifting on their own, but eventually saw the benefit of group contributions which reduced burnout and task division which allowed folks to keep moving forward on their own momentum.
-->
他描述了自己的贡献经历:一开始,他试图独自完成所有艰巨的任务,但最终看到了团队协作贡献的好处,
分工合作减少了过度疲劳,这让人们能够凭借自己的动力继续前进。
<!--
He recommends that new contributors use pair programming.
-->
他建议新的贡献者结对编程。
<!--
> _The cross pollination of approaches and two pairs of eyes on the same work can often yield a much more amplified effect than a PR comment / approval alone can afford._
-->
> _针对一个项目,多人关注和交叉交流往往比单独的评审、批准 PR 能产生更大的效果。_
## [Nick Young](https://github.com/youngnick)
<!--
Nick Young works at VMware as a technical lead for Contour, a CNCF ingress controller. He was active with the upstream Kubernetes project from the beginning, and eventually became the chair of the LTS working group, where he advocated user concerns. He is currently the SIG Network Gateway API subproject's maintainer.
-->
Nick Young 在 VMware 工作,是 CNCF 入口控制器 Contour 的技术负责人。
他从一开始就积极参与上游 Kubernetes 项目,最终成为 LTS 工作组的主席,
他提倡关注用户。他目前是 SIG Network Gateway API 子项目的维护者。
<!--
His contribution path was notable in that he began working on major areas of the Kubernetes project early on, skewing his trajectory.
-->
他的贡献之路是引人注目的,因为他很早就在 Kubernetes 项目的主要领域工作,这改变了他的轨迹。
<!--
He asserts the best thing a new contributor can do is to "start contributing". Naturally, if it is relevant to their employment, that is excellent; however, investing non-work time in contributing can pay off in the long run in terms of work. He believes that new contributors, particularly those who are currently Kubernetes users, should be encouraged to participate in higher-level project discussions.
-->
他断言,一个新贡献者能做的最好的事情就是“开始贡献”。当然,如果与他的工作息息相关,那好极了;
然而,把非工作时间投入到贡献中去,从长远来看可以在工作上获得回报。
他认为,应该鼓励新的贡献者,特别是那些目前是 Kubernetes 用户的人,参与到更高层次的项目讨论中来。
<!--
> _Just being active and contributing will get you a long way. Once you've been active for a while, you'll find that you're able to answer questions, which will mean you're asked questions, and before you know it you are an expert._
-->
> _只要积极主动,做出贡献,你就可以走很远。一旦你活跃了一段时间,你会发现你能够解答别人的问题,
这意味着会有人请教你或和你讨论,在你意识到这一点之前,你就已经是专家了。_
---
<!--
If you have any recommendations/suggestions for who we should interview next, please let us know in #sig-contribex. Your suggestions would be much appreciated. We're thrilled to have additional folks assisting us in reaching out to even more wonderful individuals of the community.
-->
如果你对我们接下来应该采访的人有任何意见/建议,请在 #sig-contribex 中告知我们。
非常感谢你的建议。我们很高兴有更多的人帮助我们接触到社区中更优秀的人。
<!--
We'll see you all in the next one. Everyone, till then, have a happy contributing! 👋
-->
我们下期再见。祝你有个愉快的贡献之旅!👋
+5 -1
View File
@@ -1,5 +1,9 @@
<!-- The files in this directory have been imported from other sources. Do not
edit them directly, except by replacing them with new versions. -->
edit them directly, except by replacing them with new versions.
Localization note: you do not need to create localized versions of any of
the files in this directory.
-->
本路径下的文件从其它地方导入。
除了版本更新,不要直接修改。
本地化说明:你无需为此目录中的任何文件创建本地化版本。
@@ -25,7 +25,7 @@ allows the clean up of resources like the following:
* [Objects without owner references](#owners-dependents)
* [Unused containers and container images](#containers-images)
* [Dynamically provisioned PersistentVolumes with a StorageClass reclaim policy of Delete](/docs/concepts/storage/persistent-volumes/#delete)
* [Stale or expired CertificateSigningRequests (CSRs)](/reference/access-authn-authz/certificate-signing-requests/#request-signing-process)
* [Stale or expired CertificateSigningRequests (CSRs)](/docs/reference/access-authn-authz/certificate-signing-requests/#request-signing-process)
* {{<glossary_tooltip text="Nodes" term_id="node">}} deleted in the following scenarios:
* On a cloud when the cluster uses a [cloud controller manager](/docs/concepts/architecture/cloud-controller/)
* On-premises when the cluster uses an addon similar to a cloud controller
@@ -77,8 +77,8 @@ ConfigMap 是一个 API [对象](/zh/docs/concepts/overview/working-with-objects
让你可以存储其他对象所需要使用的配置。
和其他 Kubernetes 对象都有一个 `spec` 不同的是,ConfigMap 使用 `data`
`binaryData` 字段。这些字段能够接收键-值对作为其取值。`data``binaryData`
字段都是可选的。`data` 字段设计用来保存 UTF-8 字节序列,而 `binaryData`
被设计用来保存二进制数据作为 base64 编码的字串。
字段都是可选的。`data` 字段设计用来保存 UTF-8 字节序列,而 `binaryData`
被设计用来保存二进制数据作为 base64 编码的字串。
ConfigMap 的名字必须是一个合法的
[DNS 子域名](/zh/docs/concepts/overview/working-with-objects/names#dns-subdomain-names)。
@@ -92,11 +92,11 @@ Starting from v1.19, you can add an `immutable` field to a ConfigMap
definition to create an [immutable ConfigMap](#configmap-immutable).
-->
`data``binaryData` 字段下面的每个键的名称都必须由字母数字字符或者
`-``_``.` 组成。在 `data` 下保存的键名不可以与在 `binaryData`
出现的键名有重叠。
`-``_``.` 组成。在 `data` 下保存的键名不可以与在 `binaryData`
出现的键名有重叠。
从 v1.19 开始,你可以添加一个 `immutable` 字段到 ConfigMap 定义中,创建
[不可变更的 ConfigMap](#configmap-immutable)。
从 v1.19 开始,你可以添加一个 `immutable` 字段到 ConfigMap 定义中,
创建[不可变更的 ConfigMap](#configmap-immutable)。
<!--
## ConfigMaps and Pods
@@ -107,8 +107,8 @@ the same {{< glossary_tooltip text="namespace" term_id="namespace" >}}.
-->
## ConfigMaps 和 Pods
你可以写一个引用 ConfigMap 的 Pod 的 `spec`,并根据 ConfigMap 中的数据
在该 Pod 中配置容器。这个 Pod 和 ConfigMap 必须要在同一个
你可以写一个引用 ConfigMap 的 Pod 的 `spec`,并根据 ConfigMap 中的数据在该
Pod 中配置容器。这个 Pod 和 ConfigMap 必须要在同一个
{{< glossary_tooltip text="名字空间" term_id="namespace" >}} 中。
<!--
@@ -183,10 +183,9 @@ technique also lets you access a ConfigMap in a different namespace.
Here's an example Pod that uses values from `game-demo` to configure a Pod:
-->
第四种方法意味着你必须编写代码才能读取 ConfigMap 和它的数据。然而,
由于你是直接使用 Kubernetes API,因此只要 ConfigMap 发生更改,你的
应用就能够通过订阅来获取更新,并且在这样的情况发生的时候做出反应。
通过直接进入 Kubernetes API,这个技术也可以让你能够获取到不同的名字空间
里的 ConfigMap。
由于你是直接使用 Kubernetes API,因此只要 ConfigMap 发生更改,
你的应用就能够通过订阅来获取更新,并且在这样的情况发生的时候做出反应。
通过直接进入 Kubernetes API,这个技术也可以让你能够获取到不同的名字空间里的 ConfigMap。
下面是一个 Pod 的示例,它通过使用 `game-demo` 中的值来配置一个 Pod
@@ -243,16 +242,16 @@ definition specifies an `items` array in the `volumes` section.
If you omit the `items` array entirely, every key in the ConfigMap becomes
a file with the same name as the key, and you get 4 files.
-->
ConfigMap 不会区分单行属性值和多行类似文件的值,重要的是 Pods 和其他对象
如何使用这些值。
ConfigMap 不会区分单行属性值和多行类似文件的值,重要的是 Pods
和其他对象如何使用这些值。
上面的例子定义了一个卷并将它作为 `/config` 文件夹挂载到 `demo` 容器内,
创建两个文件,`/config/game.properties`
`/config/user-interface.properties`
尽管 ConfigMap 中包含了四个键。
这是因为 Pod 定义中在 `volumes` 节指定了一个 `items` 数组。
如果你完全忽略 `items` 数组,则 ConfigMap 中的每个键都会变成一个与
该键同名的文件,因此你会得到四个文件。
如果你完全忽略 `items` 数组,则 ConfigMap 中的每个键都会变成一个与该键同名的文件,
因此你会得到四个文件。
<!--
## Using ConfigMaps
@@ -263,9 +262,8 @@ ConfigMaps can hold data that other parts of the system should use for configura
-->
## 使用 ConfigMap {#using-configmaps}
ConfigMap 可以作为数据卷挂载。ConfigMap 也可被系统的其他组件使用,
不一定直接暴露给 Pod。例如,ConfigMap 可以保存系统中其他组件要使用
的配置数据。
ConfigMap 可以作为数据卷挂载。ConfigMap 也可被系统的其他组件使用,
不一定直接暴露给 Pod。例如,ConfigMap 可以保存系统中其他组件要使用的配置数据。
<!--
The most common way to use ConfigMaps is to configure settings for
@@ -308,8 +306,8 @@ To consume a ConfigMap in a volume in a Pod:
1. 创建一个 ConfigMap 对象或者使用现有的 ConfigMap 对象。多个 Pod 可以引用同一个
ConfigMap。
1. 修改 Pod 定义,在 `spec.volumes[]` 下添加一个卷。
为该卷设置任意名称,之后将 `spec.volumes[].configMap.name` 字段设置为对
你的 ConfigMap 对象的引用。
为该卷设置任意名称,之后将 `spec.volumes[].configMap.name` 字段设置为对你的
ConfigMap 对象的引用。
1. 为每个需要该 ConfigMap 的容器添加一个 `.spec.containers[].volumeMounts[]`
设置 `.spec.containers[].volumeMounts[].readOnly=true` 并将
`.spec.containers[].volumeMounts[].mountPath` 设置为一个未使用的目录名,
@@ -349,8 +347,8 @@ own `volumeMounts` block, but only one `.spec.volumes` is needed per ConfigMap.
-->
你希望使用的每个 ConfigMap 都需要在 `spec.volumes` 中被引用到。
如果 Pod 中有多个容器,则每个容器都需要自己的 `volumeMounts` 块,但针对
每个 ConfigMap,你只需要设置一个 `spec.volumes` 块。
如果 Pod 中有多个容器,则每个容器都需要自己的 `volumeMounts` 块,但针对每个
ConfigMap,你只需要设置一个 `spec.volumes` 块。
<!--
#### Mounted ConfigMaps are updated automatically
@@ -367,7 +365,7 @@ the [KubeletConfiguration struct](/docs/reference/config-api/kubelet-config.v1be
kubelet 组件会在每次周期性同步时检查所挂载的 ConfigMap 是否为最新。
不过,kubelet 使用的是其本地的高速缓存来获得 ConfigMap 的当前值。
高速缓存的类型可以通过
[KubeletConfiguration 结构](https://github.com/kubernetes/kubernetes/blob/{{< param "docsbranch" >}}/staging/src/k8s.io/kubelet/config/v1beta1/types.go)
[KubeletConfiguration 结构](/zh/docs/reference/config-api/kubelet-config.v1beta1/).
`ConfigMapAndSecretChangeDetectionStrategy` 字段来配置。
<!--
@@ -380,8 +378,8 @@ propagation delay, where the cache propagation delay depends on the chosen cache
-->
ConfigMap 既可以通过 watch 操作实现内容传播(默认形式),也可实现基于 TTL
的缓存,还可以直接经过所有请求重定向到 API 服务器。
因此,从 ConfigMap 被更新的那一刻算起,到新的主键被投射到 Pod 中去,这一
时间跨度可能与 kubelet 的同步周期加上高速缓存的传播延迟相等。
因此,从 ConfigMap 被更新的那一刻算起,到新的主键被投射到 Pod 中去,
这一时间跨度可能与 kubelet 的同步周期加上高速缓存的传播延迟相等。
这里的传播延迟取决于所选的高速缓存类型
(分别对应 watch 操作的传播延迟、高速缓存的 TTL 时长或者 0)。
@@ -391,6 +389,14 @@ ConfigMaps consumed as environment variables are not updated automatically and r
以环境变量方式使用的 ConfigMap 数据不会被自动更新。
更新这些数据需要重新启动 Pod。
{{< note >}}
<!--
A container using a ConfigMap as a [subPath](/docs/concepts/storage/volumes#using-subpath) volume mount will not receive ConfigMap updates.
-->
将 ConfigMap 作为 [subPath](/docs/concepts/storage/volumes#using-subpath)
卷挂载的容器无法收到 ConfigMap 更新。
{{< /note >}}
<!--
A container using a ConfigMap as a [subPath](/docs/concepts/storage/volumes#using-subpath) volume mount will not receive ConfigMap updates.
-->
@@ -412,8 +418,8 @@ individual Secrets and ConfigMaps as immutable. For clusters that extensively us
data has the following advantages:
-->
Kubernetes 特性 _不可变更的 Secret 和 ConfigMap_ 提供了一种将各个
Secret 和 ConfigMap 设置为不可变更的选项。对于大量使用 ConfigMap 的
集群(至少有数万个各不相同的 ConfigMap 给 Pod 挂载)而言,禁止更改
Secret 和 ConfigMap 设置为不可变更的选项。对于大量使用 ConfigMap 的集群
(至少有数万个各不相同的 ConfigMap 给 Pod 挂载)而言,禁止更改
ConfigMap 的数据有以下好处:
<!--
@@ -422,8 +428,8 @@ ConfigMap 的数据有以下好处:
closing watches for ConfigMaps marked as immutable.
-->
- 保护应用,使之免受意外(不想要的)更新所带来的负面影响。
- 通过大幅降低对 kube-apiserver 的压力提升集群性能,这是因为系统会关闭
对已标记为不可变更的 ConfigMap 的监视操作。
- 通过大幅降低对 kube-apiserver 的压力提升集群性能,
这是因为系统会关闭对已标记为不可变更的 ConfigMap 的监视操作。
<!--
This feature is controlled by the `ImmutableEphemeralVolumes`
@@ -432,8 +438,8 @@ You can create an immutable ConfigMap by setting the `immutable` field to `true`
For example:
-->
此功能特性由 `ImmutableEphemeralVolumes`
[特性门控](/zh/docs/reference/command-line-tools-reference/feature-gates/)
来控制。你可以通过将 `immutable` 字段设置为 `true` 创建不可变更的 ConfigMap。
[特性门控](/zh/docs/reference/command-line-tools-reference/feature-gates/)来控制。
你可以通过将 `immutable` 字段设置为 `true` 创建不可变更的 ConfigMap。
例如:
```yaml
@@ -454,8 +460,7 @@ to the deleted ConfigMap, it is recommended to recreate these pods.
-->
一旦某 ConfigMap 被标记为不可变更,则 _无法_ 逆转这一变化,,也无法更改
`data``binaryData` 字段的内容。你只能删除并重建 ConfigMap。
因为现有的 Pod 会维护一个对已删除的 ConfigMap 的挂载点,建议重新创建
这些 Pods。
因为现有的 Pod 会维护一个对已删除的 ConfigMap 的挂载点,建议重新创建这些 Pods。
## {{% heading "whatsnext" %}}
@@ -466,6 +471,6 @@ to the deleted ConfigMap, it is recommended to recreate these pods.
separating code from configuration.
-->
* 阅读 [Secret](/zh/docs/concepts/configuration/secret/)。
* 阅读 [配置 Pod 使用 ConfigMap](/zh/docs/tasks/configure-pod-container/configure-pod-configmap/)。
* 阅读 [Twelve-Factor 应用](https://12factor.net/) 来了解将代码和配置分开的动机。
* 阅读[配置 Pod 使用 ConfigMap](/zh/docs/tasks/configure-pod-container/configure-pod-configmap/)。
* 阅读 [Twelve-Factor 应用](https://12factor.net/zh_cn/)来了解将代码和配置分开的动机。
@@ -254,7 +254,7 @@ Mi, Ki. For example, the following represent roughly the same value:
```
<!--
Take care about case for suffixes. If you request `400m` of memory, this is a request
Pay attention to the case of the suffixes. If you request `400m` of memory, this is a request
for 0.4 bytes. Someone who types that probably meant to ask for 400 mebibytes (`400Mi`)
or 400 megabytes (`400M`).
-->
File diff suppressed because it is too large Load Diff
@@ -70,16 +70,17 @@ Customization approaches can be broadly divided into *configuration*, which only
*Configuration files* and *flags* are documented in the Reference section of the online documentation, under each binary:
* [kubelet](/docs/reference/command-line-tools-reference/kubelet/)
* [kube-proxy](/docs/reference/command-line-tools-reference/kube-proxy/)
* [kube-apiserver](/docs/reference/command-line-tools-reference/kube-apiserver/)
* [kube-controller-manager](/docs/reference/command-line-tools-reference/kube-controller-manager/)
* [kube-scheduler](/docs/reference/command-line-tools-reference/kube-scheduler/).
-->
## 配置 {#configuration}
## Configuration
*配置文件*和*参数标志*的说明位于在线文档的参考章节,按可执行文件组织:
配置文件和参数标志的说明位于在线文档的参考章节,按可执行文件组织:
* [kubelet](/zh/docs/reference/command-line-tools-reference/kubelet/)
* [kube-proxy](/zh/docs/reference/command-line-tools-reference/kube-proxy/)
* [kube-apiserver](/zh/docs/reference/command-line-tools-reference/kube-apiserver/)
* [kube-controller-manager](/zh/docs/reference/command-line-tools-reference/kube-controller-manager/)
* [kube-scheduler](/zh/docs/reference/command-line-tools-reference/kube-scheduler/).
@@ -94,19 +95,19 @@ Flags and configuration files may not always be changeable in a hosted Kubernete
有鉴于此,通常应该在没有其他替代方案时才应考虑更改参数标志和配置文件。
<!--
*Built-in Policy APIs*, such as [ResourceQuota](/docs/concepts/policy/resource-quotas/), [PodSecurityPolicies](/docs/concepts/policy/pod-security-policy/), [NetworkPolicy](/docs/concepts/services-networking/network-policies/) and Role-based Access Control ([RBAC](/docs/reference/access-authn-authz/rbac/)), are built-in Kubernetes APIs. APIs are typically used with hosted Kubernetes services and with managed Kubernetes installations. They are declarative and use the same conventions as other Kubernetes resources like pods, so new cluster configuration can be repeatable and be managed the same way as applications. And, where they are stable, they enjoy a [defined support policy](/docs/reference/deprecation-policy/) like other Kubernetes APIs. For these reasons, they are preferred over *configuration files* and *flags* where suitable.
*Built-in Policy APIs*, such as [ResourceQuota](/docs/concepts/policy/resource-quotas/), [PodSecurityPolicies](/docs/concepts/policy/pod-security-policy/), [NetworkPolicy](/docs/concepts/services-networking/network-policies/) and Role-based Access Control ([RBAC](/docs/reference/access-authn-authz/rbac/)), are built-in Kubernetes APIs. APIs are typically used with hosted Kubernetes services and with managed Kubernetes installations. They are declarative and use the same conventions as other Kubernetes resources like pods, so new cluster configuration can be repeatable and be managed the same way as applications. And, where they are stable, they enjoy a [defined support policy](/docs/reference/using-api/deprecation-policy/) like other Kubernetes APIs. For these reasons, they are preferred over *configuration files* and *flags* where suitable.
-->
*内置的策略 API*,例如[ResourceQuota](/zh/docs/concepts/policy/resource-quotas/)、
[PodSecurityPolicies](/zh/docs/concepts/policy/pod-security-policy/)、
[NetworkPolicy](/zh/docs/concepts/services-networking/network-policies/)
和基于角色的访问控制([RBAC](/zh/docs/reference/access-authn-authz/rbac/)等等
都是内置的 Kubernetes API。
和基于角色的访问控制([RBAC](/zh/docs/reference/access-authn-authz/rbac/)
等等都是内置的 Kubernetes API。
API 通常用于托管的 Kubernetes 服务和受控的 Kubernetes 安装环境中。
这些 API 是声明式的,与 Pod 这类其他 Kubernetes 资源遵从相同的约定,所以
新的集群配置是可复用的,并且可以当作应用程序来管理。
此外,对于稳定版本的 API 而言,它们与其他 Kubernetes API 一样,采纳的是
一种[预定义的支持策略](/zh/docs/reference/using-api/deprecation-policy/)。
出于以上原因,在条件允许的情况下,基于 API 的方案应该优先于*配置文件*和*参数标志*
这些 API 是声明式的,与 Pod 这类其他 Kubernetes 资源遵从相同的约定,
所以新的集群配置是可复用的,并且可以当作应用程序来管理。
此外,对于稳定版本的 API 而言,它们与其他 Kubernetes API 一样,
采纳的是一种[预定义的支持策略](/zh/docs/reference/using-api/deprecation-policy/)。
出于以上原因,在条件允许的情况下,基于 API 的方案应该优先于配置文件参数标志。
<!--
## Extensions
@@ -114,9 +115,9 @@ API 通常用于托管的 Kubernetes 服务和受控的 Kubernetes 安装环境
Extensions are software components that extend and deeply integrate with Kubernetes.
They adapt it to support new types and new kinds of hardware.
Most cluster administrators will use a hosted or distribution
instance of Kubernetes. As a result, most Kubernetes users will not need to
install extensions and fewer will need to author new ones.
Many cluster administrators use a hosted or distribution instance of Kubernetes.
These clusters come with extensions pre-installed. As a result, most Kubernetes
users will not need to install extensions and even fewer users will need to author new ones.
-->
## 扩展 {#extensions}
@@ -124,7 +125,7 @@ install extensions and fewer will need to author new ones.
它们调整 Kubernetes 的工作方式使之支持新的类型和新的硬件种类。
大多数集群管理员会使用一种托管的 Kubernetes 服务或者其某种发行版本。
因此,大多数 Kubernetes 用户不需要安装扩展,
这类集群通常都预先安装了扩展。因此,大多数 Kubernetes 用户不需要安装扩展,
至于需要自己编写新的扩展的情况就更少了。
<!--
@@ -155,31 +156,29 @@ calls out to a remote service, it is called a *Webhook*. The remote service
is called a *Webhook Backend*. Like Controllers, Webhooks do add a point of
failure.
-->
编写客户端程序有一种特殊的 *Controller(控制器)* 模式,能够与 Kubernetes 很好地
协同工作。控制器通常会读取某个对象的 `.spec`,或许还会执行一些操作,之后更新
对象的 `.status`
*Controller(控制器)* 是 Kubernetes 的客户端。
编写客户端程序有一种特殊的 Controller控制器模式,能够与 Kubernetes
很好地协同工作。控制器通常会读取某个对象的 `.spec`,或许还会执行一些操作,
之后更新对象的 `.status`
当 Kubernetes 充当客户端,调用某远程服务时,对应
的远程组件称作*Webhook*。 远程服务称作*Webhook 后端*。
Controller 是 Kubernetes 的客户端。当 Kubernetes 充当客户端,
调用某远程服务时,对应的远程组件称作 *Webhook*远程服务称作 Webhook 后端
与控制器模式相似,Webhook 也会在整个架构中引入新的失效点(Point of Failure)。
<!--
In the webhook model, Kubernetes makes a network request to a remote service.
In the *Binary Plugin* model, Kubernetes executes a binary (program).
Binary plugins are used by the kubelet (e.g. [Flex Volume
Plugins](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-storage/flexvolume.md)
and [Network
Plugins](/docs/concepts/cluster-administration/network-plugins/))
Binary plugins are used by the kubelet (e.g.
[Flex Volume Plugins](/docs/concepts/storage/volumes/#flexvolume)
and [Network Plugins](/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/))
and by kubectl.
Below is a diagram showing how the extension points interact with the
Kubernetes control plane.
-->
在 Webhook 模式中,Kubernetes 向远程服务发起网络请求。
*可执行文件插件(Binary Plugin* 模式中,Kubernetes 执行某个可执行文件(程序)。
可执行文件插件在 kubelet (例如,
[FlexVolume 插件](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-storage/flexvolume.md)
**可执行文件插件(Binary Plugin** 模式中,Kubernetes
执行某个可执行文件(程序)。可执行文件插件在 kubelet (例如,
[FlexVolume 插件](/zh/docs/concepts/storage/volumes/#flexvolume))
和[网络插件](/zh/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/)
和 kubectl 中使用。
@@ -223,12 +222,11 @@ If you are unsure where to start, this flowchart can help. Note that some soluti
2. API 服务器处理所有请求。API 服务器中的几种扩展点能够使用户对请求执行身份认证、
基于其内容阻止请求、编辑请求内容、处理删除操作等等。
这些扩展点在 [API 访问扩展](#api-access-extensions)
节详述。
这些扩展点在 [API 访问扩展](#api-access-extensions)节详述。
3. API 服务器向外提供不同类型的*资源(resources*
*内置的资源类型*,如 `pods`,是由 Kubernetes 项目所定义的,无法改变。
你也可以添加自己定义的或者其他项目所定义的称作*自定义资源(Custom Resources*
3. API 服务器向外提供不同类型的资源(resources)。
内置的资源类型,如 `pods`,是由 Kubernetes 项目所定义的,无法改变。
你也可以添加自己定义的或者其他项目所定义的称作自定义资源(Custom Resources
的资源,正如[自定义资源](#user-defined-types)节所描述的那样。
自定义资源通常与 API 访问扩展点结合使用。
@@ -236,12 +234,12 @@ If you are unsure where to start, this flowchart can help. Note that some soluti
有几种方式来扩展调度行为。这些方法将在
[调度器扩展](#scheduler-extensions)节中展开。
5. Kubernetes 中的很多行为都是通过称为控制器(Controllers)的程序来实现的,这些程序也都是 API 服务器
的客户端。控制器常常与自定义资源结合使用。
5. Kubernetes 中的很多行为都是通过称为控制器(Controllers)的程序来实现的,
这些程序也都是 API 服务器的客户端。控制器常常与自定义资源结合使用。
6. 组件 kubelet 运行在各个节点上,帮助 Pod 展现为虚拟的服务器并在集群网络中拥有自己的 IP。
[网络插件](#network-plugins)使得 Kubernetes 能够采用
不同实现技术来连接 Pod 网络。
[网络插件](#network-plugins)使得 Kubernetes 能够采用不同实现技术来连接
Pod 网络。
7. 组件 kubelet 也会为容器增加或解除存储卷的挂载。
通过[存储插件](#storage-plugins),可以支持新的存储类型。
@@ -320,9 +318,8 @@ Kubernetes has several built-in authentication methods that it supports. It can
这些步骤中都存在扩展点。
Kubernetes 提供若干内置的身份认证方法。
它也可以运行在某中身份认证代理的后面,并且可以将来自鉴权头部的令牌发送到
某个远程服务(Webhook)来执行验证操作。
Kubernetes 提供若干内置的身份认证方法。它也可以运行在某种身份认证代理的后面,
并且可以将来自鉴权头部的令牌发送到某个远程服务(Webhook)来执行验证操作。
所有这些方法都在[身份认证文档](/zh/docs/reference/access-authn-authz/authentication/)
中有详细论述。
@@ -345,12 +342,12 @@ Kubernetes 提供若干种内置的认证方法,以及
<!--
### Authorization
[Authorization](/docs/reference/access-authn-authz/webhook/) determines whether specific users can read, write, and do other operations on API resources. It works at the level of whole resources - it doesn't discriminate based on arbitrary object fields. If the built-in authorization options don't meet your needs, and [Authorization webhook](/docs/reference/access-authn-authz/webhook/) allows calling out to user-provided code to make an authorization decision.
[Authorization](/docs/reference/access-authn-authz/authorization/) determines whether specific users can read, write, and do other operations on API resources. It works at the level of whole resources - it doesn't discriminate based on arbitrary object fields. If the built-in authorization options don't meet your needs, and [Authorization webhook](/docs/reference/access-authn-authz/webhook/) allows calling out to user-provided code to make an authorization decision.
-->
### 鉴权 {#authorization}
[鉴权](/zh/docs/reference/access-authn-authz/webhook/)操作负责确定特定的用户
是否可以读、写 API 资源或对其执行其他操作。
[鉴权](/zh/docs/reference/access-authn-authz/authorization/)
操作负责确定特定的用户是否可以读、写 API 资源或对其执行其他操作。
此操作仅在整个资源集合的层面进行。
换言之,它不会基于对象的特定字段作出不同的判决。
如果内置的鉴权选项无法满足你的需要,你可以使用
@@ -371,10 +368,10 @@ After a request is authorized, if it is a write operation, it also goes through
[准入控制](/zh/docs/reference/access-authn-authz/admission-controllers/)处理步骤。
除了内置的处理步骤,还存在一些扩展点:
* [Image Policy webhook](/zh/docs/reference/access-authn-authz/admission-controllers/#imagepolicywebhook)
* [镜像策略 Webhook](/zh/docs/reference/access-authn-authz/admission-controllers/#imagepolicywebhook)
能够限制容器中可以运行哪些镜像。
* 为了执行任意的准入控制,可以使用一种通用的
[Admission webhook](/zh/docs/reference/access-authn-authz/extensible-admission-controllers/#admission-webhooks)
[准入 Webhook](/zh/docs/reference/access-authn-authz/extensible-admission-controllers/#admission-webhooks)
机制。这类 Webhook 可以拒绝对象创建或更新请求。
<!--
@@ -392,8 +389,15 @@ Kubelet call a Binary Plugin to mount the volume.
[FlexVolumes](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/storage/flexvolume-deployment.md
)
卷可以让用户挂载无需内建支持的卷类型,kubelet 会调用可执行文件插件
来挂载对应的存储卷。
卷可以让用户挂载无需内建支持的卷类型,
kubelet 会调用可执行文件插件来挂载对应的存储卷。
<!--
FlexVolume is deprecated since Kubernetes v1.23. The Out-of-tree CSI driver is the recommended way to write volume drivers in Kubernetes. See [Kubernetes Volume Plugin FAQ for Storage Vendors](https://github.com/kubernetes/community/blob/master/sig-storage/volume-plugin-faq.md#kubernetes-volume-plugin-faq-for-storage-vendors) for more information.
-->
从 Kubernetes v1.23 开始,FlexVolume 被弃用。
在 Kubernetes 中编写卷驱动的推荐方式是使用树外(Out-of-treeCSI 驱动。
详细信息可参阅 [Kubernetes Volume Plugin FAQ for Storage Vendors](https://github.com/kubernetes/community/blob/master/sig-storage/volume-plugin-faq.md#kubernetes-volume-plugin-faq-for-storage-vendors)。
<!--
### Device Plugins
@@ -413,8 +417,8 @@ Different networking fabrics can be supported via node-level [Network Plugins](/
### 网络插件 {#network-plugins}
通过节点层面的[网络插件](/zh/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/)可以支持
不同的网络设施。
通过节点层面的[网络插件](/zh/docs/concepts/extend-kubernetes/compute-storage-net/network-plugins/)
可以支持不同的网络设施。
<!--
### Scheduler Extensions
@@ -447,7 +451,6 @@ the nodes chosen for a pod.
[Webhook](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/scheduling/scheduler_extender.md)
允许使用某种 Webhook 后端(调度器扩展)来为 Pod 可选的节点执行过滤和优先排序操作。
## {{% heading "whatsnext" %}}
<!--
@@ -467,4 +470,3 @@ the nodes chosen for a pod.
* 了解 [kubectl 插件](/zh/docs/tasks/extend-kubectl/kubectl-plugins/)
* 了解 [Operator 模式](/zh/docs/concepts/extend-kubernetes/operator/)
@@ -51,7 +51,7 @@ many core Kubernetes functions are now built using custom resources, making Kube
Custom resources can appear and disappear in a running cluster through dynamic registration,
and cluster admins can update custom resources independently of the cluster itself.
Once a custom resource is installed, users can create and access its objects using
[kubectl](/docs/reference/kubectl/overview/), just as they do for built-in resources like
[kubectl](/docs/reference/kubectl/), just as they do for built-in resources like
*Pods*.
-->
*定制资源(Custom Resource* 是对 Kubernetes API 的扩展,不一定在默认的
@@ -61,7 +61,7 @@ Kubernetes 安装中就可用。定制资源所代表的是对特定 Kubernetes
定制资源可以通过动态注册的方式在运行中的集群内或出现或消失,集群管理员可以独立于集群
更新定制资源。一旦某定制资源被安装,用户可以使用
[kubectl](/zh/docs/reference/kubectl/overview/)
[kubectl](/docs/reference/kubectl/)
来创建和访问其中的对象,就像他们为 *pods* 这种内置资源所做的一样。
<!--
@@ -323,7 +323,7 @@ making them available to all of its clients.
-->
## API 服务器聚合 {#api-server-aggregation}
通常,Kubernetes API 中的每个都需要处理 REST 请求和管理对象持久性存储的代码。
通常,Kubernetes API 中的每个资源都需要处理 REST 请求和管理对象持久性存储的代码。
Kubernetes API 主服务器能够处理诸如 *pods**services* 这些内置资源,也可以
按通用的方式通过 [CRD](#customresourcedefinitions) 来处理定制资源。
@@ -43,13 +43,13 @@ Kubernetes 作为一个项目,目前支持和维护
{{% thirdparty-content %}}
<!--
* [AKS Application Gateway Ingress Controller](https://azure.github.io/application-gateway-kubernetes-ingress/) is an ingress controller that configures the [Azure Application Gateway](https://docs.microsoft.com/azure/application-gateway/overview).
* [AKS Application Gateway Ingress Controller](https://docs.microsoft.com/azure/application-gateway/tutorial-ingress-controller-add-on-existing?toc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Faks%2Ftoc.json&bc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fbread%2Ftoc.json) is an ingress controller that configures the [Azure Application Gateway](https://docs.microsoft.com/azure/application-gateway/overview).
* [Ambassador](https://www.getambassador.io/) API Gateway is an [Envoy](https://www.envoyproxy.io)-based ingress
controller.
* [Apache APISIX ingress controller](https://github.com/apache/apisix-ingress-controller) is an [Apache APISIX](https://github.com/apache/apisix)-based ingress controller.
* [Avi Kubernetes Operator](https://github.com/vmware/load-balancer-and-ingress-services-for-kubernetes) provides L4-L7 load-balancing using [VMware NSX Advanced Load Balancer](https://avinetworks.com/).
-->
* [AKS 应用程序网关 Ingress 控制器](https://azure.github.io/application-gateway-kubernetes-ingress/)
* [AKS 应用程序网关 Ingress 控制器](https://docs.microsoft.com/azure/application-gateway/tutorial-ingress-controller-add-on-existing?toc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Faks%2Ftoc.json&bc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fbread%2Ftoc.json)
是一个配置 [Azure 应用程序网关](https://docs.microsoft.com/azure/application-gateway/overview)
的 Ingress 控制器。
* [Ambassador](https://www.getambassador.io/) API 网关是一个基于
@@ -34,7 +34,7 @@ Currently, the following types of volume sources can be projected:
* [`secret`](/docs/concepts/storage/volumes/#secret)
* [`downwardAPI`](/docs/concepts/storage/volumes/#downwardapi)
* [`configMap`](/docs/concepts/storage/volumes/#configmap)
* `serviceAccountToken`
* [`serviceAccountToken`](#serviceaccounttoken)
-->
## 介绍 {#introduction}
@@ -45,7 +45,7 @@ Currently, the following types of volume sources can be projected:
* [`secret`](/zh/docs/concepts/storage/volumes/#secret)
* [`downwardAPI`](/zh/docs/concepts/storage/volumes/#downwardapi)
* [`configMap`](/zh/docs/concepts/storage/volumes/#configmap)
* `serviceAccountToken`
* [`serviceAccountToken`](#serviceaccounttoken)
<!--
All sources are required to be in the same namespace as the Pod. For more details,
@@ -85,10 +85,12 @@ parameters are nearly the same with two exceptions:
你可以显式地为每个投射单独设置 `mode` 属性。
<!--
## serviceAccountToken projected volumes {#serviceaccounttoken}
When the `TokenRequestProjection` feature is enabled, you can inject the token
for the current [service account](/docs/reference/access-authn-authz/authentication/#service-account-tokens)
into a Pod at a specified path. For example:
-->
## serviceAccountToken 投射卷 {#serviceaccounttoken}
`TokenRequestProjection` 特性被启用时,你可以将当前
[服务账号](/zh/docs/reference/access-authn-authz/authentication/#service-account-tokens)
的令牌注入到 Pod 中特定路径下。例如:
@@ -97,14 +99,17 @@ into a Pod at a specified path. For example:
<!--
The example Pod has a projected volume containing the injected service account
token. This token can be used by a Pod's containers to access the Kubernetes API
server. The `audience` field contains the intended audience of the
token. Containers in this Pod can use that token to access the Kubernetes API
server, authenticating with the identity of [the pod's ServiceAccount](/docs/tasks/configure-pod-container/configure-service-account/).
The `audience` field contains the intended audience of the
token. A recipient of the token must identify itself with an identifier specified
in the audience of the token, and otherwise should reject the token. This field
is optional and it defaults to the identifier of the API server.
-->
示例 Pod 中包含一个投射卷,其中包含注入的服务账号令牌。该令牌可以被 Pod
中的容器用来访问 Kubernetes API 服务器`audience` 字段包含令牌所针对的受众。
示例 Pod 中包含一个投射卷,其中包含注入的服务账号令牌。
此 Pod 中的容器可以使用该令牌访问 Kubernetes API 服务器 使用
[pod 的 ServiceAccount](/zh/docs/tasks/configure-pod-container/configure-service-account/)
进行身份验证。`audience` 字段包含令牌所针对的受众。
收到令牌的主体必须使用令牌受众中所指定的某个标识符来标识自身,否则应该拒绝该令牌。
此字段是可选的,默认值为 API 服务器的标识。
@@ -209,7 +209,7 @@ If you do not specify either, then the DaemonSet controller will create Pods on
### 通过默认调度器调度 {#scheduled-by-default-scheduler}
{{< feature-state state="stable" for-kubernetes-version="1.17" >}}
{{< feature-state for_kubernetes_version="1.17" state="stable" >}}
<!--
A DaemonSet ensures that all eligible nodes run a copy of a Pod. Normally, the
@@ -183,7 +183,7 @@ Here are some ideas for how to use init containers:
* 等待一个 Service 完成创建,通过类似如下 shell 命令:
```shell
for i in {1..100}; do sleep 1; if dig myservice; then exit 0; fi; exit 1
for i in {1..100}; do sleep 1; if dig myservice; then exit 0; fi; done; exit 1
```
* 注册这个 Pod 到远程服务器,通过在命令中调用 API,类似如下:
@@ -75,7 +75,7 @@ node4 Ready <none> 2m43s v1.16.0 node=node4,zone=zoneB
<!--
Then the cluster is logically viewed as below:
-->
然后从逻辑上看集群如下:
那么,从逻辑上看集群如下:
{{<mermaid>}}
graph TB
@@ -96,11 +96,9 @@ graph TB
{{< /mermaid >}}
<!--
Instead of manually applying labels, you can also reuse the [well-known labels](/docs/reference/labels-annotations-taints/) that are created and populated automatically on most clusters.
-->
你可以复用在大多数集群上自动创建和填充的
[常用标签](/zh/docs/reference/labels-annotations-taints/)
你可以复用在大多数集群上自动创建和填充的[常用标签](/zh/docs/reference/labels-annotations-taints/)
而不是手动添加标签。
<!--
@@ -169,6 +167,12 @@ You can define one or multiple `topologySpreadConstraint` to instruct the kube-s
拓扑域中 Pod 的数量。
有关详细信息,请参考[标签选择算符](/zh/docs/concepts/overview/working-with-objects/labels/#label-selectors)。
<!--
When a Pod defines more than one `topologySpreadConstraint`, those constraints are ANDed: The kube-scheduler looks for a node for the incoming Pod that satisfies all the constraints.
-->
当 Pod 定义了不止一个 `topologySpreadConstraint`,这些约束之间是逻辑与的关系。
kube-scheduler 会为新的 Pod 寻找一个能够满足所有约束的节点。
<!--
You can read more about this field by running `kubectl explain Pod.spec.topologySpreadConstraints`.
-->
@@ -353,7 +357,6 @@ graph BT
class zoneA,zoneB cluster;
{{< /mermaid >}}
<!--
If you apply "two-constraints.yaml" to this cluster, you will notice "mypod" stays in `Pending` state. This is because: to satisfy the first constraint, "mypod" can only be put to "zoneB"; while in terms of the second constraint, "mypod" can only put to "node2". Then a joint result of "zoneB" and "node2" returns nothing.
-->
@@ -374,54 +377,59 @@ The scheduler will skip the non-matching nodes from the skew calculations if the
-->
### 节点亲和性与节点选择器的相互作用 {#interaction-with-node-affinity-and-node-selectors}
如果 Pod 定义了 `spec.nodeSelector``spec.affinity.nodeAffinity`调度器将从倾斜计算中跳过不匹配的节点。
如果 Pod 定义了 `spec.nodeSelector``spec.affinity.nodeAffinity`
调度器将在偏差计算中跳过不匹配的节点。
<!--
Suppose you have a 5-node cluster ranging from zoneA to zoneC:
### Example: TopologySpreadConstraints with NodeAffinity
and you know that "zoneC" must be excluded. In this case, you can compose the yaml as below, so that "mypod" will be placed onto "zoneB" instead of "zoneC". Similarly `spec.nodeSelector` is also respected.
{{< codenew file="pods/topology-spread-constraints/one-constraint-with-nodeaffinity.yaml" >}}
Suppose you have a 5-node cluster ranging from zoneA to zoneC:
-->
假设你有一个跨越 zoneA 到 zoneC 的 5 节点集群:
### 示例:TopologySpreadConstraints 与 NodeAffinity
{{<mermaid>}}
graph BT
subgraph "zoneB"
p3(Pod) --> n3(Node3)
n4(Node4)
end
subgraph "zoneA"
p1(Pod) --> n1(Node1)
p2(Pod) --> n2(Node2)
end
假设你有一个跨越 zoneA 到 zoneC 的 5 节点集群:
classDef plain fill:#ddd,stroke:#fff,stroke-width:4px,color:#000;
classDef k8s fill:#326ce5,stroke:#fff,stroke-width:4px,color:#fff;
classDef cluster fill:#fff,stroke:#bbb,stroke-width:2px,color:#326ce5;
class n1,n2,n3,n4,p1,p2,p3 k8s;
class p4 plain;
class zoneA,zoneB cluster;
{{< /mermaid >}}
{{<mermaid>}}
graph BT
subgraph "zoneB"
p3(Pod) --> n3(Node3)
n4(Node4)
end
subgraph "zoneA"
p1(Pod) --> n1(Node1)
p2(Pod) --> n2(Node2)
end
{{<mermaid>}}
graph BT
subgraph "zoneC"
n5(Node5)
end
classDef plain fill:#ddd,stroke:#fff,stroke-width:4px,color:#000;
classDef k8s fill:#326ce5,stroke:#fff,stroke-width:4px,color:#fff;
classDef cluster fill:#fff,stroke:#bbb,stroke-width:2px,color:#326ce5;
class n1,n2,n3,n4,p1,p2,p3 k8s;
class p4 plain;
class zoneA,zoneB cluster;
{{< /mermaid >}}
classDef plain fill:#ddd,stroke:#fff,stroke-width:4px,color:#000;
classDef k8s fill:#326ce5,stroke:#fff,stroke-width:4px,color:#fff;
classDef cluster fill:#fff,stroke:#bbb,stroke-width:2px,color:#326ce5;
class n5 k8s;
class zoneC cluster;
{{< /mermaid >}}
{{<mermaid>}}
graph BT
subgraph "zoneC"
n5(Node5)
end
而且你知道 "zoneC" 必须被排除在外。在这种情况下,可以按如下方式编写 yaml,
以便将 "mypod" 放置在 "zoneB" 上,而不是 "zoneC" 上。同样,`spec.nodeSelector`
也要一样处理。
classDef plain fill:#ddd,stroke:#fff,stroke-width:4px,color:#000;
classDef k8s fill:#326ce5,stroke:#fff,stroke-width:4px,color:#fff;
classDef cluster fill:#fff,stroke:#bbb,stroke-width:2px,color:#326ce5;
class n5 k8s;
class zoneC cluster;
{{< /mermaid >}}
{{< codenew file="pods/topology-spread-constraints/one-constraint-with-nodeaffinity.yaml" >}}
<!--
and you know that "zoneC" must be excluded. In this case, you can compose the yaml as below, so that "mypod" will be placed onto "zoneB" instead of "zoneC". Similarly `spec.nodeSelector` is also respected.
-->
而且你知道 "zoneC" 必须被排除在外。在这种情况下,可以按如下方式编写 YAML,
以便将 "mypod" 放置在 "zoneB" 上,而不是 "zoneC" 上。同样,`spec.nodeSelector`
也要一样处理。
{{< codenew file="pods/topology-spread-constraints/one-constraint-with-nodeaffinity.yaml" >}}
<!--
The scheduler doesn't have prior knowledge of all the zones or other topology domains that a cluster has. They are determined from the existing nodes in the cluster. This could lead to a problem in autoscaled clusters, when a node pool (or node group) is scaled to zero nodes and the user is expecting them to scale up, because, in this case, those topology domains won't be considered until there is at least one node in them.
@@ -503,7 +511,7 @@ An example configuration might look like follows:
配置的示例可能看起来像下面这个样子:
```yaml
apiVersion: kubescheduler.config.k8s.io/v1beta1
apiVersion: kubescheduler.config.k8s.io/v1beta3
kind: KubeSchedulerConfiguration
profiles:
@@ -565,20 +573,24 @@ is disabled.
-->
此外,原来用于提供等同行为的 `SelectorSpread` 插件也会被禁用。
{{< note >}}
<!--
The `PodTopologySpread` plugin does not score the nodes that don't have
the topology keys specified in the spreading constraints. This might result
in a different default behavior compared to the legacy `SelectorSpread` plugin when
using the default topology constraints.
-->
对于分布约束中所指定的拓扑键而言,`PodTopologySpread` 插件不会为不包含这些主键的节点评分。
这可能导致在使用默认拓扑约束时,其行为与原来的 `SelectorSpread` 插件的默认行为不同,
<!--
If your nodes are not expected to have **both** `kubernetes.io/hostname` and
`topology.kubernetes.io/zone` labels set, define your own constraints
instead of using the Kubernetes defaults.
The `PodTopologySpread` plugin does not score the nodes that don't have
the topology keys specified in the spreading constraints.
-->
{{< note >}}
如果你的节点不会 **同时** 设置 `kubernetes.io/hostname`
`topology.kubernetes.io/zone` 标签,你应该定义自己的约束而不是使用
Kubernetes 的默认约束。
插件 `PodTopologySpread` 不会为未设置分布约束中所给拓扑键的节点评分。
{{< /note >}}
<!--
@@ -586,11 +598,11 @@ If you don't want to use the default Pod spreading constraints for your cluster,
you can disable those defaults by setting `defaultingType` to `List` and leaving
empty `defaultConstraints` in the `PodTopologySpread` plugin configuration:
-->
如果你不想为集群使用默认的 Pod 分布约束,你可以通过设置 `defaultingType` 参数为 `List`
`PodTopologySpread` 插件配置中的 `defaultConstraints` 参数置空来禁用默认 Pod 分布约束。
如果你不想为集群使用默认的 Pod 分布约束,你可以通过设置 `defaultingType` 参数为 `List`
`PodTopologySpread` 插件配置中的 `defaultConstraints` 参数置空来禁用默认 Pod 分布约束。
```yaml
apiVersion: kubescheduler.config.k8s.io/v1beta1
apiVersion: kubescheduler.config.k8s.io/v1beta3
kind: KubeSchedulerConfiguration
profiles:
@@ -613,9 +625,9 @@ scheduled - more packed or more scattered.
<!--
- For `PodAffinity`, you can try to pack any number of Pods into qualifying
topology domain(s)
topology domain(s)
- For `PodAntiAffinity`, only one Pod can be scheduled into a
single topology domain.
single topology domain.
-->
- 对于 `PodAffinity`,你可以尝试将任意数量的 Pod 集中到符合条件的拓扑域中。
- 对于 `PodAntiAffinity`,只能将一个 Pod 调度到某个拓扑域中。
@@ -627,12 +639,6 @@ cost-saving. This can also help on rolling update workloads and scaling out
replicas smoothly. See
[Motivation](https://github.com/kubernetes/enhancements/tree/master/keps/sig-scheduling/895-pod-topology-spread#motivation)
for more details.
The "EvenPodsSpread" feature provides flexible options to distribute Pods evenly across different
topology domains - to achieve high availability or cost-saving. This can also help on rolling update
workloads and scaling out replicas smoothly.
See [Motivation](https://github.com/kubernetes/enhancements/blob/master/keps/sig-scheduling/20190221-pod-topology-spread.md#motivation) for more details.
-->
要实现更细粒度的控制,你可以设置拓扑分布约束来将 Pod 分布到不同的拓扑域下,
从而实现高可用性或节省成本。这也有助于工作负载的滚动更新和平稳地扩展副本规模。
@@ -642,13 +648,19 @@ See [Motivation](https://github.com/kubernetes/enhancements/blob/master/keps/sig
<!--
## Known Limitations
- Scaling down a Deployment may result in imbalanced Pods distribution.
- There's no guarantee that the constraints remain satisfied when Pods are removed. For example, scaling down a Deployment may result in imbalanced Pods distribution.
You can use [Descheduler](https://github.com/kubernetes-sigs/descheduler) to rebalance the Pods distribution.
- Pods matched on tainted nodes are respected. See [Issue 80921](https://github.com/kubernetes/kubernetes/issues/80921)
-->
## 已知局限性
- Deployment 缩容操作可能导致 Pod 分布不平衡。
- 具有污点的节点上的 Pods 也会被统计
- 当 Pod 被移除时,无法保证约束仍被满足。例如,缩减某 Deployment 的规模时,
Pod 的分布可能不再均衡
你可以使用 [Descheduler](https://github.com/kubernetes-sigs/descheduler)
来重新实现 Pod 分布的均衡。
- 具有污点的节点上匹配的 Pods 也会被统计。
参考 [Issue 80921](https://github.com/kubernetes/kubernetes/issues/80921)。
## {{% heading "whatsnext" %}}
File diff suppressed because it is too large Load Diff
@@ -233,7 +233,7 @@ token,user,uid,"group1,group2,group3"
When using bearer token authentication from an http client, the API
server expects an `Authorization` header with a value of `Bearer
THETOKEN`. The bearer token must be a character sequence that can be
<token>`. The bearer token must be a character sequence that can be
put in an HTTP header value using no more than the encoding and
quoting facilities of HTTP. For example: if the bearer token is
`31ada4fd-adec-460c-809a-9e56ceb75269` then it would appear in an HTTP
@@ -242,7 +242,7 @@ header as shown below.
#### 在请求中放入持有者令牌 {#putting-a-bearer-token-in-a-request}
当使用持有者令牌来对某 HTTP 客户端执行身份认证时,API 服务器希望看到
一个名为 `Authorization` 的 HTTP 头,其值格式为 `Bearer THETOKEN`
一个名为 `Authorization` 的 HTTP 头,其值格式为 `Bearer <token>`
持有者令牌必须是一个可以放入 HTTP 头部值字段的字符序列,至多可使用
HTTP 的编码和引用机制。
例如:如果持有者令牌为 `31ada4fd-adec-460c-809a-9e56ceb75269`,则其
@@ -273,11 +273,9 @@ of provisioning.
<!--
Bootstrap tokens are a simpler and more easily managed method to authenticate kubelets, and do not require any additional flags when starting kube-apiserver.
Using bootstrap tokens is currently __beta__ as of Kubernetes version 1.12.
-->
启动引导令牌是一种对 kubelet 进行身份认证的方法,相对简单且容易管理,
且不需要在启动 kube-apiserver 时设置额外的标志。
启动引导令牌从 Kubernetes 1.12 开始是一种 __Beta__ 功能特性。
<!--
Whichever method you choose, the requirement is that the kubelet be able to authenticate as a user with the rights to:
@@ -0,0 +1,49 @@
---
api_metadata:
apiVersion: ""
import: "k8s.io/apimachinery/pkg/apis/meta/v1"
kind: "Patch"
content_type: "api_reference"
description: "提供 Patch 是为了给 Kubernetes PATCH 请求正文提供一个具体的名称和类型。"
title: "Patch"
weight: 9
auto_generated: true
---
<!--
api_metadata:
apiVersion: ""
import: "k8s.io/apimachinery/pkg/apis/meta/v1"
kind: "Patch"
content_type: "api_reference"
description: "Patch is provided to give a concrete name and type to the Kubernetes PATCH request body."
title: "Patch"
weight: 9
auto_generated: true
-->
<!--
The file is auto-generated from the Go source code of the component using a generic
[generator](https://github.com/kubernetes-sigs/reference-docs/). To learn how
to generate the reference documentation, please read
[Contributing to the reference documentation](/docs/contribute/generate-ref-docs/).
To update the reference content, please follow the
[Contributing upstream](/docs/contribute/generate-ref-docs/contribute-upstream/)
guide. You can file document formatting bugs against the
[reference-docs](https://github.com/kubernetes-sigs/reference-docs/) project.
-->
`import "k8s.io/apimachinery/pkg/apis/meta/v1"`
<!-- Patch is provided to give a concrete name and type to the Kubernetes PATCH request body. -->
提供 Patch 是为了给 Kubernetes PATCH 请求正文提供一个具体的名称和类型。
<hr>
@@ -0,0 +1,135 @@
---
api_metadata:
apiVersion: ""
import: "k8s.io/apimachinery/pkg/api/resource"
kind: "Quantity"
content_type: "api_reference"
description: "数量(Quantity)是数字的定点表示。"
title: "Quantity"
weight: 10
auto_generated: true
---
<!--
api_metadata:
apiVersion: ""
import: "k8s.io/apimachinery/pkg/api/resource"
kind: "Quantity"
content_type: "api_reference"
description: "Quantity is a fixed-point representation of a number."
title: "Quantity"
weight: 10
auto_generated: true
-->
<!--
The file is auto-generated from the Go source code of the component using a generic
[generator](https://github.com/kubernetes-sigs/reference-docs/). To learn how
to generate the reference documentation, please read
[Contributing to the reference documentation](/docs/contribute/generate-ref-docs/).
To update the reference content, please follow the
[Contributing upstream](/docs/contribute/generate-ref-docs/contribute-upstream/)
guide. You can file document formatting bugs against the
[reference-docs](https://github.com/kubernetes-sigs/reference-docs/) project.
-->
`import "k8s.io/apimachinery/pkg/api/resource"`
<!--
Quantity is a fixed-point representation of a number.
It provides convenient marshaling/unmarshaling in JSON and YAML,
in addition to String() and AsInt64() accessors.
The serialization format is:
-->
数量(Quantity)是数字的定点表示。
除了 String() 和 AsInt64() 的访问接口之外,
它以 JSON 和 YAML形式提供方便的打包和解包方法。
序列化格式如下:
<!--
\<quantity> ::= \<signedNumber>\<suffix>
(Note that \<suffix> may be empty, from the "" case in \<decimalSI>.)
\<digit> ::= 0 | 1 | ... | 9
\<digits> ::= \<digit> | \<digit>\<digits>
\<number> ::= \<digits> | \<digits>.\<digits> | \<digits>. | .\<digits>
\<sign> ::= "+" | "-"
\<signedNumber> ::= \<number> | \<sign>\<number>
\<suffix> ::= \<binarySI> | \<decimalExponent> | \<decimalSI>
\<binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
(International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)
\<decimalSI> ::= m | "" | k | M | G | T | P | E
(Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
\<decimalExponent> ::= "e" \<signedNumber> | "E" \<signedNumber>
-->
```
<quantity> ::= <signedNumber><suffix>
(注意 <suffix> 可能为空, 例如 <decimalSI> 的 "" 情形。) </br>
<digit> ::= 0 | 1 | ... | 9 </br>
<digits> ::= <digit> | <digit><digits> </br>
<number> ::= <digits> | <digits>.<digits> | <digits>. | .<digits> </br>
<sign> ::= "+" | "-" </br>
<signedNumber> ::= <number> | <sign><number> </br>
<suffix> ::= <binarySI> | <decimalExponent> | <decimalSI> </br>
<binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
(国际单位制度;查阅:http://physics.nist.gov/cuu/Units/binary.html) </br>
<decimalSI> ::= m | "" | k | M | G | T | P | E
(注意,1024 = 1ki 但 1000 = 1k;我没有选择大写。) </br>
<decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber> </br>
```
<!--
No matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities.
When a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized.
-->
无论使用三种指数形式中哪一种,没有数量可以表示大于 2<sup>63</sup>-1 的数,也不可能超过 3 个小数位。
更大或更精确的数字将被截断或向上取整。(例如:0.1m 将向上取整为 1m。)
如果将来我们需要更大或更小的数量,可能会扩展。
当从字符串解析数量时,它将记住它具有的后缀类型,并且在序列化时将再次使用相同类型。
<!--
Before serializing, Quantity will be put in "canonical form".
This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that:
a. No precision is lost
b. No fractional digits will be emitted
c. The exponent (or suffix) is as large as possible.
The sign will be omitted unless the number is negative.
-->
在序列化之前,数量将以“规范形式”放置。这意味着指数或者后缀将被向上或向下调整(尾数相应增加或减少),并确保:
1. 没有精度丢失
2. 不会输出小数数字
3. 指数(或后缀)尽可能大。
除非数量是负数,否则将省略正负号。
<!--
Examples:
1.5 will be serialized as "1500m"
1.5Gi will be serialized as "1536Mi"
-->
例如:
- 1.5 将会被序列化成 “1500m”
- 1.5Gi 将会被序列化成 “1536Mi”
<!--
Note that the quantity will NEVER be internally represented by a floating point number.
That is the whole point of this exercise.
Non-canonical values will still parse as long as they are well formed,
but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.)
This format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.
-->
请注意,数量永远**不会**在内部以浮点数表示。这是本设计的重中之重。
只要它们格式正确,非规范值仍将解析,但将以其规范形式重新输出。(所以应该总是使用规范形式,否则不要执行 diff 比较。)
这种格式旨在使得很难在不撰写某种特殊处理代码的情况下使用这些数字,进而希望实现者也使用定点实现。
<hr>
@@ -0,0 +1,62 @@
---
api_metadata:
apiVersion: ""
import: "k8s.io/api/core/v1"
kind: "ResourceFieldSelector"
content_type: "api_reference"
description: "ResourceFieldSelector 表示容器资源(CPU,内存)及其输出格式。"
title: "ResourceFieldSelector"
weight: 11
auto_generated: true
---
<!--
api_metadata:
apiVersion: ""
import: "k8s.io/api/core/v1"
kind: "ResourceFieldSelector"
content_type: "api_reference"
description: "ResourceFieldSelector represents container resources (cpu, memory) and their output format."
title: "ResourceFieldSelector"
weight: 11
auto_generated: true
-->
<!--
The file is auto-generated from the Go source code of the component using a generic
[generator](https://github.com/kubernetes-sigs/reference-docs/). To learn how
to generate the reference documentation, please read
[Contributing to the reference documentation](/docs/contribute/generate-ref-docs/).
To update the reference content, please follow the
[Contributing upstream](/docs/contribute/generate-ref-docs/contribute-upstream/)
guide. You can file document formatting bugs against the
[reference-docs](https://github.com/kubernetes-sigs/reference-docs/) project.
-->
`import "k8s.io/api/core/v1"`
<!-- ResourceFieldSelector represents container resources (cpu, memory) and their output format -->
ResourceFieldSelector 表示容器资源(CPU,内存)及其输出格式。
<hr>
- **resource** (string), 必选
<!-- Required: resource to select -->
必选:选择的资源
- **containerName** (string)
<!-- Container name: required for volumes, optional for env vars -->
容器名称:对卷必选,对环境变量可选
- **divisor** (<a href="{{< ref "../common-definitions/quantity#Quantity" >}}">Quantity</a>)
<!-- Specifies the output format of the exposed resources, defaults to "1" -->
指定所曝光资源的输出格式,默认值为“1”
@@ -28,8 +28,10 @@ This page describes the CoreDNS upgrade process and how to install CoreDNS inste
<!--
## About CoreDNS
[CoreDNS](https://coredns.io) is a flexible, extensible DNS server that can serve as the Kubernetes cluster DNS.
Like Kubernetes, the CoreDNS project is hosted by the {{< glossary_tooltip text="CNCF" term_id="cncf" >}}.
[CoreDNS](https://coredns.io) is a flexible, extensible DNS server
that can serve as the Kubernetes cluster DNS.
Like Kubernetes, the CoreDNS project is hosted by the
{{< glossary_tooltip text="CNCF" term_id="cncf" >}}.
-->
## 关于 CoreDNS
@@ -37,11 +39,12 @@ Like Kubernetes, the CoreDNS project is hosted by the {{< glossary_tooltip text=
与 Kubernetes 一样,CoreDNS 项目由 {{< glossary_tooltip text="CNCF" term_id="cncf" >}} 托管。
<!--
You can use CoreDNS instead of kube-dns in your cluster by replacing kube-dns in an existing
deployment, or by using tools like kubeadm that will deploy and upgrade the cluster for you.
You can use CoreDNS instead of kube-dns in your cluster by replacing
kube-dns in an existing deployment, or by using tools like kubeadm
that will deploy and upgrade the cluster for you.
-->
通过现有集群中替换 kube-dns可以在集群中使用 CoreDNS 代替 kube-dns 部署
或者使用 kubeadm 等工具来为你部署和升级集群。
通过替换现有集群部署中的 kube-dns或者使用 kubeadm 等工具来为你部署和升级集群
可以在你的集群中使用 CoreDNS 而非 kube-dns
<!--
## Installing CoreDNS
@@ -52,105 +55,93 @@ For manual deployment or replacement of kube-dns, see the documentation at the
## 安装 CoreDNS
有关手动部署或替换 kube-dns,请参阅
[CoreDNS GitHub 工程](https://github.com/coredns/deployment/tree/master/kubernetes)。
[CoreDNS GitHub 项目](https://github.com/coredns/deployment/tree/master/kubernetes)。
<!--
## Migrating to CoreDNS
### Upgrading an existing cluster with kubeadm
-->
## 迁移到 CoreDNS
### 使用 kubeadm 升级现有集群
<!--
In Kubernetes version 1.10 and later, you can also move to CoreDNS when you use `kubeadm` to upgrade
a cluster that is using `kube-dns`. In this case, `kubeadm` will generate the CoreDNS configuration
("Corefile") based upon the `kube-dns` ConfigMap, preserving configurations for
In Kubernetes version 1.21, kubeadm removed its support for `kube-dns` as a DNS application.
For `kubeadm` v{{< skew currentVersion >}}, the only supported cluster DNS application
is CoreDNS.
-->
在 Kubernetes 1.21 版本中,kubeadm 移除了对将 `kube-dns` 作为 DNS 应用的支持。
对于 `kubeadm` v{{< skew currentVersion >}},所支持的唯一的集群 DNS 应用是 CoreDNS。
<!--
You can move to CoreDNS when you use `kubeadm` to upgrade a cluster that is
using `kube-dns`. In this case, `kubeadm` generates the CoreDNS configuration
("Corefile") based upon the `kube-dns` ConfigMap, preserving configurations for
stub domains, and upstream name server.
-->
在 Kubernetes 1.10 及更高版本中,当你使用 `kubeadm` 升级使用 `kube-dns` 的集群时,你还可以迁移到 CoreDNS。
本例中 `kubeadm` 将生成 CoreDNS 配置("Corefile"基于 `kube-dns` ConfigMap
当你使用 `kubeadm` 升级使用 `kube-dns` 的集群时,你还可以执行到 CoreDNS 的迁移
这种场景中,`kubeadm`基于 `kube-dns` ConfigMap 生成 CoreDNS 配置("Corefile"),
保存存根域和上游名称服务器的配置。
<!--
If you are moving from kube-dns to CoreDNS, make sure to set the `CoreDNS` feature gate to `true`
during an upgrade. For example, here is what a `v1.11.0` upgrade would look like:
-->
如果你正在从 kube-dns 迁移到 CoreDNS,请确保在升级期间将 `CoreDNS` 特性门设置为 `true`
例如,`v1.11.0` 升级应该是这样的:
```
kubeadm upgrade apply v1.11.0 --feature-gates=CoreDNS=true
```
<!--
In Kubernetes version 1.13 and later the `CoreDNS` feature gate is removed and CoreDNS
is used by default.
-->
在 Kubernetes 版本 1.13 和更高版本中,`CoreDNS`特性门已经删除,CoreDNS 在默认情况下使用。
<!--
In versions prior to 1.11 the Corefile will be **overwritten** by the one created during upgrade.
**You should save your existing ConfigMap if you have customized it.** You may re-apply your
customizations after the new ConfigMap is up and running.
-->
在 1.11 之前的版本中,核心文件将被升级过程中创建的文件覆盖。
**如果已对其进行自定义,则应保存现有的 ConfigMap。**
在新的 ConfigMap 启动并运行后,你可以重新应用自定义。
<!--
If you are running CoreDNS in Kubernetes version 1.11 and later, during upgrade,
your existing Corefile will be retained.
-->
如果你在 Kubernetes 1.11 及更高版本中运行 CoreDNS,则在升级期间,将保留现有的 Corefile。
<!--
In Kubernetes version 1.21, support for `kube-dns` is removed from kubeadm.
-->
在 kubernetes 1.21 中,kubeadm 移除了对 `kube-dns` 的支持。
<!--
## Upgrading CoreDNS
CoreDNS is available in Kubernetes since v1.9.
You can check the version of CoreDNS shipped with Kubernetes and the changes made to CoreDNS [here](https://github.com/coredns/deployment/blob/master/kubernetes/CoreDNS-k8s_version.md).
You can check the version of CoreDNS that kubeadm installs for each version of
Kubernetes in the page
[CoreDNS version in Kubernetes](https://github.com/coredns/deployment/blob/master/kubernetes/CoreDNS-k8s_version.md).
-->
## 升级 CoreDNS
从 v1.9 起,Kubernetes 提供了 CoreDNS。
你可以在[此处](https://github.com/coredns/deployment/blob/master/kubernetes/CoreDNS-k8s_version.md)
查看 Kubernetes 随附的 CoreDNS 版本以及对 CoreDNS 所做的更改。
你可以在 [CoreDNS version in Kubernetes](https://github.com/coredns/deployment/blob/master/kubernetes/CoreDNS-k8s_version.md)
页面查看 kubeadm 为不同版本 Kubernetes 所安装的 CoreDNS 版本。
<!--
CoreDNS can be upgraded manually in case you want to only upgrade CoreDNS or use your own custom image.
There is a helpful [guideline and walkthrough](https://github.com/coredns/deployment/blob/master/kubernetes/Upgrading_CoreDNS.md) available to ensure a smooth upgrade.
CoreDNS can be upgraded manually in case you want to only upgrade CoreDNS
or use your own custom image.
There is a helpful [guideline and walkthrough](https://github.com/coredns/deployment/blob/master/kubernetes/Upgrading_CoreDNS.md)
available to ensure a smooth upgrade.
Make sure the existing CoreDNS configuration ("Corefile") is retained when
upgrading your cluster.
-->
如果你只想升级 CoreDNS 或使用自己的自定义镜像,可以手动升级 CoreDNS。
如果你只想升级 CoreDNS 或使用自己的定制镜像,可以手动升级 CoreDNS。
参看[指南和演练](https://github.com/coredns/deployment/blob/master/kubernetes/Upgrading_CoreDNS.md)
文档了解如何平滑升级。
在升级你的集群过程中,请确保现有 CoreDNS 的配置("Corefile")被保留下来。
<!--
If you are upgrading your cluster using the `kubeadm` tool, `kubeadm`
can take care of retaining the existing CoreDNS configuration automatically.
-->
如果使用 `kubeadm` 工具来升级集群,则 `kubeadm` 可以自动处理保留现有 CoreDNS
配置这一事项。
<!--
## Tuning CoreDNS
When resource utilisation is a concern, it may be useful to tune the configuration of CoreDNS. For more details, check out the
When resource utilisation is a concern, it may be useful to tune
the configuration of CoreDNS. For more details, check out the
[documentation on scaling CoreDNS]((https://github.com/coredns/deployment/blob/master/kubernetes/Scaling_CoreDNS.md)).
-->
## CoreDNS 调优
当资源利用方面有问题时,优化 CoreDNS 的配置可能是有用的。
有关详细信息,请参阅[有关扩缩 CoreDNS 的文档](https://github.com/coredns/deployment/blob/master/kubernetes/Scaling_CoreDNS.md)。
有关详细信息,请参阅有关[扩缩 CoreDNS 的文档](https://github.com/coredns/deployment/blob/master/kubernetes/Scaling_CoreDNS.md)。
## {{% heading "whatsnext" %}}
<!--
You can configure [CoreDNS](https://coredns.io) to support many more use cases than
kube-dns by modifying the `Corefile`. For more information, see the
[CoreDNS site](https://coredns.io/2017/05/08/custom-dns-entries-for-kubernetes/).
kube-dns does by modifying the CoreDNS configuration ("Corefile").
For more information, see the [documentation](https://coredns.io/plugins/kubernetes/)
for the `kubernetes` CoreDNS plugin, or read the
[Custom DNS Entries for Kubernetes](https://coredns.io/2017/05/08/custom-dns-entries-for-kubernetes/)
in the CoreDNS blog.
-->
你可以通过修改 `Corefile` 来配置 [CoreDNS](https://coredns.io)以支持比 kube-dns 更多的用例。
请参考 [CoreDNS 网站](https://coredns.io/2017/05/08/custom-dns-entries-for-kubernetes/)
你可以通过修改 CoreDNS 的配置("Corefile"来配置 [CoreDNS](https://coredns.io)
以支持比 kube-dns 更多的用例。
请参考 `kubernetes` CoreDNS 插件的[文档](https://coredns.io/plugins/kubernetes/)
或者 CoreDNS 博客上的博文
[Custom DNS Entries for Kubernetes](https://coredns.io/2017/05/08/custom-dns-entries-for-kubernetes/)
以了解更多信息。
@@ -1,4 +1,8 @@
---
title: 安装网络规则驱动
title: 安装网络策略驱动
weight: 30
---
<!--
title: Install a Network Policy Provider
weight: 30
-->
@@ -149,10 +149,10 @@ and a memory limit of 200 MiB.
```yaml
...
resources:
limits:
memory: 200Mi
requests:
memory: 100Mi
limits:
memory: 200Mi
...
```
@@ -263,7 +263,7 @@ The output shows that the Container was killed because it is out of memory (OOM)
```shell
lastState:
terminated:
containerID: docker://65183c1877aaec2e8427bc95609cc52677a454b56fcb24340dbd22917c23b10f
containerID: 65183c1877aaec2e8427bc95609cc52677a454b56fcb24340dbd22917c23b10f
exitCode: 137
finishedAt: 2017-06-20T20:52:19Z
reason: OOMKilled
@@ -17,8 +17,16 @@ card:
<!-- overview -->
<!--
Many applications rely on configuration which is used during either application initialization or runtime.
Most of the times there is a requirement to adjust values assigned to configuration parameters.
ConfigMaps is the kubernetes way to inject application pods with configuration data.
ConfigMaps allow you to decouple configuration artifacts from image content to keep containerized applications portable. This page provides a series of usage examples demonstrating how to create ConfigMaps and configure Pods using data stored in ConfigMaps.
-->
很多应用在其初始化或运行期间要依赖一些配置信息。大多数时候,
存在要调整配置参数所设置的数值的需求。
ConfigMap 是 Kubernetes 用来向应用 Pod 中注入配置数据的方法。
ConfigMap 允许你将配置文件与镜像文件分离,以使容器化的应用程序具有可移植性。
本页提供了一系列使用示例,这些示例演示了如何创建 ConfigMap 以及配置 Pod
使用存储在 ConfigMap 中的数据。
@@ -35,8 +43,8 @@ You can use either `kubectl create configmap` or a ConfigMap generator in `kusto
-->
## 创建 ConfigMap
你可以使用 `kubectl create configmap` 或者在 `kustomization.yaml` 中的 ConfigMap 生成器
来创建 ConfigMap。注意,`kubectl` 从 1.14 版本开始支持 `kustomization.yaml`
你可以使用 `kubectl create configmap` 或者在 `kustomization.yaml` 中的 ConfigMap
生成器来创建 ConfigMap。注意,`kubectl` 从 1.14 版本开始支持 `kustomization.yaml`
<!--
### Create a ConfigMap Using kubectl create configmap
@@ -45,12 +53,13 @@ Use the `kubectl create configmap` command to create configmaps from [directorie
-->
### 使用 kubectl create configmap 创建 ConfigMap
你可以使用 `kubectl create configmap` 命令基于
[目录](#create-configmaps-from-directories)、[文件](#create-configmaps-from-files)
或者[字面值](#create-configmaps-from-literal-values)来创建 ConfigMap
你可以使用 `kubectl create configmap`
命令基于[目录](#create-configmaps-from-directories)、
[文件](#create-configmaps-from-files)或者[字面值](#create-configmaps-from-literal-values)来创建
ConfigMap
```shell
kubectl create configmap <map-name> <data-source>
kubectl create configmap <映射名称> <数据源>
```
<!--
@@ -58,7 +67,7 @@ where \<map-name> is the name you want to assign to the ConfigMap and \<data-sou
The name of a ConfigMap object must be a valid
[DNS subdomain name](/docs/concepts/overview/working-with-objects/names#dns-subdomain-names).
-->
其中,\<map-name\> 是要设置的 ConfigMap 名称,\<data-source\> 是要从中提取数据的目录、
其中,`<映射名称>` 是为 ConfigMap 指定的名称,`<数据源>` 是要从中提取数据的目录、
文件或者字面值。
ConfigMap 对象的名称必须是合法的
[DNS 子域名](/zh/docs/concepts/overview/working-with-objects/names#dns-subdomain-names).
@@ -66,8 +75,8 @@ ConfigMap 对象的名称必须是合法的
<!--
When you are creating a ConfigMap based on a file, the key in the \<data-source> defaults to the basename of the file, and the value defaults to the file content.
-->
在你基于文件来创建 ConfigMap 时,\<data-source\> 中的键名默认取自
文件的基本名,而对应的值则默认为文件的内容。
在你基于文件来创建 ConfigMap 时,`<数据源>` 中的键名默认取自文件的基本名,
而对应的值则默认为文件的内容。
<!--
You can use [`kubectl describe`](/docs/reference/generated/kubectl/kubectl-commands/#describe) or
@@ -90,10 +99,11 @@ are ignored (e.g. subdirectories, symlinks, devices, pipes, etc).
For example:
-->
#### 基于目录创建 ConfigMap {#create-configmaps-from-directories}
你可以使用 `kubectl create configmap` 基于同一目录中的多个文件创建 ConfigMap。
当你基于目录来创建 ConfigMap 时,kubectl 识别目录下基本名可以作为合法键名的
文件,并将这些文件打包到新的 ConfigMap 中。普通文件之外的所有目录项都会被
忽略(例如子目录、符号链接、设备、管道等等)。
当你基于目录来创建 ConfigMap 时,kubectl 识别目录下基本名可以作为合法键名的文件,
并将这些文件打包到新的 ConfigMap 中。普通文件之外的所有目录项都会被忽略
(例如子目录、符号链接、设备、管道等等)。
例如:
@@ -256,7 +266,7 @@ kubectl create configmap game-config-2 --from-file=configure-pod-container/confi
<!--
Describe the above `game-config-2` configmap created
-->
描述上面创建的 `game-config-2` configmap
描述上面创建的 `game-config-2` ConfigMap
```shell
kubectl describe configmaps game-config-2
@@ -324,22 +334,20 @@ enemies=aliens
lives=3
allowed="true"
-->
Env 文件包含环境变量列表。
其中适用以下语法规则:
Env 文件包含环境变量列表。其中适用以下语法规则:
- Env 文件中的每一行必须为 VAR=VAL 格式。
- 以#开头的行(即注释)将被忽略。
- 空行将被忽略。
- 引号不会被特殊处理(即它们将成为 ConfigMap 值的一部分)。
将示例文件下载到 `configure-pod-container/configmap/` 目录
将示例文件下载到 `configure-pod-container/configmap/` 目录
```shell
wget https://kubernetes.io/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties
```
env 文件 `game-env-file.properties` 如下所示:
Env 文件 `game-env-file.properties` 如下所示:
```shell
cat configure-pod-container/configmap/game-env-file.properties
@@ -410,10 +418,10 @@ kubectl create configmap config-multi-env-files \
```
-->
```shell
# 将样本文件下载到 `configure-pod-container/configmap/` 目录
# 将示例文件下载到 `configure-pod-container/configmap/` 目录
wget https://k8s.io/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties
# 创建 configmap
# 创建 ConfigMap
kubectl create configmap config-multi-env-files \
--from-env-file=configure-pod-container/configmap/game-env-file.properties \
--from-env-file=configure-pod-container/configmap/ui-env-file.properties
@@ -432,6 +440,7 @@ kubectl get configmap config-multi-env-files -o yaml
where the output is similar to this:
-->
输出类似以下内容:
```yaml
apiVersion: v1
kind: ConfigMap
@@ -459,13 +468,13 @@ You can define a key other than the file name to use in the `data` section of yo
而不是按默认行为使用文件名:
```shell
kubectl create configmap game-config-3 --from-file=<my-key-name>=<path-to-file>
kubectl create configmap game-config-3 --from-file=<我的键名>=<文件路径>
```
<!--
where <my-key-name> is the key you want to use in the ConfigMap and `<path-to-file>` is the location of the data source file you want the key to represent.
-->
`<my-key-name>` 是你要在 ConfigMap 中使用的键名,`<path-to-file>` 是你想要键表示数据源文件的位置。
`<我的键名>` 是你要在 ConfigMap 中使用的键名,`<文件路径>` 是你想要键表示数据源文件的位置。
<!-- For example: -->
例如:
@@ -479,7 +488,7 @@ would produce the following ConfigMap:
-->
将产生以下 ConfigMap:
```
```shell
kubectl get configmaps game-config-3 -o yaml
```
@@ -513,7 +522,9 @@ data:
You can use `kubectl create configmap` with the `--from-literal` argument to define a literal value from the command line:
-->
#### 根据字面值创建 ConfigMap {#create-configmaps-from-literal-values}
你可以将 `kubectl create configmap``--from-literal` 参数一起使用,从命令行定义文字值:
你可以将 `kubectl create configmap``--from-literal` 参数一起使用,
通过命令行定义文字值:
```shell
kubectl create configmap special-config --from-literal=special.how=very --from-literal=special.type=charm
@@ -551,7 +562,6 @@ data:
<!--
### Create a ConfigMap from generator
`kubectl` supports `kustomization.yaml` since 1.14.
You can also create a ConfigMap from generators and then apply it to create the object on
the Apiserver. The generators
@@ -560,7 +570,7 @@ should be specified in a `kustomization.yaml` inside a directory.
### 基于生成器创建 ConfigMap
自 1.14 开始,`kubectl` 开始支持 `kustomization.yaml`
你还可以基于生成器创建 ConfigMap,然后将其应用于 API 服务器上创建对象。
你还可以基于生成器Generators创建 ConfigMap,然后将其应用于 API 服务器上创建对象。
生成器应在目录内的 `kustomization.yaml` 中指定。
<!--
@@ -570,7 +580,8 @@ For example, to generate a ConfigMap from files `configure-pod-container/configm
-->
#### 基于文件生成 ConfigMap
例如,要 `configure-pod-container/configmap/kubectl/game.properties` 文件生成一个 ConfigMap
例如,要基于 `configure-pod-container/configmap/kubectl/game.properties`
文件生成一个 ConfigMap
```shell
# 创建包含 ConfigMapGenerator 的 kustomization.yaml 文件
@@ -585,11 +596,12 @@ EOF
<!--
Apply the kustomization directory to create the ConfigMap object.
-->
使用 kustomization 目录创建 ConfigMap 对象:
应用(Applykustomization 目录创建 ConfigMap 对象:
```shell
kubectl apply -k .
```
```
configmap/game-config-4-m9dm2f92bt created
```
@@ -597,7 +609,7 @@ configmap/game-config-4-m9dm2f92bt created
<!--
You can check that the ConfigMap was created like this:
-->
你可以检查 ConfigMap 是这样创建的:
你可以检查 ConfigMap 被创建如下:
```shell
kubectl get configmap
@@ -645,7 +657,7 @@ with the key `game-special-key`
-->
#### 定义从文件生成 ConfigMap 时要使用的键
在 ConfigMap 生成器,你可以定义一个非文件名的键名。
在 ConfigMap 生成器,你可以定义一个非文件名的键名。
例如,从 `configure-pod-container/configmap/game.properties` 文件生成 ConfigMap
但使用 `game-special-key` 作为键名:
@@ -662,11 +674,12 @@ EOF
<!--
Apply the kustomization directory to create the ConfigMap object.
-->
使用 Kustomization 目录创建 ConfigMap 对象。
用 Kustomization 目录创建 ConfigMap 对象。
```shell
kubectl apply -k .
```
```
configmap/game-config-5-m67dt67794 created
```
@@ -677,7 +690,7 @@ configmap/game-config-5-m67dt67794 created
To generate a ConfigMap from literals `special.type=charm` and `special.how=very`,
you can specify the ConfigMap generator in `kusotmization.yaml` as
-->
#### 字面值生成 ConfigMap
#### 基于字面值生成 ConfigMap
要基于字符串 `special.type=charm``special.how=very` 生成 ConfigMap
可以在 `kusotmization.yaml` 中配置 ConfigMap 生成器:
@@ -701,6 +714,7 @@ Apply the kustomization directory to create the ConfigMap object.
```shell
kubectl apply -k .
```
```
configmap/special-config-2-c92b5mmcf2 created
```
@@ -726,7 +740,7 @@ configmap/special-config-2-c92b5mmcf2 created
<!--
2. Assign the `special.how` value defined in the ConfigMap to the `SPECIAL_LEVEL_KEY` environment variable in the Pod specification.
-->
2. 将 ConfigMap 中定义的 `special.how`分配给 Pod 规中的 `SPECIAL_LEVEL_KEY` 环境变量。
2. 将 ConfigMap 中定义的 `special.how` 值给 Pod 规中的 `SPECIAL_LEVEL_KEY` 环境变量。
{{< codenew file="pods/pod-single-configmap-env-variable.yaml" >}}
@@ -760,7 +774,7 @@ configmap/special-config-2-c92b5mmcf2 created
<!--
* Define the environment variables in the Pod specification.
-->
* 在 Pod 规中定义环境变量。
* 在 Pod 规中定义环境变量。
{{< codenew file="pods/pod-multiple-configmap-env-variable.yaml" >}}
@@ -803,7 +817,8 @@ Kubernetes v1.6 和更高版本支持此功能。
<!--
* Use `envFrom` to define all of the ConfigMap's data as container environment variables. The key from the ConfigMap becomes the environment variable name in the Pod.
-->
* 使用 `envFrom` 将所有 ConfigMap 的数据定义为容器环境变量,ConfigMap 中的键成为 Pod 中的环境变量名称。
* 使用 `envFrom` 将所有 ConfigMap 的数据定义为容器环境变量,ConfigMap
中的键成为 Pod 中的环境变量名称。
{{< codenew file="pods/pod-configmap-envFrom.yaml" >}}
@@ -825,12 +840,13 @@ Kubernetes v1.6 和更高版本支持此功能。
<!--
You can use ConfigMap-defined environment variables in the `command` and `args` of a container using the `$(VAR_NAME)` Kubernetes substitution syntax.
-->
你可以使用 `$(VAR_NAME)` Kubernetes 替换语法在容器的 `command``args` 部分中使用 ConfigMap 定义的环境变量。
你可以使用 `$(VAR_NAME)` Kubernetes 替换语法在容器的 `command``args`
属性中使用 ConfigMap 定义的环境变量。
<!--
For example, the following Pod specification
-->
例如,以下 Pod 规
例如,以下 Pod 规
{{< codenew file="pods/pod-configmap-env-var-valueFrom.yaml" >}}
@@ -866,7 +882,7 @@ As explained in [Create ConfigMaps from files](#create-configmaps-from-files), w
<!--
The examples in this section refer to a ConfigMap named special-config, shown below.
-->
本节中的示例引用了一个名为 special-config 的 ConfigMap,如下所示:
本节中的示例引用了一个名为 'special-config' 的 ConfigMap,如下所示:
{{< codenew file="configmap/configmap-multikeys.yaml" >}}
@@ -886,10 +902,11 @@ Add the ConfigMap name under the `volumes` section of the Pod specification.
This adds the ConfigMap data to the directory specified as `volumeMounts.mountPath` (in this case, `/etc/config`).
The `command` section references the `special.level` item stored in the ConfigMap.
-->
### 使用存储在 ConfigMap 中的数据填充数据
### 使用存储在 ConfigMap 中的数据填充卷
在 Pod 规约的 `volumes` 部分下添加 ConfigMap 名称。
这会将 ConfigMap 数据添加到指定为 `volumeMounts.mountPath` 的目录(在本例中为 `/etc/config`)。
这会将 ConfigMap 数据添加到 `volumeMounts.mountPath` 所指定的目录
(在本例中为 `/etc/config`)。
`command` 部分引用存储在 ConfigMap 中的 `special.level`
{{< codenew file="pods/pod-configmap-volume.yaml" >}}
@@ -914,14 +931,14 @@ SPECIAL_TYPE
If there are some files in the `/etc/config/` directory, they will be deleted.
-->
{{< caution >}}
如果在 `/etc/config/` 目录中有一些文件,它们将被删除。
如果在 `/etc/config/` 目录中有一些文件,这些文件将被删除。
{{< /caution >}}
<!--
Text data is exposed as files using the UTF-8 character encoding. To use some other character encoding, use binaryData.
-->
{{< note >}}
文本数据会使用 UTF-8 字符编码的形式展现为文件。如果使用其他字符编码,
文本数据会展现为 UTF-8 字符编码的文件。如果使用其他字符编码,
可以使用 `binaryData`
{{< /note >}}
@@ -931,10 +948,11 @@ Text data is exposed as files using the UTF-8 character encoding. To use some ot
Use the `path` field to specify the desired file path for specific ConfigMap items.
In this case, the `SPECIAL_LEVEL` item will be mounted in the `config-volume` volume at `/etc/config/keys`.
-->
### 将 ConfigMap 数据添加到数据卷中的特定路径
### 将 ConfigMap 数据添加到卷中的特定路径
使用 `path` 字段为特定的 ConfigMap 项目指定预期的文件路径。
在这里,ConfigMap中,键值 `SPECIAL_LEVEL` 的内容将挂载在 `config-volume` 数据卷中 `/etc/config/keys` 文件下。
在这里,ConfigMap 中键 `SPECIAL_LEVEL` 的内容将挂载在 `config-volume`
卷中 `/etc/config/keys` 文件中。
{{< codenew file="pods/pod-configmap-volume-specific-key.yaml" >}}
@@ -950,11 +968,12 @@ kubectl create -f https://kubernetes.io/examples/pods/pod-configmap-volume-speci
<!--
When the pod runs, the command `cat /etc/config/keys` produces the output below:
-->
pod 运行时,命令 `cat /etc/config/keys` 产生以下输出:
Pod 运行时,命令 `cat /etc/config/keys` 产生以下输出:
```
very
```
<!--
Like before, all previous files in the `/etc/config/` directory will be deleted.
-->
@@ -968,33 +987,49 @@ Like before, all previous files in the `/etc/config/` directory will be deleted.
You can project keys to specific paths and specific permissions on a per-file
basis. The [Secrets](/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod) user guide explains the syntax.
-->
### 映射键指定路径和文件权限
### 映射键指定路径并设置文件访问权限
你可以通过指定键名到特定目录的投射关系,也可以逐个文件地设定访问权限。
你可以指定键名投射到特定目录,也可以逐个文件地设定访问权限。
[Secret 用户指南](/zh/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod)
这一语法提供了解释。
这一语法提供了解释。
<!--
### Optional References
A ConfigMap reference may be marked "optional". If the ConfigMap is non-existent, the mounted volume will be empty. If the ConfigMap exists, but the referenced
key is non-existent the path will be absent beneath the mount point.
-->
### 可选的引用 {#optional-references}
ConfigMap 引用可以被标记为 “optional(可选的)”。如果所引用的 ConfigMap 不存在,
则所挂载的卷将会是空的。如果所引用的 ConfigMap 确实存在,但是所引用的主键不存在,
则在挂载点下对应的路径也会不存在。
<!--
### Mounted ConfigMaps are updated automatically
-->
### 挂载的 ConfigMap 将自动更新
### 挂载的 ConfigMap 将自动更新 {#mounted-configmaps-are-updated-automatically}
<!--
When a ConfigMap already being consumed in a volume is updated, projected keys
are eventually updated as well. Kubelet is checking whether the mounted
ConfigMap is fresh on every periodic sync. However, it is using its local
ttl-based cache for getting the current value of the ConfigMap. As a result,
the total delay from the moment when the ConfigMap is updated to the moment
when new keys are projected to the pod can be as long as kubelet sync period
(1 minute by default) + ttl of ConfigMaps cache (1 minute by default) in
kubelet. You can trigger an immediate refresh by updating one of the pod's
annotations.
When a mounted ConfigMap is updated, the projected content is eventually updated too. This applies in the case where an optionally referenced ConfigMap comes into
existence after a pod has started.
-->
更新已经在数据卷中使用的 ConfigMap 时,已映射的键最终也会被更新。
`kubelet` 在每次定期同步时都会检查已挂载的 ConfigMap 是否是最新的。
当某个已被挂载的 ConfigMap 被更新,所投射的内容最终也会被更新。
对于 Pod 已经启动之后所引用的、可选的 ConfigMap 才出现的情形,
这一动态更新现象也是适用的。
<!--
Kubelet checks whether the mounted ConfigMap is fresh on every periodic sync. However, it uses its local TTL-based cache for getting the current value of the
ConfigMap. As a result, the total delay from the moment when the ConfigMap is updated to the moment when new keys are projected to the pod can be as long as
kubelet sync period (1 minute by default) + TTL of ConfigMaps cache (1 minute by default) in kubelet. You can trigger an immediate refresh by updating one of
the pod's annotations.
-->
`kubelet` 在每次周期性同步时都会检查已挂载的 ConfigMap 是否是最新的。
但是,它使用其本地的基于 TTL 的缓存来获取 ConfigMap 的当前值。
因此,从更新 ConfigMap 到将新键映射到 Pod 的总延迟可能与
kubelet 同步周期 + ConfigMap 在 kubelet 中缓存的 TTL 一样长。
kubelet 同步周期(默认 1 分钟) + ConfigMap 在 kubelet 中缓存的 TTL
(默认 1 分钟)一样长。
你可以通过更新 Pod 的某个注解来触发立即更新。
<!--
A container using a ConfigMap as a [subPath](/docs/concepts/storage/volumes/#using-subpath) volume will not receive ConfigMap updates.
@@ -1014,9 +1049,9 @@ The ConfigMap API resource stores configuration data as key-value pairs. The dat
## 了解 ConfigMap 和 Pod
ConfigMap API 资源将配置数据存储为键值对。
数据可以在 Pod 中使用,也可以提供系统组件(如控制器)的配置。
数据可以在 Pod 中使用,也可以用来提供系统组件(如控制器)的配置。
ConfigMap 与 [Secret](/zh/docs/concepts/configuration/secret/) 类似,
但是提供了一种使用不包含敏感信息的字符串的方法。
但是提供的是一种处理不含敏感信息的字符串的方法。
用户和系统组件都可以在 ConfigMap 中存储配置数据。
<!--
@@ -1024,9 +1059,9 @@ ConfigMaps should reference properties files, not replace them. Think of the Con
-->
{{< note >}}
ConfigMap 应该引用属性文件,而不是替换它们。可以将 ConfigMap 理解为类似于 Linux
`/etc` 目录及其内容的东西。例如,如果你 ConfigMap 创建
`/etc` 目录及其内容的东西。例如,如果你基于 ConfigMap 创建
[Kubernetes 卷](/zh/docs/concepts/storage/volumes/),则 ConfigMap
中的每个数据项都由该数据卷中的单个文件表示。
中的每个数据项都由该数据卷中的某个独立的文件表示。
{{< /note >}}
<!--
@@ -1059,17 +1094,18 @@ data:
- You must create a ConfigMap before referencing it in a Pod specification (unless you mark the ConfigMap as "optional"). If you reference a ConfigMap that doesn't exist, the Pod won't start. Likewise, references to keys that don't exist in the ConfigMap will prevent the pod from starting.
-->
### 限制
### 限制 {#restrictions}
- 在 Pod 规中引用之前,必须先创建一个 ConfigMap(除非将 ConfigMap 标记为"可选")。
如果引用的 ConfigMap 不存在,则 Pod 将不会启动。同样,引用 ConfigMap 中不存在的键也会阻止 Pod 启动。
- 在 Pod 规中引用个 ConfigMap 之前,必须先创建它(除非将 ConfigMap 标记为
“optional(可选)”)。如果引用的 ConfigMap 不存在,则 Pod 将不会启动。
同样,引用 ConfigMap 中不存在的主键也会令 Pod 无法启动。
<!--
- If you use `envFrom` to define environment variables from ConfigMaps, keys that are considered invalid will be skipped. The pod will be allowed to start, but the invalid names will be recorded in the event log (`InvalidVariableNames`). The log message lists each skipped key. For example:
-->
- 如果你使用 `envFrom` 基于 ConfigMap 定义环境变量,那么无效的键将被忽略。
可以启动 Pod,但无效名称将记录在事件日志中(`InvalidVariableNames`)。
日志消息列出了每个跳过的键。例如:
- 如果你使用 `envFrom` 基于 ConfigMap 定义环境变量,那么无效的键将被忽略。
Pod 可以启动,但无效名称将记录在事件日志中(`InvalidVariableNames`)。
日志消息列出了每个跳过的键。例如:
```shell
kubectl get events
@@ -1086,13 +1122,13 @@ data:
<!--
- ConfigMaps reside in a specific {{< glossary_tooltip term_id="namespace" >}}. A ConfigMap can only be referenced by pods residing in the same namespace.
-->
- ConfigMap 位于定的{{< glossary_tooltip term_id="namespace" text="名字空间" >}}
中。每个 ConfigMap 只能被同一名字空间中的 Pod 引用.
- ConfigMap 位于定的{{< glossary_tooltip term_id="namespace" text="名字空间" >}}中。
每个 ConfigMap 只能被同一名字空间中的 Pod 引用.
<!--
- You can't use ConfigMaps for {{< glossary_tooltip text="static pods" term_id="static-pod" >}}, because the Kubelet does not support this.
-->
- 你不能将 ConfigMap 用于 {{< glossary_tooltip text="静态 Pod" term_id="static-pod" >}}
- 你不能将 ConfigMap 用于{{< glossary_tooltip text="静态 Pod" term_id="static-pod" >}}
因为 Kubernetes 不支持这种用法。
## {{% heading "whatsnext" %}}
@@ -1101,5 +1137,5 @@ data:
* Follow a real world example of [Configuring Redis using a ConfigMap](/docs/tutorials/configuration/configure-redis-using-configmap/).
-->
* 浏览[使用 ConfigMap 配置 Redis](/zh/docs/tutorials/configuration/configure-redis-using-configmap/)
真实实例
真实实例
@@ -68,7 +68,7 @@ plugins:
# 要豁免的已认证用户名列表
usernames: []
# 要豁免的运行时类名称列表
runtimeClassNames: []
runtimeClasses: []
# 要豁免的名字空间列表
namespaces: []
```
@@ -60,7 +60,7 @@ accomplish commonly used tasks, and [Tutorials](/docs/tutorials/) are more
comprehensive walkthroughs of real-world, industry-specific, or end-to-end
development scenarios. The [Reference](/docs/reference/) section provides
detailed documentation on the [Kubernetes API](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/)
and command-line interfaces (CLIs), such as [`kubectl`](/docs/user-guide/kubectl-overview/).
and command-line interfaces (CLIs), such as [`kubectl`](/docs/reference/kubectl/).
-->
### 问题 {#questions}
@@ -71,7 +71,7 @@ and command-line interfaces (CLIs), such as [`kubectl`](/docs/user-guide/kubectl
[教程](/zh/docs/tutorials/)部分则提供对现实世界、特定行业或端到端开发场景的更全面的演练。
[参考](/zh/docs/reference/)部分提供了详细的
[Kubernetes API](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/) 文档
和命令行 (CLI) 接口的文档,例如[`kubectl`](/zh/docs/reference/kubectl/overview/)。
和命令行 (CLI) 接口的文档,例如[`kubectl`](/zh/docs/reference/kubectl/)。
<!--
## Help! My question isn't covered! I need help now!
@@ -84,14 +84,18 @@ and command-line interfaces (CLIs), such as [`kubectl`](/docs/user-guide/kubectl
Someone else from the community may have already asked a similar question or may
be able to help with your problem. The Kubernetes team will also monitor
[posts tagged Kubernetes](https://stackoverflow.com/questions/tagged/kubernetes).
If there aren't any existing questions that help, please
[ask a new one](https://stackoverflow.com/questions/ask?tags=kubernetes)!
If there aren't any existing questions that help, **please [ensure that your question is on-topic on Stack Overflow](https://stackoverflow.com/help/on-topic)
and that you read through the guidance on [how to ask a new question](https://stackoverflow.com/help/how-to-ask)**,
before [asking a new one](https://stackoverflow.com/questions/ask?tags=kubernetes)!
-->
### Stack Overflow {#stack-overflow}
社区中的其他人可能已经问过和你类似的问题,也可能能够帮助解决你的问题。
Kubernetes 团队还会监视[带有 Kubernetes 标签的帖子](https://stackoverflow.com/questions/tagged/kubernetes)。
如果现有的问题对你没有帮助,[问一个新问题](https://stackoverflow.com/questions/ask?tags=kubernetes)!
如果现有的问题对你没有帮助,[问一个新问题](https://stackoverflow.com/questions/ask?tags=kubernetes)
之前,**请[确保你的问题是关于 Stack Overflow 的主题](https://stackoverflow.com/help/on-topic)
并且你需要阅读关于[如何提出新问题](https://stackoverflow.com/help/how-to-ask)
的指南。**
<!--
### Slack

Some files were not shown because too many files have changed in this diff Show More