Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Inserta proxies de sidecar con Cloud Service Mesh
En este documento, se explica cómo configurar la inserción del proxy de sidecar con Cloud Service Mesh para mejorar la seguridad, la confiabilidad y la observabilidad de la red. Estas funciones se abstraen del contenedor principal de la aplicación y se implementan en un proxy fuera del proceso común (el archivo adicional), que se entrega como un contenedor por separado en el mismo Pod. Esto proporciona las funciones de Cloud Service Mesh sin rediseñar las aplicaciones de producción para participar en una malla de servicios.
La inserción automática del proxy de sidecar (inserción automática) ocurre cuando Cloud Service Mesh detecta una etiqueta de espacio de nombres que se configura para el Pod de la carga de trabajo. El proxy intercepta todo el tráfico de entrada y de salida de las cargas de trabajo y se comunica con Cloud Service Mesh.
Permisos necesarios para estas tareas
Para realizar las tareas de esta página, debes tener la función roles/container.clusterAdmin o una superior. Consulta las funciones de Google Kubernetes Engine para obtener detalles sobre los permisos incluidos en esta función.
Habilita la inserción automática de sidecar
La forma recomendada de insertar proxies de sidecar es usar el inyector automático del sidecar basado en webhooks, aunque puedes actualizar de forma manual la configuración de Kubernetes de tus Pods.
Para habilitar la inserción automática, etiqueta tus espacios de nombres con las etiquetas de inyección predeterminadas si la etiqueta predeterminada está configurada o con la etiqueta de revisión en tu espacio de nombres.
La etiqueta que agregues también depende de si implementaste Cloud Service Mesh administrado (con la API de Fleet o con asmcli) o si instalaste el plano de control en el clúster. El webhook de inyector de sidecar usa la etiqueta para asociar los sidecars insertados con una revisión de plano de control en particular.
Para habilitarla, usa este comando:
En el clúster
Usa el siguiente comando para encontrar la etiqueta de revisión en istiod:
kubectl -n istio-system get pods -l app=istiod --show-labels
En el resultado, en la columna LABELS, observa el valor de la etiqueta de revisión istiod, que está después del prefijo istio.io/rev=. En este ejemplo, el valor es asm-1264-1.
Aplica la etiqueta de revisión a los espacios de nombres y quita la etiqueta istio-injection (si existe). En el siguiente comando, NAMESPACE es el nombre del espacio de nombres en el que deseas habilitar la inserción automática y REVISION es la etiqueta de revisión que anotaste en el paso anterior.
Puedes ignorar el mensaje "istio-injection not found" en el resultado. Esto significa que el espacio de nombres no tenía la etiqueta istio-injection, que debería aparecer en las nuevas instalaciones de Cloud Service Mesh o en implementaciones nuevas. Debido a que el comportamiento de la inserción automática no está definido cuando un espacio de nombres tiene tanto la etiqueta istio-injection como la de revisión, todos los comandos kubectl label de la documentación de Cloud Service Mesh garantizan de forma explícita que solo se establezca una.
Para reiniciar los Pods afectados, sigue los pasos de la siguiente sección.
Malla de servicios administrados
Usa el siguiente comando para ubicar los canales de versiones disponibles:
kubectl -n istio-system get controlplanerevision
El resultado es similar a este:
NAME AGE
asm-managed 6d7h
En el resultado, selecciona el valor en la columna NAME es la etiqueta de REVISION que corresponde al canal de versiones disponible para la versión de Cloud Service Mesh. Aplica esta etiqueta a los espacios de nombres y quita la etiqueta istio-injection (si existe).
En el siguiente comando, reemplaza REVISION por la etiqueta de revisión que anotaste antes y reemplaza NAMESPACE por el nombre del espacio de nombres en el que deseas habilitar la inserción automática:
Puedes ignorar el mensaje "istio-injection not found" en el resultado. Esto significa que el espacio de nombres no tenía la etiqueta istio-injection, que debería aparecer en las nuevas instalaciones de Cloud Service Mesh o en implementaciones nuevas. Debido a que el comportamiento de la inserción automática no está definido cuando un espacio de nombres tiene tanto la etiqueta istio-injection como la de revisión, todos los comandos kubectl label de la documentación de Cloud Service Mesh garantizan de forma explícita que solo se establezca una.
Para reiniciar los Pods afectados, sigue los pasos de la siguiente sección.
Si no usaste un Deployment, borra los pods, y se volverán a crear de forma automática con sidecars:
kubectl delete pod -n YOUR_NAMESPACE --all
Verifica que todos los pods en el espacio de nombres tengan sidecars incorporados:
kubectl get pod -n YOUR_NAMESPACE
En el siguiente resultado de ejemplo del comando anterior, observa que la columna READY indica que hay dos contenedores para cada una de tus cargas de trabajo: el contenedor principal y el contenedor del proxy de sidecar.
NAME READY STATUS RESTARTS AGE
YOUR_WORKLOAD 2/2 Running 0 20s
...
[[["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-04 (UTC)"],[],[],null,["Inject sidecar proxies with Cloud Service Mesh\n\nThis document covers how to configure sidecar proxy injection with Cloud Service Mesh\nto enhance network security, reliability, and observability. These functions are\nabstracted away from the application's primary container and implemented in a\ncommon out-of-process proxy (the sidecar), delivered as a separate container in\nthe same Pod. This provides the\n[Cloud Service Mesh's features](/service-mesh/v1.20/docs/overview) without redesigning your\nproduction applications to participate in a service mesh.\n\nAutomatic sidecar proxy injection (auto-injection) occurs when Cloud Service Mesh\ndetects a namespace label you configure for the workload's Pod. The proxy\nintercepts all inbound and outbound traffic to the workloads and communicates\nwith Cloud Service Mesh.\n\nPermissions required for these tasks\n\n\nTo perform the tasks on this page, you must have the\n`roles/container.clusterAdmin` or a higher role. See\n[Google Kubernetes Engine roles](/iam/docs/understanding-roles#container) for\ndetails on the permissions included in this role.\n\nEnabling automatic sidecar injection\n\nThe recommended way to inject sidecar proxies is to use the webhooks-based\nautomatic sidecar injector, although you can manually update your Pods'\nKubernetes configuration.\n\nTo enable auto-injection, you label your namespaces with the\n*[default injection labels](https://istio.io/latest/docs/setup/upgrade/canary/#default-tag)*\nif the default tag is set up, or with the\n[revision label](/service-mesh/v1.20/docs/revisions-overview) to your namespace.\nThe label that you add also depends on whether you deployed\nmanaged Cloud Service Mesh (with the\n[fleet API](/service-mesh/docs/managed/provision-managed-anthos-service-mesh) or with\n[`asmcli`](/service-mesh/docs/managed/provision-managed-anthos-service-mesh-asmcli)), or\ninstalled the in-cluster control plane. The label is used by the sidecar\ninjector webhook to associate injected sidecars with a particular control plane\nrevision.\n\nTo enable auto-injection: \n\nIn-cluster\n\n1. Use the following command to locate the revision label on `istiod`:\n\n kubectl -n istio-system get pods -l app=istiod --show-labels\n\n The output looks similar to the following: \n\n ```bash\n NAME READY STATUS RESTARTS AGE LABELS\n istiod-asm-1264-1-5788d57586-bljj4 1/1 Running 0 23h app=istiod,istio.io/rev=asm-1264-1,istio=istiod,pod-template-hash=5788d57586\n istiod-asm-1264-1-5788d57586-vsklm 1/1 Running 1 23h app=istiod,istio.io/rev=asm-1264-1,istio=istiod,pod-template-hash=5788d57586\n ```\n\n In the output, under the `LABELS` column, note the value of the `istiod`\n revision label, which follows the prefix `istio.io/rev=`. In this\n example, the value is `asm-1264-1`.\n\n\n | **Note:** You can substitute `istio.io/rev` with the `istio-injection=enabled` label if the [default tag](https://istio.io/latest/docs/setup/upgrade/canary/#default-tag) is configured. Verify the default tag exists by running ` istioctl tag list` with the `istioctl` from \u003cvar translate=\"no\"\u003eOUTPUT_DIR\u003c/var\u003e.\n\n \u003cbr /\u003e\n\n2. Apply the revision label to namespaces and remove the istio-injection label\n (if it exists). In the following command, \u003cvar translate=\"no\"\u003eNAMESPACE\u003c/var\u003e is\n the name of the namespace where you want to enable auto-injection, and\n \u003cvar translate=\"no\"\u003eREVISION\u003c/var\u003e is the revision label you noted in the\n previous step.\n\n kubectl label namespace \u003cvar translate=\"no\"\u003eNAMESPACE\u003c/var\u003e istio-injection- istio.io/rev=\u003cvar translate=\"no\"\u003eREVISION\u003c/var\u003e --overwrite\n\n\n You can ignore the message `\"istio-injection not found\"` in the\n output. That means that the namespace didn't previously have the\n `istio-injection` label, which you should expect in new\n installations of Cloud Service Mesh or new deployments. Because auto-injection\n behavior is undefined when a namespace has both the `istio-injection`\n and the revision label, all `kubectl label` commands in the\n Cloud Service Mesh documentation explicitly ensure that only one is set.\n3. Restart the affected pods, using the steps in the next section.\n\nManaged service mesh\n\n1. Use the following command to locate the available release channels:\n\n kubectl -n istio-system get controlplanerevision\n\n The output is similar to the following: \n\n NAME AGE\n asm-managed 6d7h\n\n In the output, select the value under the `NAME` column is the\n \u003cvar translate=\"no\"\u003eREVISION\u003c/var\u003e label that corresponds to the available\n [release channel](/service-mesh/docs/managed/select-a-release-channel#anthos_service_mesh_versions_per_channel)\n for the Cloud Service Mesh version. Apply this label to your namespaces, and\n remove the `istio-injection` label (if it exists).\n In the following command, replace \u003cvar translate=\"no\"\u003eREVISION\u003c/var\u003e with the\n revision label you noted above, and replace\n \u003cvar translate=\"no\"\u003eNAMESPACE\u003c/var\u003e` ` with the name of the namespace where you\n want to enable auto-injection: \n\n kubectl label namespace \u003cvar translate=\"no\"\u003eNAMESPACE\u003c/var\u003e istio-injection- istio.io/rev=\u003cvar translate=\"no\"\u003eREVISION\u003c/var\u003e --overwrite\n\n\n You can ignore the message `\"istio-injection not found\"` in the\n output. That means that the namespace didn't previously have the\n `istio-injection` label, which you should expect in new\n installations of Cloud Service Mesh or new deployments. Because auto-injection\n behavior is undefined when a namespace has both the `istio-injection`\n and the revision label, all `kubectl label` commands in the\n Cloud Service Mesh documentation explicitly ensure that only one is set.\n2. Restart the affected pods, using the steps in the next section.\n\n3. If you also deployed the optional\n [Google-managed data plane](/service-mesh/docs/managed/provision-managed-anthos-service-mesh#managed-data-plane),\n annotate the `demo` namespace as follows:\n\n kubectl annotate --overwrite namespace \u003cvar translate=\"no\"\u003eYOUR_NAMESPACE\u003c/var\u003e \\\n mesh.cloud.google.com/proxy='{\"managed\":\"true\"}'\n\nRestart Pods to update sidecar proxies **Warning:** Unless you have a load balancer or router setup for [blue-green deployments](https://martinfowler.com/bliki/BlueGreenDeployment.html), make sure you test restarting Pods in a staging environment to verify that your services can handle any potential traffic interruption.\n\nWith automatic sidecar injection, you can update the sidecars for existing Pods\nwith a Pod restart:\n\nHow you restart Pods depends on if they were created as part of a\n[Deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/).\n\n1. If you used a Deployment, restart the Deployment, which restarts all Pods\n with sidecars:\n\n ```\n kubectl rollout restart deployment -n YOUR_NAMESPACE\n ```\n\n If you didn't use a Deployment, delete the Pods, and they are automatically\n recreated with sidecars: \n\n ```\n kubectl delete pod -n YOUR_NAMESPACE --all\n ```\n2. Check that all the Pods in the namespace have sidecars injected:\n\n ```\n kubectl get pod -n YOUR_NAMESPACE\n ```\n\n In the following example output from the previous command, notice that the\n `READY` column indicates there are two containers for each of your\n workloads: the primary container and the container for the sidecar proxy. \n\n ```\n NAME READY STATUS RESTARTS AGE\n YOUR_WORKLOAD 2/2 Running 0 20s\n ...\n ```\n\nWhat's next\n\nLearn more about:\n\n- [Cloud Service Mesh control plane revisions](/service-mesh/v1.20/docs/revisions-overview)\n- [Deploying workloads](/kubernetes-engine/docs/how-to/deploying-workloads-overview)\n- [Customizing injection](https://istio.io/latest/docs/setup/additional-setup/sidecar-injection/#customizing-injection)"]]