Saltar al contenido

Pod de Múltiples Contenedores: Cómo, Cuándo y Por Qué

city with high rise buildings during night time

Hablemos sobre la opción más peligrosa desde la perspectiva del diseño de Pods, ¡para que estés listo para usarla!


Foto de Timelab Pro en Unsplash

Una de las conversaciones habituales es sobre la composición y definición de componentes dentro de un Pod. Esto es normal para las personas que se trasladan de un despliegue tradicional a un entorno nativo de la nube, y la pregunta principal es: ¿Cuántos contenedores puedo tener dentro de un pod? 

Estoy seguro de que la mayoría de ustedes han escuchado o han hecho esa pregunta en algún momento de su viaje nativo de la nube, o incluso tienen esta duda internamente en este momento, y no hay duda en la respuesta: Un solo contenedor.

¡Espera, espera! ¡No dejes el post todavía! Sabemos que eso no es técnicamente cierto, pero es más fácil de entender inicialmente; solo puedes tener un pod haciendo una cosa.

Entonces, si ese es el caso, ¿por qué existen los pods de múltiples contenedores? Y lo más importante, si esta es la primera vez que escuchas ese concepto, ¿qué es un pod de múltiples contenedores?

Comencemos con la definición: Un pod de múltiples contenedores tiene más de un contenedor en su composición. Y cuando hablamos de múltiples contenedores, no estamos hablando de tener algunos initContainers para gestionar las dependencias. Aún así, estamos hablando de tener más de un contenedor ejecutándose simultáneamente y al mismo nivel, como puedes ver en la imagen a continuación:

Definición de Pod de Múltiples Contenedores

¿Kubernetes admite este modelo? Sí, por supuesto. Puedes definir dentro de tu sección de contenedores tantos contenedores como necesites. Entonces, desde un punto de vista técnico, no hay límite para tener tantos contenedores como necesites en el mismo pod. Pero la pregunta principal que deberías hacerte es:

¿Es esto lo que quieres hacer?

Un pod es la unidad más pequeña en Kubernetes como recordatorio. Despliegas y retiras pods, detienes y arrancas pods, reinicias pods, escalas pods. Así que cualquier cosa que esté dentro del mismo pod está altamente acoplada. Es como un paquete, y también comparten recursos. Así que es aún más crítico.

Imagina esta situación, me gustaría comprar un cuaderno, así que voy a la tienda y pido el cuaderno, pero no tienen un solo cuaderno. Aún así, tienen un paquete increíble: un cuaderno, un bolígrafo y una grapadora por solo $2 más que el precio de un solo cuaderno.

Así que piensas que este es un excelente precio porque estás obteniendo un bolígrafo y una grapadora por una pequeña parte de su precio si quisieras comprarlo por separado. Así que piensas que es una buena idea. Pero luego, recuerdas que también necesitas otros cuadernos para otros propósitos. Al final, necesitas diez cuadernos más, pero cuando necesitas comprarlos, también necesitas reconocer los diez bolígrafos y las diez grapadoras que ya no necesitas. OK, son más baratos, pero al final, estás pagando un precio razonable por algo que no necesitas. Así que, no es eficiente. Y lo mismo se aplica a la definición de la estructura del Pod.

Al final, ¿te mueves de despliegues monolíticos tradicionales a diferentes contenedores dentro de un pod para tener los mismos desafíos y problemas? ¿Cuál es el punto de hacer eso?

Ninguno.

Si no hay razón para tener dos contenedores estrechamente juntos, ¿por qué está permitido esto en la especificación de K8S? Porque esto es útil para algunos casos de uso y escenarios específicos. Hablemos de algunos de ellos.

  • Contenedores de Ayuda: Este es el más común y es que tienes diferentes contenedores dentro del pod. Aún así, uno es el principal, el que proporciona una capacidad de negocio o una característica, y el otro solo está ayudando de alguna manera.
  • Implementación del Patrón Sidecar: Otro enfoque común para tener esta composición es implementar el patrón sidecar. Así es como funciona al desplegar otro contenedor para realizar una capacidad específica. Lo has visto, por ejemplo, para Service Meshes, Arquitectura de Agregación de Logs, u otros componentes que siguen ese patrón.
  • Exportadores de Monitoreo: Otra cosa usual de ver es usar uno de estos contenedores para actuar como un exportador de las métricas de monitoreo del componente principal. Esto se ve usualmente en arquitecturas como Prometheus, donde cada pieza tiene su exportador para ser extraído del Servidor Prometheus

También hay hechos interesantes de compartir contenedores dentro de un pod porque, como se comentó, también comparten recursos como:

  • Volúmenes: Puedes, por ejemplo, definir una carpeta compartida para todos los diferentes contenedores dentro de un pod, para que un contenedor pueda leer información del otro para realizar su tarea de manera rápida y eficiente.
  • Comunicación Inter-procesos: Puedes comunicarte entre contenedores usando IPC para comunicarte de manera más eficiente.
  • Red: Los diferentes contenedores dentro de un pod también pueden acceder a puertos de otros contenedores simplemente alcanzando localhost.

Espero que este artículo te haya ayudado a entender por qué existe esta capacidad de tener muchos contenedores dentro del mismo pod, pero al mismo tiempo saber qué tipo de escenarios están usando este enfoque y tener algún razonamiento sobre si un nuevo caso de uso debería usar este enfoque o no.

Multi Container Pod: How, When, and Why

city with high rise buildings during night time

Let’s Talk About the Most Dangerous Option From Pod Design Perspective, so you can be ready to use it!


Photo by Timelab Pro on Unsplash

One of the usual conversations is about the composition and definition of components inside a Pod. This is normal for people moving from traditional deployment to a cloud-native environment, and the main question is: How many containers can I have inside a pod? 

I’m sure that most of you have heard or have asked that question at some point on your cloud-native journey, or even you have this doubt internally at this moment, and there is no doubt on the answer: One single container.

Wait, wait!! Don’t leave the post yet! We know that is not technically true, but it is easier to understand initially; you can only have a pod doing one thing.

So, if that’s the case, why do the multi container pods exist? And most importantly, if this is the first time you have heard that concept, what is a multi container pod?

Let’s start with the definition: A multi container pod has more than one container in its composition. And when we are talking about multi container, we are not talking about having some initContainers to manage the dependencies. Still, we are talking about having more than one container run simultaneously and at the same level, as you can see in the picture below:

Multi Container Pod Definition

Does Kubernetes support this model? Yes, for sure. You can define inside your containers section as many containers as you need. So, from a technical view, there is no limit to having as many containers as you need in the same pod. But the main question you should ask yourself is:

Is this what you want to do?

A pod is the smallest unit in Kubernetes as a reminder. You deploy and undeploy pods, stop and start pods, restart pods, scale pods. So anything that is inside the same pod is highly coupled. It’s like a bundle, and they also share resources. So it is even more critical.

Imagine this situation, I’d like to buy a notebook, so I go to the shop and ask for the notebook, but they don’t have a single notebook. Still, they have an incredible bundle: a notebook, a pen, and a stapler just for $2 more than a single notebook price.

So you think that this is an excellent price because you are getting a pen and a stapler for a small part of their price if you would like to buy it in isolation. So you think that’s a good idea. But then, you remind that you also need other notebooks for other purposes. In the end, you need ten more notebooks, but when you need to buy them, you also need to acknowledge the ten pens and ten staplers that you don’t need anymore. OK, there are cheaper, but in the end, you are paying a reasonable price for something that you don’t need. So, it is not efficient. And the same applies to the Pod structure definition.

In the end, you move from traditional monolith deployments to different containers inside a pod to have the same challenges and issues? What is the point of doing that?

None.

If there is no reason to have two containers tightly together, why is this allowed in the K8S specification? Because this is useful for some specific use-cases and scenarios. Let’s talk about some of them.

  • Helper Containers: This is the most common one and is that you have different containers inside the pod. Still, one is the main one, the one that provides a business capability or a feature, and the other is just helping in some way.
  • Sidecar Pattern Implementation: Another common approach to have this composition is implementing the sidecar pattern. This is how it works by deploying another container to perform a specific capability. You have seen it, for example, for Service Meshes, Log Aggregation Architecture, or other components that follow that pattern.
  • Monitoring Exporters: Another usual see to thing do is to use one of these containers to act as an exporter for the monitoring metrics of the main component. This is usually seen on architectures such as Prometheus, where each piece has its exporter to be scraped from the Prometheus Server

There are also exciting facts of sharing containers inside a pod because, as commented, they also share resources such as:

  • Volumes: You can, for example, define a shared folder for all the different containers inside a pod, so one container can read information for the other to perform its task quickly and efficiently.
  • Inter-process Communication: You can communicate between containers using IPC to communicate more efficiently.
  • Network: The different containers inside a pod can also access ports from other containers just reaching localhost.

I hope this article has helped you understand why this capability of having many containers inside the same pod exists, but at the same time to know which kind of scenarios are using this approach and having some reasoning about if a new use-case should be used this approach or not.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *