Soluciona problemas del servidor de la API de Kubernetes
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta página, se muestra cómo resolver problemas con el servidor de la API de Kubernetes (kube-apiserver) para Google Distributed Cloud.
Esta página está destinada a administradores de TI y operadores que administran el ciclo de vida de la infraestructura tecnológica subyacente, y responden a las alertas y las páginas cuando no se cumplen los objetivos de nivel de servicio (SLO) o fallan las aplicaciones. Para obtener más información sobre los roles comunes y las tareas de ejemplo a las que hacemos referencia en el contenido de Google Cloud, consulta Tareas y roles comunes de los usuarios de GKE.
Tiempos de espera de webhook y llamadas de webhook fallidas
Estos errores se pueden observar de varias maneras. Si experimentas alguno de los siguientes problemas, es posible que las llamadas a webhooks no se realicen correctamente:
Connection refused: Si kube-apiserver informa errores de tiempo de espera para llamar al webhook, se informa el siguiente error en los registros:
failed calling webhook "server.system.private.gdc.goog":
failed to call webhook: Post "https://root-admin-webhook.gpc-system.svc:443/mutate-system-private-gdc-goog-v1alpha1-server?timeout=10s":
dial tcp 10.202.1.18:443: connect: connection refused
Se superó el plazo del contexto: Es posible que también veas el siguiente error en los registros:
failed calling webhook "namespaces.hnc.x-k8s.io": failed to call webhook: Post
"https://hnc-webhook-service.hnc-system.svc:443/validate-v1-namespace?timeout=10s\":
context deadline exceeded"
Si crees que estás experimentando tiempos de espera de webhook o llamadas a webhook fallidas, usa uno de los siguientes métodos para confirmar el problema:
Verifica el registro del servidor de la API para ver si hay problemas de red.
Revisa el registro para ver si hay errores relacionados con la red, como TLS handshake error.
Verifica si la IP o el puerto coinciden con lo que el servidor de la API está configurado para responder.
Sigue estos pasos para supervisar la latencia del webhook:
Si el webhook requiere más tiempo para completarse, puedes configurar un valor de tiempo de espera personalizado.
La latencia de los webhooks se suma a la latencia de las solicitudes a la API, por lo que se debe evaluar lo más rápido posible.
Si el error del webhook bloquea la disponibilidad del clúster o si el webhook es inofensivo para quitar y mitiga la situación, verifica si es posible establecer temporalmente failurePolicy en Ignore o quitar el webhook infractor.
Falla o latencia de marcación del servidor de la API
Este error se puede observar de varias maneras:
Errores de resolución de nombres externos: Es posible que un cliente externo devuelva errores que contengan lookup en el mensaje, como los siguientes:
dial tcp: lookup kubernetes.example.com on 127.0.0.1:53: no such host
Este error no se aplica a un cliente que se ejecuta dentro del clúster. Se inserta la IP del servicio de Kubernetes, por lo que no se requiere resolución.
Errores de red: Es posible que el cliente imprima un error de red genérico cuando intente marcar el servidor de la API, como en los siguientes ejemplos:
dial tcp 10.96.0.1:443: connect: no route to host
dial tcp 10.96.0.1:443: connect: connection refused
dial tcp 10.96.0.1:443: connect: i/o timeout
Alta latencia al conectarse al servidor de la API: Es posible que la conexión al servidor de la API se realice correctamente, pero las solicitudes agoten el tiempo de espera en el cliente. En esta situación, el cliente suele imprimir mensajes de error que contienen context deadline
exceeded.
Si la conexión al servidor de la API falla por completo, intenta conectarte en el mismo entorno en el que el cliente informa el error.
Los contenedores efímeros de Kubernetes se pueden usar para insertar un contenedor de depuración en los espacios de nombres existentes de la siguiente manera:
Desde donde se ejecuta el cliente problemático, usa kubectl para realizar una solicitud con un alto nivel de detalle. Por ejemplo, una solicitud GET a /healthz no suele requerir autenticación:
kubectlget-v999--raw/healthz
Si la solicitud falla o kubectl no está disponible, puedes obtener la URL del resultado y realizar la solicitud de forma manual con curl. Por ejemplo, si el host del servicio que se obtuvo del resultado anterior era https://192.0.2.1:36917/, puedes enviar una solicitud similar de la siguiente manera:
# Replace "--ca-cert /path/to/ca.pem" to "--insecure" if you are accessing# a local cluster and you trust the connection cannot be tampered.# The output is always "ok" and thus contains no sensentive information.
curl-v--cacert/path/to/ca.pemhttps://192.0.2.1:36917/healthz
El resultado de este comando suele indicar la causa raíz de una conexión fallida.
Si la conexión se realiza correctamente, pero es lenta o se agota el tiempo de espera, indica que el servidor de la API está sobrecargado. Para confirmar, en la consola, consulta las métricas de latencia de las solicitudes y de API
Server Request Rate en Cloud Kubernetes > Anthos >
Cluster > K8s Control Plane.
Para resolver estos problemas de latencia o fallas de conexión, revisa las siguientes opciones de corrección:
Si se produce un error de red dentro del clúster, es posible que haya un problema con el complemento de la interfaz de red de contenedores (CNI). Por lo general, este problema es transitorio y se resuelve después de que se vuelve a crear o reprogramar un Pod.
Si el error de red se produce fuera del clúster, verifica si el cliente está configurado correctamente para acceder a él o vuelve a generar la configuración del cliente. Si la conexión pasa por un proxy o una puerta de enlace, verifica si funciona otra conexión que pase por el mismo mecanismo.
Si el servidor de API está sobrecargado, suele significar que muchos clientes acceden a él al mismo tiempo. Un solo cliente no puede sobrecargar un servidor de API debido a la limitación y la función Prioridad y equidad. Revisa la carga de trabajo en las siguientes áreas:
Funciona a nivel del Pod. Es más común crear Pods por error y olvidarlos que recursos de nivel superior.
Ajustar la cantidad de réplicas a través de un cálculo erróneo
Un webhook que reenvía la solicitud a sí mismo o amplifica la carga creando más solicitudes de las que controla.
¿Qué sigue?
Si necesitas asistencia adicional, comunícate con
Atención al cliente de Cloud.
También puedes consultar Cómo obtener asistencia para obtener más información sobre los recursos de asistencia, incluidos los siguientes:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-01 (UTC)"],[],[],null,["This page shows you how to resolve issues with the Kubernetes API server\n(`kube-apiserver`) for Google Distributed Cloud.\n\nThis page is for IT administrators and Operators who manage the\nlifecycle of the underlying tech infrastructure, and respond to alerts and pages\nwhen service level objectives (SLOs) aren't met or applications fail. To learn\nmore about common roles and example tasks that we reference in Google Cloud\ncontent, see\n[Common GKE user roles and tasks](/kubernetes-engine/enterprise/docs/concepts/roles-tasks).\n\nWebhook timeouts and failed webhook calls\n\nThese errors might be seen in a few different ways. If you experience any of the\nfollowing symptoms, it's possible that webhook calls are failing:\n\n- **Connection refused:** If `kube-apiserver` reports timeout errors for\n calling the webhook, the following error is reported in the logs:\n\n failed calling webhook \"server.system.private.gdc.goog\":\n failed to call webhook: Post \"https://root-admin-webhook.gpc-system.svc:443/mutate-system-private-gdc-goog-v1alpha1-server?timeout=10s\":\n dial tcp 10.202.1.18:443: connect: connection refused\n\n- **Context deadline exceeded:** You might also see the following error reported\n in the logs:\n\n failed calling webhook \"namespaces.hnc.x-k8s.io\": failed to call webhook: Post\n \"https://hnc-webhook-service.hnc-system.svc:443/validate-v1-namespace?timeout=10s\\\":\n context deadline exceeded\"\n\nIf you think that you are experiencing webhook timeouts or failed webhook calls,\nuse one of the following methods to confirm the issue:\n\n- Check the API server log to see if there is network issue.\n\n - Check the log for network-related errors like `TLS handshake error`.\n - Check if the IP/Port matches what the API server is configured to respond on.\n- Monitor webhook latency with the following steps:\n\n 1. In the console, go to the Cloud Monitoring page.\n\n [Go to the Cloud Monitoring page](https://console.cloud.google.com/monitoring/)\n 2. Select **Metrics explorer**.\n\n 3. Select the `apiserver_admission_webhook_admission_duration_seconds` metric.\n\nTo resolve this issue, review the following suggestions:\n\n- Additional firewall rules might be required for the webhook. For more\n information, see how to\n [add firewall rules for specific use cases](/kubernetes-engine/docs/how-to/private-clusters#add_firewall_rules).\n\n- If the webhook requires more time to complete, you can\n [configure a custom timeout value](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#timeouts).\n The webhooks latency adds to API request latency, so should be evaluated as\n quickly as possible.\n\n- If the webhook error blocks cluster availability or the webhook is harmless\n to remove and mitigates the situation, check if it's possible to temporarily\n set the `failurePolicy` to `Ignore` or remove the offending webhook.\n\nAPI server dial failure or latency\n\nThis error might be seen in a few different ways:\n\n- **External name resolution errors:** An external client might return errors\n that contain `lookup` in the message, such as:\n\n dial tcp: lookup kubernetes.example.com on 127.0.0.1:53: no such host\n\n This error doesn't apply to a client running within the cluster. The\n Kubernetes Service IP is injected, so no resolution is required.\n- **Network errors:** The client might print a generic network error when trying\n to dial the API server, like the following examples:\n\n dial tcp 10.96.0.1:443: connect: no route to host\n dial tcp 10.96.0.1:443: connect: connection refused\n dial tcp 10.96.0.1:443: connect: i/o timeout\n\n- **High latency connecting to API server:** The connection to API server might\n be successful, but the requests timeout on the client side. In this scenario,\n the client usually prints error messages containing `context deadline\n exceeded`.\n\nIf the connection to the API server fails completely, try the connection within\nthe same environment where the client reports the error.\n[Kubernetes ephemeral containers](https://kubernetes.io/docs/concepts/workloads/pods/ephemeral-containers/)\ncan be used to inject a debugging container to the existing namespaces as\nfollows:\n\n1. From where the problematic client runs, use `kubectl` to perform a request\n with high verbosity. For example, a `GET` request to `/healthz` usually\n requires no authentication:\n\n kubectl get -v999 --raw /healthz\n\n2. If the request fails or `kubectl` is unavailable, you can obtain the URL from\n the output and manually perform the request with `curl`. For example, if the\n service host obtained from the previous output was `https://192.0.2.1:36917/`,\n you can send a similar request as follows:\n\n # Replace \"--ca-cert /path/to/ca.pem\" to \"--insecure\" if you are accessing\n # a local cluster and you trust the connection cannot be tampered.\n # The output is always \"ok\" and thus contains no sensentive information.\n\n curl -v --cacert /path/to/ca.pem https://192.0.2.1:36917/healthz\n\n The output from this command usually indicates the root cause of a failed\n connection.\n | **Note:** You can't use the `ping` or `traceroute` commands to the IP address. A Kubernetes Service IP doesn't accept ICMP or protocols outside the list defined in the Service resource.\n\n If the connection is successful but is slow or times out, it indicates an\n overloaded API server. To confirm, in the console look at `API\n Server Request Rate` and request latency metrics in `Cloud Kubernetes \u003e Anthos \u003e\n Cluster \u003e K8s Control Plane`.\n\nTo resolve these connection failures or latency problems, review the following\nremediation options:\n\n- If a network error occurs within the cluster, there might be problem with the\n Container Network Interface (CNI) plugin. This problem is usually transient\n and resolves itself after a Pod recreation or reschedule.\n\n- If the network error is from outside the cluster, check if the client is\n properly configured to access the cluster, or generate the client\n configuration again. If the connection goes through a proxy or gateway, check\n if another connection that goes through the same mechanism works.\n\n- If the API server is overloaded, it usually means that many clients access the\n API server at the same time. A single client can't overload an API server due\n to throttling and the\n [Priority and Fairness](https://kubernetes.io/docs/concepts/cluster-administration/flow-control/)\n feature. Review the workload for the following areas:\n\n - Works at Pod level. It's more common to mistakenly create and forget Pods than higher level resources.\n - Adjust the number of replicas through erroneous calculation.\n - A webhook that loops back the request to itself or amplifies the load by creating more requests than it handles.\n\nWhat's next\n\nIf you need additional assistance, reach out to\n\n[Cloud Customer Care](/support-hub).\nYou can also see\n[Getting support](/kubernetes-engine/distributed-cloud/bare-metal/docs/getting-support) for more information about support resources, including the following:\n\n- [Requirements](/kubernetes-engine/distributed-cloud/bare-metal/docs/getting-support#intro-support) for opening a support case.\n- [Tools](/kubernetes-engine/distributed-cloud/bare-metal/docs/getting-support#support-tools) to help you troubleshoot, such as your environment configuration, logs, and metrics.\n- Supported [components](/kubernetes-engine/distributed-cloud/bare-metal/docs/getting-support#what-we-support)."]]