Merge pull request #411 from manuelver/feature/translateES-13

This commit is contained in:
Michael Cade 2023-05-08 00:10:11 +02:00 committed by GitHub
commit 0272a57049
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 362 additions and 365 deletions

View File

@ -1,132 +1,145 @@
## Docker Images & Hands-On with Docker Desktop ## Imágenes Docker y Manos a la Obra con Docker Desktop
We now have Docker Desktop installed on our system. (If you are running Linux then you still have options but no GUI but docker does work on Linux.)[Install Docker Engine on Ubuntu](https://docs.docker.com/engine/install/ubuntu/) (Other distributions also available.) Ahora tenemos Docker Desktop instalado en nuestro sistema. (Si estás ejecutando Linux, tienes más opciones pero no el GUI.)[Instalar Docker Engine en Ubuntu](https://docs.docker.com/engine/install/ubuntu/) (También está disponible para otras distribuciones.)
In this post, we are going to get started with deploying some images into our environment. A recap on what a Docker Image is - A Docker image is a file used to execute code in a Docker container. Docker images act as a set of instructions to build a Docker container, like a template. Docker images also act as the starting point when using Docker. En este post, vamos a empezar con el despliegue de algunas imágenes en nuestro entorno. Una imagen Docker es un archivo utilizado para ejecutar código en un contenedor Docker. Las imágenes Docker actúan como un conjunto de instrucciones para construir un contenedor Docker, como una plantilla. Las imágenes Docker también actúan como el punto de partida cuando se utiliza Docker.
Now is a good time to go and create your account on [DockerHub](https://hub.docker.com/) Ahora es un buen momento para crear tu cuenta en [DockerHub](https://hub.docker.com/)
![](Images/Day44_Containers1.png) ![](Images/Day44_Containers1.png)
DockerHub is a centralised resource for working with Docker and its components. Most commonly known as a registry to host docker images. But there are a lot of additional services here which can be used in part with automation or integrated into GitHub as well as security scanning. DockerHub es un recurso centralizado para trabajar con Docker y sus componentes. Más comúnmente conocido como un registro para alojar imágenes Docker. Pero hay un montón de servicios adicionales que se pueden utilizar en parte con la automatización o integración en GitHub, así como el escaneo de seguridad.
If you scroll down once logged in you are going to see a list of container images, You might see database images for MySQL, hello-world etc. Think of these as great baseline images or you might just need a database image and you are best to use the official one which means you don't need to create your own. Desplazándote hacia abajo una vez logueado verás una lista de imágenes de contenedores, es posible que veas imágenes de bases de datos MySQL, hello-world, etc. Piensa en estas como las imágenes de referencia, puede que sólo necesites una imagen de BBDD MySQL y la mejor sea utilizar la oficial, lo que significa que no es necesario crear una propia personalizada.
![](Images/Day44_Containers2.png) ![](Images/Day44_Containers2.png)
We can drill deeper into the view of available images and search across categories, operating systems and architectures. The one thing I highlight below is the Official Image, this should give you peace of mind about the origin of this container image. Podemos profundizar en la vista de imágenes disponibles y buscar por categorías, sistemas operativos y arquitecturas. Hay que destacar la Imagen Oficial, porque esta debería darte tranquilidad sobre su origen. Para nada recomiendo utilizar imágenes no oficiales, sobretodo en producción. En caso de que lo hagas, asegúrate al menos de que son de un editor verificado.
![](Images/Day44_Containers3.png) ![](Images/Day44_Containers3.png)
We can also search for a specific image, for example, WordPress might be a good base image that we want we can do that at the top and find all container images related to WordPress. Below are notices that we also have verified publisher. Por otra parte, podemos buscar una imagen específica, por ejemplo, WordPress podría ser una buena imagen de base que incluye todas las imágenes de contenedores relacionados que necesite la aplicación. Ten en cuenta que existe diferencias entre imagen oficial y editor verificado.
- **Imagen Oficial** - Las imágenes Oficiales de Docker son un conjunto curado de código abierto de Docker y repositorios de soluciones "drop-in".
- Official Image - Docker Official images are a curated set of Docker open source and "drop-in" solution repositories. - **Editor verificado** - Contenido Docker de alta calidad de editores verificados. Estos productos son publicados y mantenidos directamente por una entidad comercial.
- Verified Publisher - High-quality Docker content from verified publishers. These products are published and maintained directly by a commercial entity.
![](Images/Day44_Containers4.png) ![](Images/Day44_Containers4.png)
### Exploring Docker Desktop ### Explorando Docker Desktop
We have Docker Desktop installed on our system and if you open this I expect unless you had this already installed you will see something similar to the image below. As you can see we have no containers running and our docker engine is running. Tenemos Docker Desktop instalado en nuestro equipo windows. Si lo abres por primera vez verás algo similar a la imagen de abajo. Como puedes ver no tenemos ningún contenedor ejecutándose y nuestro motor docker está funcionando.
![](Images/Day44_Containers5.png) ![](Images/Day44_Containers5.png)
Because this was not a fresh install for me, I do have some images already downloaded and available on my system. You will likely see nothing in here. Debido a que esta no fue la primera instalación, tengo algunas imágenes ya descargadas y disponibles en mi sistema. Es probable que lo veas diferente.
![](Images/Day44_Containers6.png) ![](Images/Day44_Containers6.png)
Under remote repositories, this is where you will find any container images you have stored in your docker hub. You can see from the below I do not have any images. En los repositorios remotos es donde encontrarás cualquier imagen de contenedor que hayas almacenado en tu docker hub. Puedes ver en la imagen de abajo que no tengo ninguna imagen.
![](Images/Day44_Containers7.png) ![](Images/Day44_Containers7.png)
We can also clarify this on our dockerhub site and confirm that we have no repositories there. Hay que confirmarlo en nuestro sitio dockerhub y confirmar que no tenemos repositorios allí.
![](Images/Day44_Containers8.png) ![](Images/Day44_Containers8.png)
Next, we have the Volumes tab, If you have containers that require persistence then this is where we can add these volumes to your local file system or a shared file system. A continuación, tenemos la pestaña Volumes. Si tienes contenedores que requieren persistencia será aquí donde podemos añadir estos volúmenes al sistema de archivos local o a un sistema de archivos compartido.
![](Images/Day44_Containers9.png) ![](Images/Day44_Containers9.png)
At the time of writing, there is also a Dev Environments tab, this is going to help you collaborate with your team instead of moving between different git branches. We won't be covering this. En el momento de escribir esto, también hay una pestaña de Entornos de Desarrollo, esto va a ayudarte a colaborar con tu equipo en lugar de moverte entre diferentes ramas de git. No vamos a cubrir esto.
![](Images/Day44_Containers10.png) ![](Images/Day44_Containers10.png)
Going back to the first tab you can see that there is a command we can run which is a getting started container. Let's run `docker run -d -p 80:80 docker/getting-started` in our terminal. Volviendo a la primera pestaña puedes ver que hay un comando que podemos ejecutar para iniciar el contenedor. Ejecutamos en nuestro terminal:
```shell
docker run -d -p 80:80 docker/getting-started
```
![](Images/Day44_Containers11.png) ![](Images/Day44_Containers11.png)
If we go and check our docker desktop window again, we are going to see that we have a running container. Si comprobamos nuestro docker desktop veremos que ya tenemos un contenedor en ejecución.
![](Images/Day44_Containers12.png) ![](Images/Day44_Containers12.png)
You might have noticed that I am using WSL2 and for you to be able to use that you will need to make sure this is enabled in the settings. Te habrás dado cuenta de que estoy usando WSL2. Para usarlo tendrás que asegurarte de que está activado en la configuración.
![](Images/Day44_Containers13.png) ![](Images/Day44_Containers13.png)
If we now go and check our Images tab again, you should now see an in-use image called docker/getting-started. Si ahora comprobamos nuestra pestaña Imágenes deberías ver una imagen en uso llamada docker/getting-started.
![](Images/Day44_Containers14.png) ![](Images/Day44_Containers14.png)
Back to the Containers/Apps tab, click on your running container. You are going to see the logs by default and along the top, you have some options to choose from, in our case I am pretty confident that this is going to be a web page running in this container so we are going to choose the open in the browser. De vuelta a la pestaña Contenedores/Apps, haz click en tu contenedor en ejecución. Verás los registros por defecto y en la parte superior tiene algunas opciones para elegir. En nuestro caso no va a ser una web que se ejecute en este contenedor por lo que vamos a elegir la apertura en el navegador.
![](Images/Day44_Containers15.png) ![](Images/Day44_Containers15.png)
When we hit that button above sure enough a web page should open hitting your localhost and display something similar to below. Cuando pulsemos el botón de arriba, se abrirá una web que mostrará algo similar a lo que se muestra a continuación.
This container also has some more detail on our containers and images. Este contenedor también tiene algunos detalles más sobre nuestros contenedores e imágenes.
![](Images/Day44_Containers16.png) ![](Images/Day44_Containers16.png)
We have now run our first container. Nothing too scary just yet. What about if we wanted to pull one of the container images down from DockerHub? Maybe there is a `hello world` docker container we could use. Ya hemos ejecutado nuestro primer contenedor. Nada demasiado aterrador todavía. ¿Y si quisiéramos bajar una de las imágenes de contenedor de DockerHub? Podemos usar un contenedor docker llamado `hello world` para comprobarlo.
I went ahead and stopped the getting started container not that it's taking up any mass amount of resources but for tidiness, as we walk through some more steps. Me adelanté y detuve el contenedor de inicio, no es que esté ocupando una cantidad masiva de recursos, sino para mantener un orden mientras vemos algunos pasos más.
Back in our terminal let's go ahead and run `docker run hello-world` and see what happens. De vuelta en nuestro terminal vamos a seguir adelante y ejecutar `docker run hello-world` y a ver qué pasa.
You can see we did not have the image locally so we pulled that down and then we got a message that is written into the container image with some information on what it did to get up and running and some links to reference points. Puedes ver que no teníamos la imagen localmente así que la bajamos y entonces tenemos un mensaje que está escrito en la imagen del contenedor con alguna información sobre lo que hizo para ponerse en marcha y algunos enlaces a puntos de referencia.
![](Images/Day44_Containers17.png) ![](Images/Day44_Containers17.png)
However, if we go and look in Docker Desktop now we have no running containers but we do have an exited container that used the hello-world message, meaning it came up, delivered the message and then is terminated. Sin embargo, si vamos y miramos en Docker Desktop ahora no tenemos ningún contenedor en ejecución, pero sí tenemos un contenedor que utilizó el mensaje hola-mundo, lo que significa que apareció, entregó el mensaje y luego se terminó.
![](Images/Day44_Containers18.png) ![](Images/Day44_Containers18.png)
And for the last time, let's just go and check the images tab and see that we have a new hello-world image locally on our system, meaning that if we run the `docker run hello-world` command again in our terminal we would not have to pull anything unless a version changes. Y para terminar vamos a comprobar la pestaña images de nuevo en la que tendremos una nueva imagen hello-world localmente, lo que significa que si ejecutamos de nuevo el comando `docker run hello-world` en nuestro terminal no tendríamos que descargar nada a menos de que cambie la versión.
![](Images/Day44_Containers19.png) ![](Images/Day44_Containers19.png)
The message from the hello-world container set down the challenge of running something a little more ambitious. El mensaje del contenedor hello-world nos planteó el reto de ejecutar algo un poco más ambicioso.
Challenge Accepted! ¡Reto aceptado!
![](Images/Day44_Containers20.png) ![](Images/Day44_Containers20.png)
In running `docker run -it ubuntu bash` in our terminal we are going to run a containerised version of Ubuntu well not a full copy of the Operating system. You can find out more about this particular image on [DockerHub](https://hub.docker.com/_/ubuntu) Al ejecutar `docker run -it ubuntu bash` en nuestro terminal vamos a ejecutar una versión en un contenedor de Ubuntu, que no es una copia completa del sistema operativo. Puedes encontrar más información sobre esta imagen en particular en [DockerHub](https://hub.docker.com/_/ubuntu)
You can see below when we run the command we now have an interactive prompt (`-it`) and we have a bash shell into our container. Puedes ver a continuación cuando ejecutamos el comando que ahora tenemos un símbolo del sistema interactivo (`-it`) y tenemos un shell bash en nuestro contenedor.
![](Images/Day44_Containers21.png) ![](Images/Day44_Containers21.png)
We have a bash shell but we don't have much more which is why this container image is less than 30MB. Tenemos una shell bash pero no tenemos mucho más, piensa que la imagen de este contenedor pesa menos de 30MB.
![](Images/Day44_Containers22.png) ![](Images/Day44_Containers22.png)
But we can still use this image and we can still install software using our apt package manager, we can update our container image and upgrade also. Pero con esta imagen podemos, por ejemplo:
- Instalar todo el software que necesitemos usando nuestro gestor de paquetes apt.
- Actualizar nuestra imagen de contenedor
- Crear un nuevo contenedor a partir de esta imagen
- Utilizar el contenedor interactivo para pruebas.
Y todo lo que imaginemos.
![](Images/Day44_Containers23.png) ![](Images/Day44_Containers23.png)
Or maybe we want to install some software into our container, I have chosen a really bad example here as pinta is an image editor and it's over 200MB but hopefully you get where I am going with this. This would increase the size of our container considerably but still, we are going to be in the MB and not in the GB. He instalado algún software en el contenedor, he elegido un ejemplo muy malo aquí ya que `pinta` es un editor de imágenes de más de 200 MB, pero espero que entiendas a dónde voy con esto. Esto aumentaría el tamaño de nuestro contenedor considerablemente pero aún así, vamos a estar en unos MB sin llegar al GB.
![](Images/Day44_Containers24.png) ![](Images/Day44_Containers24.png)
I wanted that to hopefully give you an overview of Docker Desktop and the not-so-scary world of containers when you break it down with simple use cases, we do need to cover some networking, security and other options we have vs just downloading container images and using them like this. By the end of the section, we want to have made something and uploaded it to our DockerHub repository and be able to deploy it. Quería que esto te diera una visión general de Docker Desktop y el mundo no tan aterrador de los contenedores cuando lo desglosas con casos de uso simples. Ahora tenemos que ver algo de redes, de seguridad y otras opciones mínimas que necesitamos de base.
## Resources ## Recursos
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE) - [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI) - [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
- [Docker Tutorial for Beginners - What is Docker? Introduction to Containers](https://www.youtube.com/watch?v=17Bl31rlnRM&list=WL&index=128&t=61s) - [Docker Tutorial for Beginners - What is Docker? Introduction to Containers](https://www.youtube.com/watch?v=17Bl31rlnRM&list=WL&index=128&t=61s)
- [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc) - [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc)
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
See you on [Day 45](day45.md) Nos vemos en el [Día 45](day45.md)

View File

@ -1,66 +1,67 @@
## The anatomy of a Docker Image ## La anatomía de una imagen Docker
In the last session, we covered some basics of how we can use Docker Desktop combined with DockerHub to deploy and run some verified images. A recap on what an image is, you won't forget things if I keep mentioning them. En la última sesión, vimos algunos aspectos básicos de cómo podemos utilizar Docker Desktop combinado con DockerHub para desplegar y ejecutar algunas imágenes verificadas. Una recapitulación sobre lo que es una imagen, no olvidarás cosas si sigo mencionándolas.
A Docker image is a read-only template that contains a set of instructions for creating a container that can run on the Docker platform. It provides a convenient way to package up applications and preconfigured server environments, which you can use for your private use or share publicly with other Docker users. Docker images are also the starting point for anyone using Docker for the first time. Una imagen Docker es una plantilla de sólo lectura que contiene un conjunto de instrucciones para crear un contenedor que se puede ejecutar en la plataforma Docker. Proporciona una forma práctica de empaquetar aplicaciones y entornos de servidor preconfigurados, que puedes utilizar para tu uso privado o compartir públicamente con otros usuarios de Docker. Las imágenes Docker son también el punto de partida para cualquiera que utilice Docker por primera vez.
What happens if we want to create our own Docker image? For us to do this we would create a Dockerfile. You saw how we could take that Ubuntu container image and we could add our software and we would have our container image with the software that we wanted and everything is good, however, if that container is shut down or thrown away then all those software updates and installations go away there is no repeatable version of what we had done. So that is great for showing off the capabilities but it doesn't help with the transport of images across multiple environments with the same set of software installed each time the container is run. ¿Qué ocurre si queremos crear nuestra propia imagen Docker? Para ello crearíamos un Dockerfile. Ya viste cómo podríamos tomar esa imagen de contenedor Ubuntu y añadir nuestro software. Con lo que tendríamos nuestra imagen de contenedor con el software que queremos, sin embargo, si ese contenedor se apaga o se destruye todas esas actualizaciones de software y las instalaciones desaparecen, perdemos los cambios sin una versión repetible. Así que eso es genial para mostrar las capacidades, pero no ayuda con el transporte de imágenes a través de múltiples entornos con el mismo conjunto de software instalado cada vez que se ejecuta el contenedor, que es la potencia de docker.
### What is a Dockerfile ### ¿Qué es un Dockerfile?
A dockerfile is a text file that contains commands you would normally execute manually to build a docker image. Docker can build images automatically by reading the instructions we have in our dockerfile. Un dockerfile es un archivo de texto que contiene comandos que normalmente ejecutarías manualmente para construir una imagen docker. Docker puede construir imágenes automáticamente leyendo las instrucciones que tenemos en nuestro dockerfile.
Each of the files that make up a docker image is known as a layer. these layers form a series of images, built on top of each other in stages. Each layer is dependent on the layer immediately below it. The order of your layers is key to the efficiency of the lifecycle management of your docker images. Cada uno de los archivos que componen una imagen docker se conoce como una capa. Estas capas forman una serie de imágenes, construidas unas sobre otras por etapas. Cada capa depende de la capa inmediatamente inferior. El orden de tus capas es clave para la eficiencia de la gestión del ciclo de vida de tus imágenes docker.
We should organise our layers that change most often as high in the stack as possible, this is because when you make changes to a layer in your image, Docker not only rebuilds that particular layer but all layers built from it. Therefore a change to a layer at the top involves the least amount of work to rebuild the entire image. Debemos organizar nuestras capas que cambian más a menudo lo más alto posible en la pila, esto se debe a que cuando se realizan cambios en una capa de la imagen, Docker no sólo reconstruye esa capa en particular, sino todas las capas construidas a partir de ella. Por lo tanto, un cambio en una capa en la parte superior implica la menor cantidad de trabajo para reconstruir toda la imagen.
Each time docker launches a container from an image (like we ran yesterday) it adds a writeable layer, known as the container layer. This stores all changes to the container throughout its runtime. This layer is the only difference between a live operational container and the source image itself. Any number of like-for-like containers can share access to the same underlying image while maintaining their state. Cada vez que docker lanza un contenedor desde una imagen (como hicimos ayer) añade una capa escribible, conocida como la capa del contenedor. Esto almacena todos los cambios en el contenedor a lo largo de su tiempo de ejecución. Esta capa es la única diferencia entre un contenedor operativo en vivo y la propia imagen de origen. Cualquier número de contenedores similares pueden compartir el acceso a la misma imagen subyacente, manteniendo su estado.
Back to the example, we used yesterday with the Ubuntu image. We could run that same command multiple times and on the first container we could go and install pinta and on the second we could install figlet with two different applications, different purposes, different sizes etc. Each container that we deployed shares the same image but not the same state and then that state is then gone when we remove the container. Volviendo al ejemplo que utilizamos ayer con la imagen de Ubuntu. Podríamos ejecutar ese mismo comando múltiples veces y en el primer contenedor podríamos instalar pinta y en el segundo podríamos instalar figlet con dos aplicaciones diferentes, diferentes propósitos, diferentes tamaños, etc. Cada contenedor que desplegamos comparte la misma imagen pero no el mismo estado y luego ese estado desaparece cuando eliminamos el contenedor.
![](Images/Day45_Containers1.png) ![](Images/Day45_Containers1.png)
Following the example above with the Ubuntu image, but also many other ready-built container images available on DockerHub and other third-party repositories. These images are generally known as the parent image. It is the foundation upon which all other layers are built and provides the basic building blocks for our container environments. Estas imágenes se conocen generalmente como la imagen padre. Es la base sobre la que se construyen todas las demás capas y proporciona los bloques de construcción básicos para nuestros entornos de contenedores.
Together with a set of individual layer files, a Docker image also includes an additional file known as a manifest. This is essentially a description of the image in JSON format and comprises information such as image tags, a digital signature, and details on how to configure the container for different types of host platforms. Junto con un conjunto de archivos de capas individuales, una imagen Docker también incluye un archivo adicional conocido como manifiesto. Se trata básicamente de una descripción de la imagen en formato JSON y contiene información como las etiquetas de la imagen, una firma digital y detalles sobre cómo configurar el contenedor para distintos tipos de plataformas host.
![](Images/Day45_Containers2.png) ![](Images/Day45_Containers2.png)
### How to create a docker image ### Cómo crear una imagen docker
There are two ways we can create a docker image. We can do it a little on the fly with the process that we started yesterday, we pick our base image spin up that container, and install all of the software and dependencies that we wish to have on our container. Hay dos maneras en que podemos crear una imagen docker. Podemos hacerlo un poco sobre la marcha con el proceso que empezamos ayer, elegimos nuestra imagen base, giramos ese contenedor e instalamos todo el software y las dependencias que deseamos tener en nuestro contenedor.
Then we can use the `docker commit container name` then we have a local copy of this image under docker images and in our docker desktop images tab. Luego podemos usar el `docker commit container name` entonces tenemos una copia local de esta imagen bajo docker images y en nuestra pestaña docker desktop images.
Super simple, I would not recommend this method unless you want to understand the process, it is going to be very difficult to manage lifecycle management this way and a lot of manual configuration/reconfiguration. But it is the quickest and most simple way to build a docker image. Great for testing, troubleshooting, validating dependencies etc. Con este método no entenderás el proceso y será muy difícil manejar la gestión del ciclo de vida, además de tener un montón de configuraciones manuales/reconfiguraciones. Pero se entiende que es la forma más rápida y sencilla de construir una imagen docker. Aunque no sea recomendable puede resultar ideal para pruebas, resolución de problemas, validación de dependencias, etc.
The way we intend to build our image is through a dockerfile. Which gives us a clean, compact and repeatable way to create our images. Much easier lifecycle management and easy integration into Continous Integration and Continuous delivery processes. But as you might gather it is a little more difficult than the first mentioned process. La mejor práctica de construir imágenes es a través de un dockerfile. Lo que nos da una forma limpia, compacta y repetible para crear nuestras imágenes con unas pocas líneas. La gestión del ciclo de vida es mucho más fácil, así como la integración en procesos de CI/CD. Pero como se puede deducir, implica un aprendizaje. El saber no ocupa lugar.
Using the dockerfile method is much more in tune with real-world, enterprise-grade container deployments. El uso del método dockerfile está mucho más en sintonía con el mundo real, los despliegues de contenedores de nivel empresarial.
A dockerfile is a three-step process whereby you create the dockerfile and add the commands you need to assemble the image. Un dockerfile es un proceso de tres pasos mediante el cual se crea el dockerfile y se añaden los comandos necesarios para montar la imagen.
The following table shows some of the dockerfile statements we will be using or that you will most likely be using. La siguiente tabla muestra algunas de las sentencias dockerfile que utilizaremos o que probablemente necesitarás.
| Command | Purpose | | Comando | Propósito |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | ---------- | --------------------------------------------------------------------------------------------------------------------------- |
| FROM | To specify the parent image. | | FROM | Para especificar la imagen base. |
| WORKDIR | To set the working directory for any commands that follow in the Dockerfile. | | WORKDIR | Para establecer el directorio de trabajo para cualquier comando que siga en el Dockerfile. |
| RUN | To install any applications and packages required for your container. | | RUN | Para instalar las aplicaciones y paquetes necesarios para su contenedor. |
| COPY | To copy over files or directories from a specific location. | | COPY | Para copiar archivos o directorios desde una ubicación específica. |
| ADD | As COPY, but also able to handle remote URLs and unpack compressed files. | | ADD | Como COPY, pero también capaz de manejar URLs remotas y desempaquetar archivos comprimidos. |
| ENTRYPOINT | Command that will always be executed when the container starts. If not specified, the default is /bin/sh -c | | ENTRYPOINT | Comando que se ejecutará siempre cuando se inicie el contenedor. Si no se especifica, el valor por defecto es `/bin/sh -c` |
| CMD | Arguments passed to the entrypoint. If ENTRYPOINT is not set (defaults to /bin/sh -c), the CMD will be the commands the container executes. | | CMD | Argumentos pasados al punto de entrada. Si no se establece ENTRYPOINT, el CMD serán los comandos que ejecute el contenedor. |
| EXPOSE | To define which port through which to access your container application. | | EXPOSE | Para definir el puerto a través del cual acceder a su aplicación contenedora. |
| LABEL | To add metadata to the image. | | LABEL | Para añadir metadatos a la imagen. |
Now we have the detail on how to build our first dockerfile we can create a working directory and create our dockerfile. I have created a working directory within this repository where you can see the files and folders I have to walk through. [Containers](Containers) Con estos detalles ya podemos crear un directorio de trabajo para construir el primer dockerfile. En este repositorio puedes encontrar el directorio de trabajo con los archivos y carpetas que veremos: [Containers](Containers)
In this directory, I am going to create a .dockerignore file similar to the .gitignore we used in the last section. This file will list any files that would otherwise be created during the Docker build process, which you want to exclude from the final build. En este directorio tendré el archivo `.dockerignore` que es similar al `.gitignore`, ¿Lo recuerdas?. Este archivo enumerará todos los archivos que se desean excluir en el proceso de construcción de Docker, para evitarlos en la construcción final.
Remember everything about containers is about being compact, as fast as possible with no bloat. Recuerda, en la creación de los contenedores es importante ser compacto, tan rápido como sea posible sin bloat (código hinchado).
Así que haremos un Dockerfile muy simple con el siguiente diseño:
I want to create a very simple Dockerfile with the below layout also can be found in the folder linked above.
``` ```
# Use the official Ubuntu 18.04 as base # Use the official Ubuntu 18.04 as base
@ -71,33 +72,33 @@ RUN apt-get install -y nginx curl
RUN rm -rf /var/lib/apt/lists/* RUN rm -rf /var/lib/apt/lists/*
``` ```
Navigate to this directory in your terminal, and then run `docker build -t 90daysofdevops:0.1 .` we are using the `-t` and then setting an image name and tag. Es importante que le fichero se llame `Dockerfile` para que docker lo pueda reconocer. Cuando lo tengas ejecuta `docker build -t 90daysofdevops:0.1 .`. Fíjate que usamos el punto para que busque el Dockerfile en el directorio donde estamos ubicados. Con el anterior comando estamos usando la `-t` y luego estableciendo un nombre de imagen y una etiqueta.
![](Images/Day45_Containers3.png) ![](Images/Day45_Containers3.png)
Now we have created our image we can then go and run our image using Docker Desktop or we could use the docker command line. I have used Docker Desktop I have fired up a container and you can see that we have `curl` available to us in the cli of the container. Ahora que hemos creado nuestra imagen podemos ir y ejecutar nuestra imagen utilizando Docker Desktop o podríamos utilizar la línea de comandos docker. He utilizado Docker Desktop, he lanzado un contenedor y puedes ver que tenemos `curl` disponible para nosotros en el cli del contenedor.
![](Images/Day45_Containers4.png) ![](Images/Day45_Containers4.png)
Whilst in Docker Desktop there is also the ability to leverage the UI to do some more tasks with this new image. Mientras que en Docker Desktop también existe la posibilidad de aprovechar la interfaz de usuario para hacer algunas tareas más con esta nueva imagen.
![](Images/Day45_Containers5.png) ![](Images/Day45_Containers5.png)
We can inspect our image, in doing so you see very much of the dockerfile and the lines of code that we wanted to run within our container. Podemos inspeccionar nuestra imagen, al hacerlo se ve gran parte del dockerfile y las líneas de código que queríamos ejecutar dentro de nuestro contenedor.
![](Images/Day45_Containers6.png) ![](Images/Day45_Containers6.png)
We have a pull option, now this would fail for us because this image is not hosted anywhere so we would get that as an error. However, we do have a Push to hub which would enable us to push our image to DockerHub. Tenemos una opción pull, ahora esto fallaría porque la imagen no está alojada en ningún lugar por lo que obtendríamos un error. Sin embargo, tenemos una opción Push al hub que nos permitiría enviar nuestra imagen a nuestro registro DockerHub.
If you are using the same `docker build` we ran earlier then this would not work either, you would need the build command to be `docker build -t {{username}}/{{imagename}}:{{version}}` Si estás usando el mismo `docker build` que ejecutamos antes, esto tampoco funcionaría, necesitarías que el comando de compilación fuera `docker build -t {{username}}/{{imagename}}:{{version}}`.
![](Images/Day45_Containers7.png) ![](Images/Day45_Containers7.png)
Then if we go and take a look in our DockerHub repository you can see that we just pushed a new image. Now in Docker Desktop, we would be able to use that pull tab. A continuación, si echamos un vistazo a nuestro repositorio DockerHub se puede ver que acabamos de subir una nueva imagen. Ahora en Docker Desktop, seríamos capaces de utilizar la pestaña pull.
![](Images/Day45_Containers8.png) ![](Images/Day45_Containers8.png)
## Resources ## Recursos
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE) - [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI) - [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
@ -105,5 +106,10 @@ Then if we go and take a look in our DockerHub repository you can see that we ju
- [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc) - [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc)
- [Blog on gettng started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/) - [Blog on gettng started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/)
- [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
See you on [Day 46](day46.md) Nos vemos en el [Día 46](day46.md)

View File

@ -1,42 +1,40 @@
## Docker Compose ## Docker Compose
The ability to run one container could be great if you have a self-contained image that has everything you need for your single use case, where things get interesting is when you are looking to build multiple applications between different container images. For example, if I had a website front end but required a backend database I could put everything in one container but better and more efficient would be to have its container for the database. La capacidad de ejecutar un contenedor puede ser muy grande si tienes una imagen auto-contenida que tiene todo lo que necesita para su caso de uso único. Donde las cosas se ponen interesantes es cuando estás buscando construir múltiples aplicaciones entre diferentes imágenes de contenedores. Por ejemplo, si tuvieras un sitio web front-end, pero requiere una base de datos back-end podría poner todo en un contenedor, aunque lo más eficiente es tener un contenedor propio para la base de datos.
This is where Docker compose comes in which is a tool that allows you to run more complex apps over multiple containers. With the benefit of being able to use a single file and command to spin up your application. The example I am going to the walkthrough in this post is from the [Docker QuickStart sample apps (Quickstart: Compose and WordPress)](https://docs.docker.com/samples/wordpress/). Aquí es donde entra en juego Docker compose, una herramienta que permite ejecutar aplicaciones más complejas en varios contenedores. Con el beneficio de ser capaz de utilizar un único archivo y comando para hacer girar su aplicación. El ejemplo que voy a mostrar en este día es de [Docker QuickStart sample apps (Quickstart: Compose and WordPress)](https://docs.docker.com/samples/wordpress/).
In this first example we are going to: Veremos cómo:
- Use Docker compose to bring up WordPress and a separate MySQL instance. - Usar Docker Compose para traer WordPress y una instancia separada de MySQL.
- Use a YAML file which will be called `docker-compose.yml` - Utilizar un archivo YAML que se llamará `docker-compose.yml`.
- Build the project - Construir el proyecto
- Configure WordPress via a Browser - Configurar WordPress a través de un navegador
- Shutdown and Clean up - Apagar y limpiar
### Install Docker Compose ### Instalar Docker Compose
As mentioned Docker Compose is a tool, If you are on macOS or Windows then compose is included in your Docker Desktop installation. However, you might be wanting to run your containers on a Windows server host or Linux server and in which case you can install using these instructions [Install Docker Compose](https://docs.docker.com/compose/install/) Como se ha mencionado Docker Compose es una herramienta, si estás en macOS o Windows entonces compose está incluido en tu instalación de Docker Desktop, así como en las últimas versiones de docker para linux. Sin embargo, es posible que desees ejecutar tus contenedores con una versión de docker más antigua, en cuyo caso puedes instalarlo siguiendo estas instrucciones [Install Docker Compose](https://docs.docker.com/compose/install/)
To confirm we have `docker-compose` installed on our system we can open a terminal and simply type the above command. Para confirmar que tenemos `docker-compose` instalado en nuestro sistema podemos abrir un terminal y simplemente escribir el comando anterior. En la últimas versiones se está dejando de usar el guión medio: `docker compose`.
![](Images/Day46_Containers1.png) ![](Images/Day46_Containers1.png)
### Docker-Compose.yml (YAML) ### Docker-Compose.yml (YAML)
The next thing to talk about is the docker-compose.yml which you can find in the container folder of the repository. But more importantly, we need to discuss YAML, in general, a little. Lo siguiente de lo que hablar es de como construir el fichero docker-compose.yml, pero realmente es más importante de que hablemos un poco de YAML, en general.
YAML could almost have its session as you are going to find it in so many different places. But for the most part YAML casi podría tener su propio día en #90DaysOfDevOps, ya que lo vas a encontrar en muchos lugares diferentes. Pero en general "YAML es un lenguaje de serialización de datos amigable para todos los lenguajes de programación", al igual que JSON o TOML.
"YAML is a human-friendly data serialization language for all programming languages." Se utiliza habitualmente para archivos de configuración y en algunas aplicaciones en las que se almacenan o transmiten datos. Sin duda te habrás encontrado con archivos XML que suelen ofrecer ese mismo archivo de configuración. YAML proporciona una sintaxis mínima pero está orientado a esos mismos casos de uso.
It is commonly used for configuration files and in some applications where data is being stored or transmitted. You have no doubt come across XML files that tend to offer that same configuration file. YAML provides a minimal syntax but is aimed at those same use cases. YAML no es un lenguaje de marcas, como se ha mencionado es un lenguaje de serialización y ha ido ganando popularidad en los últimos años. Las capacidades de serialización de objetos lo convierten en un sustituto viable de lenguajes como JSON.
YAML Ain't Markup Language (YAML) is a serialisation language that has steadily increased in popularity over the last few years. The object serialisation abilities make it a viable replacement for languages like JSON. El acrónimo YAML era la abreviatura de Yet Another Markup Language. Pero los mantenedores lo renombraron a YAML Ain't Markup Language para poner más énfasis en sus características orientadas a los datos.
The YAML acronym was shorthand for Yet Another Markup Language. But the maintainers renamed it to YAML Ain't Markup Language to place more emphasis on its data-oriented features. De todos modos, volvamos al archivo docker-compose.yml. Este es un archivo de configuración de lo que queremos hacer cuando se trata de múltiples contenedores que se despliegan en nuestro único sistema.
Anyway, back to the docker-compose.yml file. This is a configuration file of what we want to do when it comes to multiple containers being deployed on our single system. Directamente desde el tutorial vinculado anteriormente se puede ver el contenido del archivo se parece a esto:
Straight from the tutorial linked above you can see the contents of the file looks like this:
``` ```
version: "3.9" version: "3.9"
@ -72,95 +70,93 @@ volumes:
wordpress_data: {} wordpress_data: {}
``` ```
We declare a version and then a large part of this docker-compose.yml file is made up of our services, we have a DB service and a WordPress service. You can see each of those has an image defined with a version tag associated. We are now also introducing state into our configuration unlike our first walkthroughs, but now we are going to create volumes so we can store our databases there. Declaramos una versión y luego una gran parte de este archivo docker-compose.yml se compone de nuestros servicios, tenemos un servicio DB y un servicio de WordPress. Puedes ver que cada uno de ellos tiene una imagen definida con una etiqueta de versión asociada. Ahora también estamos introduciendo el estado en nuestra configuración a diferencia de nuestros primeros paseos, pero ahora vamos a crear volúmenes para que podamos almacenar nuestras bases de datos allí.
We then have some environmental variables such as passwords and usernames. These files can get very complicated but the YAML configuration file simplifies what these look like overall. Luego tenemos algunas variables de entorno como contraseñas y nombres de usuario. Estos archivos pueden llegar a ser muy complicados, pero el archivo de configuración YAML simplifica su aspecto general.
### Build the project ### Construir el proyecto
Next up we can head back into our terminal and we can use some commands with our docker-compose tool. Navigate to your directory, where your docker-compose.yml file is located. A continuación podemos volver a nuestro terminal y podemos utilizar algunos comandos con nuestra herramienta docker-compose. Asegurate de estar ubicado en el directorio donde se encuentra el archivo docker-compose.yml.
From the terminal, we can simply run `docker-compose up -d` this will start the process of pulling those images and standing up your multi-container application. Desde el terminal, podemos simplemente ejecutar `docker-compose up -d` esto iniciará el proceso de extracción de las imágenes y la puesta en marcha de su aplicación multi-contenedor.
The `-d` in this command means detached mode, which means that the Run command is or will be in the background. La `-d` en este comando significa modo separado, lo que significa que el comando Run estará en segundo plano.
![](Images/Day46_Containers2.png) ![](Images/Day46_Containers2.png)
If we now run the `docker ps` command, you can see we have 2 containers running, one being WordPress and the other being MySQL. Si ahora ejecutamos el comando `docker ps`, podemos ver que tenemos 2 contenedores ejecutándose, uno es WordPress y el otro es MySQL.
![](Images/Day46_Containers3.png) ![](Images/Day46_Containers3.png)
Next, we can validate that we have WordPress up and running by opening a browser and going to `http://localhost:8000` and you should see the WordPress set-up page. A continuación, podemos verificar que tenemos WordPress funcionando abriendo un navegador y yendo a `http://localhost:8000`. Deberías ver la página de configuración de WordPress.
![](Images/Day46_Containers4.png) ![](Images/Day46_Containers4.png)
We can run through the setup of WordPress, and then we can start building our website as we see fit in the console below. Podemos ejecutar la configuración de WordPress, y luego podemos empezar a construir nuestro sitio web como mejor nos parezca en la consola de abajo.
![](Images/Day46_Containers5.png) ![](Images/Day46_Containers5.png)
If we then open a new tab and navigate to that same address we did before `http://localhost:8000` we will now see a simple default theme with our site title "90DaysOfDevOps" and then a sample post. Si a continuación abrimos una nueva pestaña y navegamos a la misma dirección que antes `http://localhost:8000` veremos ahora un sencillo tema por defecto con el título de nuestro sitio "90DaysOfDevOps" y a continuación un post de ejemplo.
![](Images/Day46_Containers6.png) ![](Images/Day46_Containers6.png)
Before we make any changes, open Docker Desktop and navigate to the volumes tab and here you will see two volumes associated with our containers, one for WordPress and one for DB. Antes de hacer ningún cambio, abre Docker Desktop y navega hasta la pestaña de volúmenes y aquí verás dos volúmenes asociados a nuestros contenedores, uno para WordPress y otro para DB.
![](Images/Day46_Containers7.png) ![](Images/Day46_Containers7.png)
My Current wordpress theme is "Twenty Twenty-Two" and I want to change this to "Twenty Twenty" Back in the dashboard we can make those changes. Mi tema actual de wordpress es "Twenty Twenty-Two" y quiero cambiarlo por "Twenty Twenty". De vuelta en el dashboard podemos hacer esos cambios.
![](Images/Day46_Containers8.png) ![](Images/Day46_Containers8.png)
I am also going to add a new post to my site, and here below you see the latest version of our new site. También voy a añadir un nuevo post a mi sitio, y aquí abajo se ve la última versión de nuestro nuevo sitio.
![](Images/Day46_Containers9.png) ![](Images/Day46_Containers9.png)
### Clean Up or not ### Limpiar o no limpiar
If we were now to use the command `docker-compose down` this would bring down our containers. But will leave our volumes in place. Si ahora usáramos el comando `docker-compose down` esto bajaría nuestros contenedores. Pero dejará nuestros volúmenes en su sitio.
![](Images/Day46_Containers10.png) ![](Images/Day46_Containers10.png)
We can just confirm in Docker Desktop that our volumes are still there though. Podemos confirmar en Docker Desktop que nuestros volúmenes siguen ahí.
![](Images/Day46_Containers11.png) ![](Images/Day46_Containers11.png)
If we then want to bring things back up then we can issue the `docker up -d` command from within the same directory and we have our application back up and running. Si luego queremos volver a poner las cosas en marcha, podemos ejecutar el comando `docker up -d` desde el mismo directorio y ya tenemos nuestra aplicación de nuevo en marcha.
![](Images/Day46_Containers12.png) ![](Images/Day46_Containers12.png)
We then navigate in our browser to that same address of `http://localhost:8000` and notice that our new post and our theme change are all still in place. A continuación, navegamos en nuestro navegador a la misma dirección de `http://localhost:8000` y observamos que nuestro nuevo post y nuestro cambio de tema siguen en su lugar.
![](Images/Day46_Containers13.png) ![](Images/Day46_Containers13.png)
If we want to get rid of the containers and those volumes then issuing the `docker-compose down --volumes` will also destroy the volumes. Si queremos deshacernos de los contenedores y de esos volúmenes, al ejecutar `docker-compose down --volumes` también destruiremos los volúmenes.
![](Images/Day46_Containers14.png) ![](Images/Day46_Containers14.png)
Now when we use `docker-compose up -d` again we will be starting, however, the images will still be local on our system so you won't need to re-pull them from the DockerHub repository. Ahora cuando usemos `docker-compose up -d` de nuevo estaremos arrancando, sin embargo, las imágenes seguirán siendo locales en nuestro sistema por lo que no será necesario volver a extraerlas del repositorio de DockerHub.
I know that when I started diving into docker-compose and its capabilities I was then confused as to where this sits alongside or with Container Orchestration tools such as Kubernetes, well everything we have done here in this short demo is focused on one host we have WordPress and DB running on the local desktop machine. We don't have multiple virtual machines or multiple physical machines, we also can't easily scale up and down the requirements of our application. Sé que cuando empecé a bucear en docker-compose y sus capacidades estaba confundido en cuanto las diferencias con otras herramientas de orquestación de contenedores como Kubernetes. Por ahora lo que hemos hecho en esta breve demostración se centra en un host que tenemos WordPress y DB se ejecuta en la máquina de escritorio local. No tenemos múltiples máquinas virtuales o múltiples máquinas físicas, tampoco podemos escalar fácilmente hacia arriba y hacia abajo los requisitos de nuestra aplicación.
Our next section is going to cover Kubernetes but we have a few more days of Containers in general first. En la sección de Kubernetes despejaremos algunas dudas, por ahora tenemos algunos días más de Contenedores en general.
This is also a great resource for samples of docker-compose applications with multiple integrations. [Awesome-Compose](https://github.com/docker/awesome-compose) Este es también un gran recurso para muestras de aplicaciones docker-compose con múltiples integraciones. [Awesome-Compose](https://github.com/docker/awesome-compose)
In the above repository, there is a great example which will deploy an Elasticsearch, Logstash, and Kibana (ELK) in single-node. En el repositorio hay un gran ejemplo que desplegará un Elasticsearch, Logstash, y Kibana (ELK) en single-node. Podrás encontrar los ficheros en la carpeta [Containers](2022/Days/Containers/elasticsearch-logstash-kibana/). Si tienes esta carpeta en local, tan solo navega hasta allí y usa `docker-compose up -d`.
I have uploaded the files to the [Containers folder](2022/Days/Containers/elasticsearch-logstash-kibana/) When you have this folder locally, navigate there and you can simply use `docker-compose up -d`
![](Images/Day46_Containers15.png) ![](Images/Day46_Containers15.png)
We can then check we have those running containers with `docker ps` Podrás comprobar que tenemos esos contenedores en ejecución con `docker ps`. Estos mantendrán el mismo entorno que en mi pc.
![](Images/Day46_Containers16.png) ![](Images/Day46_Containers16.png)
Now we can open a browser for each of the containers: Ahora podemos abrir un navegador para cada uno de los contenedores:
![](Images/Day46_Containers17.png) ![](Images/Day46_Containers17.png)
To remove everything we can use the `docker-compose down` command. Como en la anterior práctica, para eliminar todo podemos usar el comando `docker-compose down`.
## Resources ## Recursos
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE) - [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI) - [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
@ -169,5 +165,11 @@ To remove everything we can use the `docker-compose down` command.
- [Blog on getting started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/) - [Blog on getting started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/)
- [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started) - [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started)
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
- [Comparando TOML, JSON y YAML](https://vergaracarmona.es/comparando-toml-json-y-yaml/)
See you on [Day 47](day47.md) Nos vemos en el [Día 47](day47.md)

View File

@ -1,92 +1,92 @@
## Docker Networking & Security ## Docker Networking & Security
During this container session so far we have made things happen but we have not looked at how things have worked behind the scenes either from a networking point of view also we have not touched on security, that is the plan for this session. Hasta ahora hemos visto como desplegar contenedores, pero no sabemos aún cómo funcionan las redes y cuál es la seguridad mínima que necesitan. Cómo bien anuncia el título, este es el plan de hoy.
### Docker Networking Basics ### Docker Networking Basics
Open a terminal, and type the command `docker network` this is the main command for configuring and managing container networks. Vamos al grano, abre un terminal y escribe el comando `docker network`. Este es el comando principal para configurar y gestionar redes de los contenedores.
From the below, you can see this is how we can use the command, and all of the sub-commands available. We can create new networks, list existing ones, and inspect and remove networks. Puedes ver como podemos usar el comando y todos los sub-comandos disponibles. Podemos crear nuevas redes, listar las existentes, inspeccionarlas y eliminarlas.
![](Images/Day47_Containers1.png) ![](Images/Day47_Containers1.png)
Let's take a look at the existing networks we have since our installation, so the out-of-box Docker networking looks like using the `docker network list` command. Vamos a echar un vistazo a las redes existentes que tenemos desde nuestra instalación usando el comando `docker network list`.
Each network gets a unique ID and NAME. Each network is also associated with a single driver. Notice that the "bridge" network and the "host" network have the same name as their respective drivers. Cada red tiene un ID y un NOMBRE únicos. Cada red también está asociada a un único controlador. Observa que la red "bridge" y la red "host" tienen el mismo nombre que sus respectivos controladores.
![](Images/Day47_Containers2.png) ![](Images/Day47_Containers2.png)
Next, we can take a deeper look into our networks with the `docker network inspect` command. A continuación, podemos echar un vistazo más profundo a nuestras redes con el comando `docker network inspect`.
With me running `docker network inspect bridge` I can get all the configuration details of that specific network name. This includes name, ID, drivers, connected containers and as you can see quite a lot more. Si ejecuto `docker network inspect bridge` puedo obtener todos los detalles de configuración de ese nombre de red específico. Esto incluye nombre, ID, controladores, contenedores conectados y mucho más como puedes ver.
![](Images/Day47_Containers3.png) ![](Images/Day47_Containers3.png)
### Docker: Bridge Networking ### Docker: Bridge Networking
As you have seen above a standard installation of Docker Desktop gives us a pre-built network called `bridge` If you look back up to the `docker network list` command, you will see that the network called bridge is associated with the `bridge` driver. Just because they have the same name doesn't they are the same thing. Connected but not the same thing. Como has visto arriba una instalación estándar de Docker Desktop nos da una red pre-construida llamada `bridge` Si vuelves a mirar el comando `docker network list`, verás que la red llamada bridge está asociada con el driver `bridge`. Que tengan el mismo nombre no quiere decir que sean la misma cosa. Están conectadas pero no son lo mismo.
The output above also shows that the bridge network is scoped locally. This means that the network only exists on this Docker host. This is true of all networks using the bridge driver - the bridge driver provides single-host networking. La salida anterior también muestra que la red bridge tiene un ámbito local. Esto significa que la red sólo existe en este host Docker. Esto es cierto para todas las redes que utilizan el controlador bridge que proporciona la red de un solo host.
All networks created with the bridge driver are based on a Linux bridge (a.k.a. a virtual switch). Todas las redes creadas con el controlador bridge se basan en un bridge Linux (también conocido como conmutador virtual).
### Connect a Container ### Conectar un Contenedor
By default the bridge network is assigned to new containers, meaning unless you specify a network all containers will be connected to the bridge network. Por defecto la red bridge es asignada a los nuevos contenedores, lo que significa que a menos que especifiques una red todos los contenedores serán conectados a la red bridge.
Let's create a new container with the command `docker run -dt ubuntu sleep infinity` Vamos a crear un nuevo contenedor con el comando `docker run -dt ubuntu sleep infinity`.
The sleep command above is just going to keep the container running in the background so we can mess around with it. El comando sleep de arriba sólo va a mantener el contenedor funcionando en segundo plano para que podamos trastear con él.
![](Images/Day47_Containers4.png) ![](Images/Day47_Containers4.png)
If we then check our bridge network with `docker network inspect bridge` you will see that we have a container matching what we have just deployed because we did not specify a network. Si a continuación comprobamos nuestra red bridge con `docker network inspect bridge` veremos que tenemos un contenedor que coincide con lo que acabamos de desplegar porque no hemos especificado ninguna red.
![](Images/Day47_Containers5.png) ![](Images/Day47_Containers5.png)
We can also dive into the container using `docker exec -it 3a99af449ca2 bash` you will have to use `docker ps` to get your container ID. También podemos bucear en el contenedor usando `docker exec -it 3a99af449ca2 bash`, tendrás que usar `docker ps` para obtener el ID del contenedor que has creado.
From here our image doesn't have anything to ping so we need to run the following command.`apt-get update && apt-get install -y iputils-ping` then ping an external interfacing address. `ping -c5 www.90daysofdevops.com` En principio, nuestra imagen no tiene nada con lo que hacer ping, así que tenemos que ejecutar el siguiente comando: `apt-get update && apt-get install -y iputils-ping`. Luego vamos a hacer ping a una dirección de interfaz externa, a ver que pasa: `ping -c5 www.90daysofdevops.com`
![](Images/Day47_Containers6.png) ![](Images/Day47_Containers6.png)
To clear this up we can run `docker stop 3a99af449ca2` again and use `docker ps` to find your container ID but this will remove our container. Ahora podemos parar el contenedor con `docker stop 3a99af449ca2` y utilizar `docker ps` para buscar su ID de contenedor, veremops que esto eliminará nuestro contenedor.
### Configure NAT for external connectivity ### Configurar NAT para conectividad externa
In this step, we'll start a new NGINX container and map port 8080 on the Docker host to port 80 inside of the container. This means that traffic that hits the Docker host on port 8080 will be passed on to port 80 inside the container. En este paso, iniciaremos un nuevo contenedor NGINX y asignaremos el puerto 8080 en el host Docker al puerto 80 dentro del contenedor. Esto significa que el tráfico que llega al host Docker en el puerto 8080 pasará al puerto 80 dentro del contenedor.
Start a new container based on the official NGINX image by running `docker run --name web1 -d -p 8080:80 nginx` Inicie un nuevo contenedor basado en la imagen oficial de NGINX ejecutando `docker run --name web1 -d -p 8080:80 nginx`.
![](Images/Day47_Containers7.png) ![](Images/Day47_Containers7.png)
Review the container status and port mappings by running `docker ps` Revise el estado del contenedor y las asignaciones de puertos ejecutando `docker ps`.
![](Images/Day47_Containers8.png) ![](Images/Day47_Containers8.png)
The top line shows the new web1 container running NGINX. Take note of the command the container is running as well as the port mapping - `0.0.0.0:8080->80/tcp` maps port 8080 on all host interfaces to port 80 inside the web1 container. This port mapping is what effectively makes the container's web service accessible from external sources (via the Docker hosts IP address on port 8080). La línea superior muestra el nuevo contenedor web1 ejecutando NGINX. Fíjate en el output del contenedor en la asignación de puertos - `0.0.0.0:8080->80/tcp`. Asigna el puerto 8080 en todas las interfaces del host al puerto 80 dentro del contenedor web1. Esta asignación de puertos es lo que hace que el servicio web del contenedor sea accesible desde fuentes externas (a través de la dirección IP de los hosts Docker en el puerto 8080).
Now we need our IP address for our actual host, we can do this by going into our WSL terminal and using the `IP addr` command. Ahora necesitamos nuestra dirección IP para nuestro host anfitrión, podemos hacer esto yendo a nuestro terminal WSL y utilizando el comando `ip addr`.
![](Images/Day47_Containers9.png) ![](Images/Day47_Containers9.png)
Then we can take this IP and open a browser and head to `http://172.25.218.154:8080/` Your IP might be different. This confirms that NGINX is accessible. Entonces podemos tomar esta IP y abrir un navegador y dirigirnos a `http://172.25.218.154:8080/` (Ten en cuenta que tiene que se tu IP, seguramente sea diferente). Esto confirma que NGINX es accesible.
![](Images/Day47_Containers10.png) ![](Images/Day47_Containers10.png)
I have taken these instructions from this site from way back in 2017 DockerCon but they are still relevant today. However, the rest of the walkthrough goes into Docker Swarm and I am not going to be looking into that here. [Docker Networking - DockerCon 2017](https://github.com/docker/labs/tree/master/dockercon-us-2017/docker-networking) Estas instrucciones se han sacado de "Docker Networking - DockerCon 2017". Aun siendo de la DockerCon 2017 sigue estando vigente a día de hoy. En ese tutorial siguen explicando otros conceptos de redes incluyyendo Docker Swarm, pero no lo veremos aquí. No obstante, aquí tenéis el enlace por si queréis echarle un vistazo: [Docker Networking - DockerCon 2017](https://github.com/docker/labs/tree/master/dockercon-us-2017/docker-networking)
### Securing your containers ### Asegurando tus contenedores
Containers provide a secure environment for your workloads vs a full server configuration. They offer the ability to break up your applications into much smaller, loosely coupled components each isolated from one another which helps reduce the attack surface overall. Los contenedores proporcionan un entorno seguro para las cargas de trabajo frente a una configuración de servidor completa. Ofrecen la capacidad de dividir aplicaciones en componentes mucho más pequeños y poco acoplados, cada uno aislado del otro, lo que ayuda a reducir la superficie de ataque en general.
But they are not immune from hackers that are looking to exploit systems. We still need to understand the security pitfalls of the technology and maintain best practices. Pero no son inmunes a los hackers que buscan explotar los sistemas. Todavía tenemos que entender las trampas de seguridad de la tecnología y mantener las mejores prácticas.
### Move away from root permission ### Alejarse del permiso de root
All of the containers we have deployed have been using the root permission to the process within your containers. This means they have full administrative access to your container and host environments. Now to walk through we knew these systems were not going to be up and running for long. But you saw how easy it was to get up and running. Todos los contenedores que hemos desplegado han estado utilizando el permiso root al proceso dentro de sus contenedores. Esto significa que tienen pleno acceso administrativo a su contenedor y entornos de acogida. Ahora a recorrer sabíamos que estos sistemas no iban a estar en funcionamiento por mucho tiempo. Pero ya has visto lo fácil que es ponerlo en marcha.
We can add a few steps to our process to enable non-root users to be our preferred best practice. When creating our dockerfile we can create user accounts. You can find this example also in the containers folder in the repository. Podemos añadir algunos pasos a nuestro proceso para permitir que los usuarios no root sean quienes administren el contenedor, siguiendo así una buena práctica de seguridad. Al crear nuestro dockerfile podemos crear cuentas de usuario. Puedes encontrar este ejemplo también en la carpeta [containers](containers) del repositorio.
``` ```
# Use the official Ubuntu 18.04 as base # Use the official Ubuntu 18.04 as base
@ -96,27 +96,27 @@ RUN groupadd -g 1000 basicuser && useradd -r -u 1000 -g basicuser basicuser
USER basicuser USER basicuser
``` ```
We can also use `docker run --user 1009 ubuntu` the Docker run command overrides any user specified in your Dockerfile. Therefore, in the following example, your container will always run with the least privilege—provided user identifier 1009 also has the lowest permission level. También podemos usar `docker run --user 1009 ubuntu` el comando Docker run anula cualquier usuario especificado en tu Dockerfile. Por lo tanto, en el siguiente ejemplo, su contenedor siempre se ejecutará con el identificador de usuario 1009 con menos privilegios, con un nivel de permisos más bajo.
However, this method doesnt address the underlying security flaw of the image itself. Therefore its better to specify a non-root user in your Dockerfile so your containers always run securely. Sin embargo, este método no aborda el fallo de seguridad subyacente de la propia imagen. Por lo tanto, es mejor especificar un usuario no root en tu Dockerfile para que tus contenedores siempre se ejecuten de forma segura.
### Private Registry ### Registro Privado
Another area we have used heavily in public registries in DockerHub, with a private registry of container images set up by your organisation means that you can host where you wish or there are managed services for this as well, but all in all, this gives you complete control of the images available for you and your team. Hasta ahora hemos utilizado registros públicos en DockerHub. Con un registro privado de imágenes de contenedores establecido por la organización podremos evitar problemas de curiosos. Se puede alojar la imágen donde desees, existen registros OpenSources y también administrados por terceros. Esto da un control completo de las imágenes disponibles para el equipo de trabajo.
DockerHub is great to give you a baseline, but it's only going to be providing you with a basic service where you have to put a lot of trust into the image publisher. DockerHub está muy bien para darte una base, pero sólo te va a proporcionar un servicio básico en el que tienes que confiar mucho en el editor de imágenes.
### Lean & Clean ### Liviano y limpio
Have mentioned this throughout, although not related to security. But the size of your container can also affect security in terms of attack surface if you have resources you do not use in your application then you do not need them in your container. He mencionado esto en todo momento sin relacionarlo con la seguridad. Pero el tamaño del contenedor puede afectar a la seguridad en términos de superficie de ataque. Si tienes recursos que no usas en tu aplicación entonces no los necesitas en tu contenedor, los puedes eliminar.
This is also my major concern with pulling the `latest` images because that can bring a lot of bloat to your images as well. DockerHub does show the compressed size for each of the images in a repository. Esta es mi mayor preocupación con la extracción de las imágenes `latest` porque eso puede traer un montón de bloat (hinchazón) a sus imágenes. DockerHub muestra el tamaño comprimido para cada una de las imágenes en un repositorio.
Checking `docker image` is a great command to see the size of your images. En definitiva, busca siempre de que tus imágenes sean lo más pequeñas posibles. `docker image` es el comando para comprobar el tamaño de las imágenes en local.
![](Images/Day47_Containers11.png) ![](Images/Day47_Containers11.png)
## Resources ## Recursos
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE) - [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI) - [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
@ -125,5 +125,10 @@ Checking `docker image` is a great command to see the size of your images.
- [Blog on getting started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/) - [Blog on getting started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/)
- [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started) - [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started)
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
See you on [Day 48](day48.md) Nos vemos en el [Día 48](day48.md)

View File

@ -1,96 +1,94 @@
## Alternatives to Docker ## Alternativas a Docker
I did say at the very beginning of this section that we were going to be using Docker, simply because resource wise there is so much and the community is very big, but also this was really where the indents to making containers popular came from. I would encourage you to go and watch some of the history around Docker and how it came to be, I found it very useful. Dije al principio de esta sección que íbamos a usar Docker, simplemente porque tiene muchos recursos ya que la comunidad es muy grande, pero también porque fue de aquí de donde vinieron los impulsos para popularizar los contenedores. Te animo a que veas algo de la [historia de los contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/), me pareció muy útil para entender todos los conceptos que trae.
But as I have alluded to there are other alternatives to Docker. If we think about what Docker is and what we have covered. It is a platform for developing, testing, deploying, and managing applications. Pero como he aludido existen alternativas a Docker si pensamos en lo que es Docker y de qué se ocupa: una plataforma para desarrollar, probar, desplegar y gestionar aplicaciones.
I want to highlight a few alternatives to Docker that you might or will in the future see out in the wild. Quiero destacar algunas alternativas a Docker que podrías ver o verás en el futuro.
### Podman ### Podman
What is Podman? Podman is a daemon-less container engine for developing, managing, and running OCI Containers on your Linux System. Containers can either be run as root or in rootless mode. ¿Qué es Podman? [Podman](https://podman.io/) es un motor de contenedores sin demonio para desarrollar, gestionar y ejecutar contenedores OCI en tu sistema Linux. Los contenedores se pueden ejecutar como root o en modo rootless.
I am going to be looking at this from a Windows point of view but know that like Docker there is no requirement for virtualisation there as it will use the underlying OS which is cannot do in the Windows world. Al igual que Docker no hay ningún requisito para la virtualización, pero utilizará el sistema operativo subyacente y por eso no se puede ejecutar en Windows a pelo. Se puede ejecutar bajo WSL2 pero no es tan visual como la experiencia con Docker Desktop, que está hecho para quienes usan el ratón.
Podman can be run under WSL2 although not as sleek as the experience with Docker Desktop. There is also a Windows remote client where you can connect to a Linux VM where your containers will run. También hay un cliente remoto de Windows donde se puede conectar a una máquina virtual Linux donde se ejecutarán los contenedores. Con el Ubuntu en WSL2 de la versión 20.04, siguiendo los siguientes pasos podrás instalar Podman en tu instancia WSL.
My Ubuntu on WSL2 is the 20.04 release. Following the next steps will enable you to install Podman on your WSL instance.
```Shell ```Shell
echo "deb https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/xUbuntu_20.04/ /" | echo "deb https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/xUbuntu_20.04/ /" |
sudo tee /etc/apt/sources.list.d/devel:kubic:libcontainers:stable.list sudo tee /etc/apt/sources.list.d/devel:kubic:libcontainers:stable.list
``` ```
Add the GPG Key Para añadir la clave GPG:
```Shell ```Shell
curl -L "https://download.opensuse.org/repositories/devel:/kubic:\ curl -L "https://download.opensuse.org/repositories/devel:/kubic:\
/libcontainers:/stable/xUbuntu_20.04/Release.key" | sudo apt-key add - /libcontainers:/stable/xUbuntu_20.04/Release.key" | sudo apt-key add -
``` ```
Run a system update and upgrade with the `sudo apt-get update && sudo apt-get upgrade` command. Finally, we can install podman using `sudo apt install podman` Ejecute una actualización del sistema con `sudo apt-get update && sudo apt-get upgrade`. Por último, podemos instalar podman usando `sudo apt install podman`. Espero que os déis cuenta de la incomodidad que es usar un sistema operativo que no sea Linux para trabajar con contenedores. Suele pasar con la mayoría de aplicaciones de Sistemas o desarrollo. Así como hemos visto la optimización de los contenedores, deberéis tener en cuenta que el sistema operativo anfitrión también es importante.
We can now use a lot of the same commands we have been using for docker, note that we do not have that nice docker desktop UI. You can see below I used `podman images` and I have nothing after installation then I used `podman pull ubuntu` to pull down the ubuntu container image. Ahora podemos utilizar muchos de los mismos comandos que hemos estado utilizando para docker. Como puedes ver a continuación, he utilizado `podman images` y no tengo nada después de la instalación. Luego, he utilizado `podman pull ubuntu` para bajar la imagen del contenedor ubuntu.
![](Images/Day48_Containers1.png) ![](Images/Day48_Containers1.png)
We can then run our Ubuntu image using `podman run -dit ubuntu` and `podman ps` to see our running image. Podemos ejecutar nuestra imagen de Ubuntu usando `podman run -dit ubuntu` y `podman ps` para ver nuestra imagen en ejecución.
![](Images/Day48_Containers2.png) ![](Images/Day48_Containers2.png)
To then get into that container we can run `podman attach dazzling_darwin` your container name will most likely be different. Para entrar en ese contenedor podemos ejecutar `podman attach dazzling_darwin` el nombre de tu contenedor seguramente será diferente.
![](Images/Day48_Containers3.png) ![](Images/Day48_Containers3.png)
If you are moving from docker to podman it is also common to change your config file to have `alias docker=podman` that way any command you run with docker will use podman. Si te estás moviendo de docker a podman también es común cambiar el archivo de configuración para tener `alias docker=podman` de esa manera cualquier comando que ejecute con docker utilizará podman.
### LXC ### LXC
LXC is a containerisation engine that enables users again to create multiple isolated Linux container environments. Unlike Docker, LXC acts as a hypervisor for creating multiple Linux machines with separate system files, and networking features. Was around before Docker and then made a short comeback due to Docker's shortcomings. LXC es un motor de contenedorización que permite a los usuarios crear múltiples entornos de contenedores Linux aislados. A diferencia de Docker, LXC actúa como un hipervisor para crear múltiples máquinas Linux con archivos de sistema separados, y características de red. Existió antes que Docker y volvió a aparecer debido a las deficiencias de Docker.
LXC is as lightweight though as docker and easily deployed. Sin embargo, LXC es tan ligero como Docker y fácil de desplegar.
### Containerd ### Containerd
A standalone container runtime. Containerd brings simplicity and robustness as well as of course portability. Containerd was formerly a tool that runs as part of Docker container services until Docker decided to graduate its components into standalone components. Un runtime de contenedor independiente. Containerd aporta simplicidad y robustez, así como, por supuesto, portabilidad. Containerd era antes una herramienta que se ejecutaba como parte de los servicios de contenedores Docker hasta que Docker decidió graduar sus componentes en componentes independientes.
A project in the Cloud Native Computing Foundation, placing it in the same class as popular container tools like Kubernetes, Prometheus, and CoreDNS. Es un proyecto de la Cloud Native Computing Foundation, lo que lo sitúa en la misma clase que herramientas de contenedores populares como Kubernetes, Prometheus y CoreDNS. De hecho, a partir de la versión 1.11, Kubernetes utiliza containerd como su runtime de contenedor predeterminado mientras que antes era Docker.
### Other Docker tooling ### Otras herramientas Docker
We could also mention toolings and options around Rancher, and VirtualBox but we can cover them in more detail another time. También podríamos mencionar herramientas y opciones alrededor de Rancher, y VirtualBox pero podemos cubrirlas en más detalle en otra ocasión.
[**Gradle**](https://gradle.org/) [**Gradle**](https://gradle.org/)
- Build scans allow teams to collaboratively debug their scripts and track the history of all builds. - Las exploraciones de construcción permiten a los equipos depurar sus scripts de forma colaborativa y realizar un seguimiento del historial de todas las construcciones.
- Execution options give teams the ability to continuously build so that whenever changes are inputted, the task is automatically executed. - Las opciones de ejecución dan a los equipos la capacidad de construir continuamente de modo que cada vez que se introducen cambios, la tarea se ejecuta automáticamente.
- The custom repository layout gives teams the ability to treat any file directory structure as an artefact repository. - El diseño personalizado del repositorio ofrece a los equipos la posibilidad de tratar cualquier estructura de directorios de archivos como un repositorio de artefactos.
[**Packer**](https://packer.io/) [**Packer**](https://packer.io/)
- Ability to create multiple machine images in parallel to save developer time and increase efficiency. - Posibilidad de crear varias imágenes de máquina en paralelo para ahorrar tiempo a los desarrolladores y aumentar la eficacia.
- Teams can easily debug builds using Packers debugger, which inspects failures and allows teams to try out solutions before restarting builds. - Los equipos pueden depurar fácilmente las compilaciones mediante el depurador de Packer, que inspecciona los fallos y permite a los equipos probar soluciones antes de reiniciar las compilaciones.
- Support with many platforms via plugins so teams can customize their builds. - Compatibilidad con muchas plataformas mediante plugins para que los equipos puedan personalizar sus compilaciones.
[**Logspout**](https://github.com/gliderlabs/logspout) [**Logspout**](https://github.com/gliderlabs/logspout)
- Logging tool - The tools customizability allows teams to ship the same logs to multiple destinations. - Herramienta de registro: la capacidad de personalización de la herramienta permite a los equipos enviar los mismos registros a varios destinos.
- Teams can easily manage their files because the tool only requires access to the Docker socket. - Los equipos pueden gestionar fácilmente sus archivos porque la herramienta sólo requiere acceso al socket Docker.
- Completely open-sourced and easy to deploy. - Completamente de código abierto y fácil de desplegar.
[**Logstash**](https://www.elastic.co/products/logstash) [**Logstash**](https://www.elastic.co/products/logstash)
- Customize your pipeline using Logstashs pluggable framework. - Personaliza tu pipeline utilizando el marco de trabajo pluggable de Logstash.
- Easily parse and transform your data for analysis and to deliver business value. - Analice y transforme fácilmente sus datos para el análisis y para ofrecer valor empresarial.
- Logstashs variety of outputs lets you route your data where you want. - La variedad de salidas de Logstash le permite dirigir sus datos hacia donde desee.
[**Portainer**](https://www.portainer.io/) [**Portainer**](https://www.portainer.io/)
- Utilise pre-made templates or create your own to deploy applications. - Utilice plantillas prediseñadas o cree las suyas propias para desplegar aplicaciones.
- Create teams and assign roles and permissions to team members. - Cree equipos y asigne funciones y permisos a sus miembros.
- Know what is running in each environment using the tools dashboard. - Sepa qué se está ejecutando en cada entorno mediante el panel de control de la herramienta.
## Resources ## Recursos
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE) - [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI) - [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
@ -101,5 +99,10 @@ We could also mention toolings and options around Rancher, and VirtualBox but we
- [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started) - [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started)
- [Podman | Daemonless Docker | Getting Started with Podman](https://www.youtube.com/watch?v=Za2BqzeZjBk) - [Podman | Daemonless Docker | Getting Started with Podman](https://www.youtube.com/watch?v=Za2BqzeZjBk)
- [LXC - Guide to building an LXC Lab](https://www.youtube.com/watch?v=cqOtksmsxfg) - [LXC - Guide to building an LXC Lab](https://www.youtube.com/watch?v=cqOtksmsxfg)
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
See you on [Day 49](day49.md) Nos vemos en el [Día 49](day49.md)

View File

@ -1,224 +1,199 @@
## The Big Picture: Kubernetes ## El panorama: Kubernetes
In the last section we covered Containers, Containers fall short when it comes to scale and orchestration alone. The best we can do is use docker-compose to bring up multiple containers together. When it comes to Kubernetes which is a Container Orchestrator, this gives us the ability to scale up and down in an automated way or based on a load of your applications and services. En la última sección vimos los Contenedores. Los contenedores se quedan cortos cuando se trata de escalar y de orquestación, no pueden por sí solos. Lo mejor que podemos hacer es utilizar docker-compose para reunir varios contenedores. Cuando se trata de Kubernetes, que es un orquestador de contenedores, esto nos da la capacidad de escalar hacia arriba y hacia abajo de manera automatizada o basada en una carga de sus aplicaciones y servicios.
As a platform Kubernetes offers the ability to orchestrate containers according to your requirements and desired state. We are going to cover Kubernetes in this section as it is growing rapidly as the next wave of infrastructure. I would also suggest that from a DevOps perspective Kubernetes is just one platform that you will need to have a basic understanding of, you will also need to understand bare metal, virtualisation and most likely cloud-based services as well. Kubernetes is just another option to run our applications. Como plataforma, Kubernetes ofrece la capacidad de orquestar contenedores de acuerdo a sus necesidades y el estado deseado. Vamos a cubrir Kubernetes en esta sección, ya que está creciendo rápidamente como la próxima ola de infraestructura. También me gustaría sugerir que, desde una perspectiva DevOps, Kubernetes es sólo una plataforma de las que tendrás que tener al menos un conocimiento básico. También tendrá que entender el bare metal, la virtualización y muy probablemente también los servicios basados en cloud. Kubernetes es sólo otra opción para ejecutar nuestras aplicaciones y se puede aplicar en estás dos mencionadas.
### What is Container Orchestration? ### ¿Qué es la orquestación de contenedores?
I have mentioned Kubernetes and I have mentioned Container Orchestration, Kubernetes is the technology whereas container orchestration is the concept or the process behind the technology. Kubernetes is not the only Container Orchestration platform we also have Docker Swarm, HashiCorp Nomad and others. But Kubernetes is going from strength to strength so I want to cover Kubernetes but wanted to say that it is not the only one out there. He mencionado Kubernetes y he mencionado orquestación de contenedores, Kubernetes es la tecnología mientras que la orquestación de contenedores es el concepto o el proceso detrás de esta tecnología. Kubernetes no es la única plataforma de orquestación de contenedores, también tenemos las mencionadas anteriormente docker compose y Docker Swarm, o otras como HashiCorp Nomad. Pero Kubernetes va viento en popa, es la más utilizada, así que nos centraremos en ella.
### What is Kubernetes? ### ¿Qué es Kubernetes?
The first thing you should read if you are new to Kubernetes is the official documentation, My experience of really deep diving into Kubernetes a little over a year ago was that this is going to be a steep learning curve. Coming from a virtualisation and storage background I was thinking about how daunting this felt. Lo primero que debes leer si eres nuevo en Kubernetes es la documentación oficial, es el mejor tutorial para aprender y además la van utilizando con más ejemplos o nuevas implementaciones. Mi experiencia de buceo realmente profundo en Kubernetes fue una curva de aprendizaje empinada. Viniendo de un fondo de virtualización y almacenamiento pensaba en lo desalentador que esto se sentía, pero el camino se hace al andar.
But the community, free learning resources and documentation are amazing. [Kubernetes.io](https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/) La comunidad, los recursos de aprendizaje gratuitos y la documentación son increíbles, no dejes de empaparte en ella: [Kubernetes.io](https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/)
_Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available._ Ahora al pastel. Kubernetes es una plataforma portátil, extensible y de código abierto para gestionar cargas de trabajo y servicios en contenedores. Facilita tanto la configuración declarativa como la automatización. Cuenta con un ecosistema amplio y de rápido crecimiento. Los servicios, el soporte y las herramientas de Kubernetes están ampliamente disponibles.
Important things to note from the above quote, Kubernetes is Open-Source with a rich history that goes back to Google who donated the project to the Cloud Native Computing Foundation (CNCF) and it has now been progressed by the open-source community as well as large enterprise vendors contributing to making Kubernetes what it is today. Cosas importantes a tener en cuenta de la cita anterior, Kubernetes es de código abierto con una rica historia que se remonta a cuando Google donó el proyecto a la Cloud Native Computing Foundation (CNCF). Ahora está siendo desarrollado por la comunidad de código abierto, así como grandes proveedores empresariales que contribuyen a hacer Kubernetes lo que es hoy.
I mentioned above that containers are great and in the previous section, we spoke about how containers and container images have changed and accelerated the adoption of cloud-native systems. But containers alone are not going to give you the production-ready experience you need from your application. Kubernetes gives us the following: Antes he mencionado que los contenedores son geniales y, en la sección anterior, hemos hablado de cómo los contenedores y las imágenes de contenedores han cambiado y acelerado la adopción de sistemas nativos de la nube. Pero los contenedores por sí solos no van a darte la experiencia lista para producción que necesitas de tu aplicación. Kubernetes nos proporciona estas soluciones:
- **Service discovery and load balancing** Kubernetes can expose a container using the DNS name or using their IP address. If traffic to a container is high, Kubernetes can load balance and distribute the network traffic so that the deployment is stable. - **Descubrimiento de servicios y equilibrio de carga** - Kubernetes puede exponer un contenedor utilizando el nombre DNS o su dirección IP. Si el tráfico a un contenedor es alto, Kubernetes puede equilibrar la carga y distribuir el tráfico de red para que el despliegue sea estable.
- **Orquestación de almacenamiento** - Kubernetes permite montar automáticamente un sistema de almacenamiento de su elección, como almacenamiento local, proveedores de nubes públicas, etc.
- **Rollouts y rollbacks automatizados** - Puedes describir el estado deseado para los contenedores desplegados utilizando Kubernetes, y puedes cambiar el estado actual al estado deseado a un ritmo controlado. Por ejemplo, puedes automatizar Kubernetes para crear nuevos contenedores para su despliegue, eliminar los contenedores existentes y adoptar todos sus recursos al nuevo contenedor.
- **Empaquetado automático de contenedores** - Proporcionas a Kubernetes un clúster de nodos que pueda utilizar para ejecutar tareas en contenedores, indicas cuánta CPU y memoria (RAM) necesitas para cada contenedor y Kubernetes puede acomodar los contenedores en sus nodos para hacer el mejor uso de los recursos.
- **Auto-reparación** - Kubernetes reinicia los contenedores que fallan, reemplaza los contenedores, mata los contenedores que no responden a su chequeo de salud definido por el usuario y no los anuncia a los clientes hasta que estén listos para servir.
- **Gestión de secretos y configuración** - Kubernetes permite almacenar y gestionar información confidencial, como contraseñas, tokens OAuth y claves SSH. Puede desplegar y actualizar secretos y la configuración de la aplicación sin reconstruir sus imágenes de contenedor, y sin exponer secretos en la configuración de su pila.
- **Storage orchestration** Kubernetes allows you to automatically mount a storage system of your choice, such as local storage, public cloud providers, and more. Kubernetes proporciona un marco para ejecutar sistemas distribuidos de forma resiliente.
- **Automated rollouts and rollbacks** You can describe the desired state for your deployed containers using Kubernetes, and it can change the actual state to the desired state at a controlled rate. For example, you can automate Kubernetes to create new containers for your deployment, remove existing containers and adopt all their resources to the new container. La orquestación de contenedores gestiona el despliegue, la colocación y el ciclo de vida de los contenedores.
- **Automatic bin packing** You provide Kubernetes with a cluster of nodes that it can use to run containerized tasks. You tell Kubernetes how much CPU and memory (RAM) each container needs. Kubernetes can fit containers onto your nodes to make the best use of your resources. También tiene muchas otras responsabilidades:
- **Self-healing** Kubernetes restarts containers that fail, replaces containers, kills containers that don't respond to your user-defined health check, and doesn't advertise them to clients until they are ready to serve. - La gestión de clústeres federa hosts en un objetivo.
- La gestión de la programación distribuye los contenedores entre los nodos a través del programador.
- El descubrimiento de servicios sabe dónde se encuentran los contenedores y distribuye las solicitudes de los clientes entre ellos.
- La replicación garantiza la disponibilidad del número adecuado de nodos y contenedores para la carga de trabajo solicitada.
- La gestión de la salud detecta y reemplaza los contenedores y nodos no saludables.
- **Secret and configuration management** Kubernetes lets you store and manage sensitive information, such as passwords, OAuth tokens, and SSH keys. You can deploy and update secrets and application configuration without rebuilding your container images, and without exposing secrets in your stack configuration. ### Principales componentes de Kubernetes
Kubernetes provides you with a framework to run distributed systems resiliently. Kubernetes es un orquestador de contenedores para aprovisionar, gestionar y escalar aplicaciones. Puede utilizarlo para gestionar el ciclo de vida de aplicaciones en contenedores en un clúster de nodos, que es una colección de máquinas de trabajo como VMs o máquinas físicas.
Container Orchestration manages the deployment, placement, and lifecycle of containers. Es posible que sus aplicaciones necesiten muchos otros recursos para ejecutarse, como volúmenes, redes y secretos que pueden ayudarle a conectarse a bases de datos, comunicarse con back-ends con firewalls y proteger claves. Con Kubernetes, puede añadir estos recursos a su aplicación. Los recursos de infraestructura que sus aplicaciones necesitan que se gestionen de forma declarativa.
It also has many other responsibilities: El paradigma clave de Kubernetes es su modelo declarativo. Usted proporciona el estado que desea y Kubernetes lo hace posible. Si necesita cinco instancias, no inicie cinco instancias separadas por su cuenta. En su lugar, le dice a Kubernetes que necesita cinco instancias, y Kubernetes reconcilia automáticamente el estado. Si algo sale mal con una de sus instancias y falla, Kubernetes aún conoce el estado que usted desea y crea instancias en un nodo disponible.
- Cluster management federates hosts into one target. ### Nodo
- Schedule management distributes containers across nodes through the scheduler.
- Service discovery knows where containers are located and distributes client requests across them.
- Replication ensures that the right number of nodes and containers are available for the requested workload.
- Health management detects and replaces unhealthy containers and nodes.
### Main Kubernetes Components
Kubernetes is a container orchestrator to provision, manage, and scale apps. You can use it to manage the lifecycle of containerized apps in a cluster of nodes, which is a collection of worker machines such as VMs or physical machines.
Your apps might need many other resources to run, such as volumes, networks, and secrets that can help you connect to databases, talk to firewalled back ends, and secure keys. With Kubernetes, you can add those resources to your app. Infrastructure resources that your apps need are managed declaratively.
The key paradigm of Kubernetes is its declarative model. You provide the state that you want and Kubernetes makes it happen. If you need five instances, you don't start five separate instances on your own. Instead, you tell Kubernetes that you need five instances, and Kubernetes automatically reconciles the state. If something goes wrong with one of your instances and it fails, Kubernetes still knows the state that you want and creates instances on an available node.
### Node
#### Control Plane #### Control Plane
Every Kubernetes cluster requires a Control Plane node, the control plane's components make global decisions about the cluster (for example, scheduling), as well as detecting and responding to cluster events. Cada clúster Kubernetes requiere un nodo de Control Plane, los componentes del Control Plane toman decisiones globales sobre el clúster, por ejemplo la programación, así como la detección y respuesta a los eventos del clúster.
![](Images/Day49_Kubernetes1.png) ![](Images/Day49_Kubernetes1.png)
#### Worker Node #### Worker Node
A worker machine that runs Kubernetes workloads. It can be a physical (bare metal) machine or a virtual machine (VM). Each node can host one or more pods. Kubernetes nodes are managed by a control plane Un Worker machine que ejecuta cargas de trabajo Kubernetes. Puede ser una máquina física (bare metal) o una máquina virtual (VM). Cada nodo puede alojar uno o más pods. Los nodos Kubernetes son gestionados por un plano de control.
![](Images/Day49_Kubernetes2.png) ![](Images/Day49_Kubernetes2.png)
There are other node types but I won't be covering them here. Existen otros tipos de nodos pero no los trataré aquí.
#### kubelet #### kubelet
An agent that runs on each node in the cluster. It makes sure that containers are running in a Pod. Un agente que se ejecuta en cada nodo del clúster. Se asegura de que los contenedores se ejecutan en un Pod.
The kubelet takes a set of PodSpecs that are provided through various mechanisms and ensures that the containers described in those PodSpecs are running and healthy. The kubelet doesn't manage containers which were not created by Kubernetes. El kubelet toma un conjunto de PodSpecs que se proporcionan a través de diversos mecanismos y se asegura de que los contenedores descritos en los PodSpecs se están ejecutando y en buen estado. El kubelet no gestiona contenedores que no hayan sido creados por Kubernetes.
![](Images/Day49_Kubernetes3.png) ![](Images/Day49_Kubernetes3.png)
#### kube-proxy #### kube-proxy
kube-proxy is a network proxy that runs on each node in your cluster, implementing part of the Kubernetes Service concept. kube-proxy es un proxy de red que se ejecuta en cada nodo de su clúster, implementando parte del concepto de Servicio Kubernetes.
kube-proxy maintains network rules on nodes. These network rules allow network communication to your Pods from network sessions inside or outside of your cluster. kube-proxy mantiene reglas de red en los nodos. Estas reglas de red permiten la comunicación de red a sus Pods desde sesiones de red dentro o fuera de su cluster.
kube-proxy uses the operating system packet filtering layer if there is one and it's available. Otherwise, kube-proxy forwards the traffic itself. kube-proxy utiliza la capa de filtrado de paquetes del sistema operativo si existe y está disponible. De lo contrario, kube-proxy reenvía el tráfico por sí mismo.
![](Images/Day49_Kubernetes4.png) ![](Images/Day49_Kubernetes4.png)
#### Container runtime #### Container runtime
The container runtime is the software that is responsible for running containers. El container runtime es el software responsable de ejecutar los contenedores.
Kubernetes supports several container runtimes: Docker, containerd, CRI-O, and any implementation of the Kubernetes CRI (Container Runtime Interface). Kubernetes soporta varios container runtime: Docker, containerd, CRI-O, y cualquier implementación del CRI (Container Runtime Interface) de Kubernetes.
![](Images/Day49_Kubernetes5.png) ![](Images/Day49_Kubernetes5.png)
### Cluster ### Cluster
A cluster is a group of nodes, where a node can be a physical machine or a virtual machine. Each of the nodes will have the container runtime (Docker) and will also be running a kubelet service, which is an agent that takes in the commands from the Master controller (more on that later) and a Proxy, that is used to proxy connections to the Pods from another component (Services, that we will see later). Un cluster es un grupo de nodos, donde un nodo puede ser una máquina física o una máquina virtual. Cada uno de los nodos tendrá el tiempo de ejecución del contenedor (Docker) y también estará ejecutando un servicio kubelet, que es un agente que recibe los comandos del controlador Maestro (veremos más sobre esto más adelante) y un Proxy, que se utiliza para proxy conexiones a los Pods de otro componente (Servicios, que veremos más adelante).
Our control plane which can be made highly available will contain some unique roles compared to the worker nodes, the most important will be the kube API server, this is where any communication will take place to get information or push information to our Kubernetes cluster. Nuestro control plane, que se puede hacer altamente disponible, contendrá algunos roles únicos en comparación con los nodos Workers, el más importante será el servidor API kube, aquí es donde cualquier comunicación se llevará a cabo para obtener información o enviar información a nuestro clúster Kubernetes.
#### Kube API-Server #### Servidor API Kube
The Kubernetes API server validates and configures data for the API objects which include pods, services, replication controllers, and others. The API Server services REST operations and provide the frontend to the cluster's shared state through which all other components interact. El servidor API de Kubernetes valida y configura los datos para los objetos API que incluyen pods, servicios, controladores de replicación y otros. El servidor API da servicio a las operaciones REST y proporciona el frontend al estado compartido del cluster a través del cual interactúan el resto de componentes.
#### Scheduler #### Planificador (Scheduler)
The Kubernetes scheduler is a control plane process which assigns Pods to Nodes. The scheduler determines which Nodes are valid placements for each Pod in the scheduling queue according to constraints and available resources. The scheduler then ranks each valid Node and binds the Pod to a suitable Node. El programador de Kubernetes es un proceso del control plane que asigna Pods a Nodos. El programador determina qué Nodos son válidos para cada Pod en la cola de programación de acuerdo con las restricciones y los recursos disponibles. A continuación, el planificador clasifica cada Nodo válido y vincula el Pod a un Nodo adecuado.
#### Controller Manager #### Gestor de Controladores
The Kubernetes controller manager is a daemon that embeds the core control loops shipped with Kubernetes. In applications of robotics and automation, a control loop is a non-terminating loop that regulates the state of the system. In Kubernetes, a controller is a control loop that watches the shared state of the cluster through the apiserver and makes changes attempting to move the current state towards the desired state. El gestor de controladores de Kubernetes es un demonio que incorpora los bucles de control centrales incluidos en Kubernetes. En aplicaciones de robótica y automatización, un bucle de control es un bucle no terminal que regula el estado del sistema. En Kubernetes, un controlador es un bucle de control que observa el estado compartido del cluster a través del apiserver y realiza cambios intentando mover el estado actual hacia el estado deseado.
#### etcd #### etcd
Consistent and highly-available key value store used as Kubernetes' backing store for all cluster data. Almacén de valores clave consistente y de alta disponibilidad utilizado como almacén de respaldo de Kubernetes para todos los datos del clúster.
![](Images/Day49_Kubernetes6.png) ![](Images/Day49_Kubernetes6.png)
#### kubectl #### kubectl
To manage this from a CLI point of view we have kubectl, kubectl interacts with the API server. Para gestionar esto desde un punto de vista CLI tenemos kubectl, kubectl interactúa con el servidor API.
The Kubernetes command-line tool, kubectl, allows you to run commands against Kubernetes clusters. You can use kubectl to deploy applications, inspect and manage cluster resources, and view logs. La herramienta de línea de comandos de Kubernetes, kubectl, le permite ejecutar comandos contra clústeres Kubernetes. Puede utilizar kubectl para desplegar aplicaciones, inspeccionar y gestionar recursos de clúster y ver registros.
![](Images/Day49_Kubernetes7.png) ![](Images/Day49_Kubernetes7.png)
### Pods ### Pods
A Pod is a group of containers that form a logical application. E.g. If you have a web application that is running a NodeJS container and also a MySQL container, then both these containers will be located in a single Pod. A Pod can also share common data volumes and they also share the same networking namespace. Remember that Pods are ephemeral and they could be brought up and down by the Master Controller. Kubernetes uses a simple but effective means to identify the Pods via the concepts of Labels (name values). Un Pod es un grupo de contenedores que forman una aplicación lógica. Por ejemplo, si tienes una aplicación web que está ejecutando un contenedor NodeJS y también un contenedor MySQL, entonces ambos contenedores pueden estar ubicados en un único Pod, aunque no es lo aconsejable. Un Pod también puede compartir volúmenes de datos comunes y también comparten el mismo espacio de nombres de red. Recuerda que los Pods son efímeros y pueden ser subidos y bajados por el Controlador Maestro. Kubernetes utiliza un medio simple pero eficaz para identificar los Pods a través de los conceptos de Labels (nombre - valor).
- Pods handle Volumes, Secrets, and configuration for containers. Algunas características importantes de los Pods:
- Los Pods son la unidad más pequeña de Kubernetes.
- Pods are ephemeral. They are intended to be restarted automatically when they die. - Los Pods manejan Volúmenes, Secretos y configuración para los contenedores.
- Los Pods son efímeros. Están pensados para reiniciarse automáticamente cuando mueren.
- Pods are replicated when the app is scaled horizontally by the ReplicationSet. Each Pod will run the same container code. - Los Pods se replican cuando la aplicación se escala horizontalmente mediante el ReplicationSet. Cada Pod ejecutará el mismo código de contenedor.
- Los Pods viven en Nodos Workers.
- Pods live on Worker Nodes. - Los Pods pueden comunicarse entre sí usando localhost.
![](Images/Day49_Kubernetes8.png) ![](Images/Day49_Kubernetes8.png)
### Deployments ### Deployments
- You can just decide to run Pods but when they die they die. Puedes decidir ejecutar Pods pero cuando mueren, mueren. Los Deployments son una forma de ejecutar Pods de forma continua. Los Deployments también le permiten actualizar una aplicación en ejecución sin tiempo de inactividad.
- A Deployment will enable your pod to run continuously. - Un Deployment permitirá que tu pod se ejecute continuamente.
- Los Deployments le permiten actualizar una aplicación en ejecución sin tiempo de inactividad.
- Deployments allow you to update a running app without downtime. - Los Deployments también especifican una estrategia para reiniciar Pods cuando mueren.
- Los Deployments son la forma recomendada de administrar Pods en producción.
- Deployments also specify a strategy to restart Pods when they die - Los Deployments son una abstracción de alto nivel que maneja la creación de Pods y ReplicaSets.
- Los Deployments son declarativos, como todo en Kubernetes, esto significa que describe el estado deseado en su clúster y Kubernetes se encarga de cambiar el estado real para que coincida con el estado deseado.
![](Images/Day49_Kubernetes9.png) ![](Images/Day49_Kubernetes9.png)
### ReplicaSets ### ReplicaSets
- The Deployment can also create the ReplicaSet Como se ha comentado, el Deployment también puede crear el ReplicaSet. Un ReplicaSet es un objeto que define un conjunto de Pods idénticos. Un ReplicaSet garantiza que un número especificado de réplicas de un Pod se estén ejecutando en todo momento. Si hay demasiados Pods, el ReplicaSet eliminará los Pods adicionales. Si hay muy pocos Pods, el ReplicaSet creará más. Los ReplicaSets son la forma recomendada de administrar Pods en producción.
- A ReplicaSet ensures your app has the desired number of Pods - Un ReplicaSet asegura que su aplicación tiene el número deseado de Pods
- Los ReplicaSets crearán y escalarán Pods basándose en el Deployment
- ReplicaSets will create and scale Pods based on the Deployment - Los Deployments, ReplicaSets y Pods no son excluyentes, pero pueden ser
- Deployments, ReplicaSets, and Pods are not exclusive but can be
### StatefulSets ### StatefulSets
- Does your App require you to keep information about its state? ¿Necesita tu App mantener información sobre su estado? Por ejemplo, una base de datos necesita estado. Los StatefulSets son la forma de ejecutar aplicaciones que necesitan mantener un estado. Los StatefulSets son similares a los Deployments, pero tienen algunas diferencias importantes:
- A database needs state - Los Pods de un StatefulSet no son intercambiables.
- Cada pod tiene un identificador único y persistente que el controlador mantiene por encima de cualquier reprogramación.
- A StatefulSets Pods are not interchangeable. - Los Pods de un StatefulSet se crean en orden secuencial, uno a la vez.
- Los Pods de un StatefulSet tienen un nombre DNS estable y predecible. Mantienen el mismo nombre a través de las reprogramaciones.
- Each pod has a unique, persistent identifier that the controller maintains over any rescheduling. - Los volúmenes pueden ser persistentes.
![](Images/Day49_Kubernetes10.png) ![](Images/Day49_Kubernetes10.png)
### DaemonSets ### DaemonSets
- DaemonSets are for continuous process - Los DaemonSets son para procesos continuos que se ejecutan en todos los nodos. Un Pod por Nodo.
- Cada nuevo nodo añadido al cluster hace que se inicie un pod.
- They run one Pod per Node. - Útiles para tareas en segundo plano como monitorización y recogida de logs.
- Cada pod tiene un identificador único y persistente que el controlador mantiene por encima de cualquier reprogramación.
- Each new node added to the cluster gets a pod started
- Useful for background tasks such as monitoring and log collection
- Each pod has a unique, persistent identifier that the controller maintains over any rescheduling.
![](Images/Day49_Kubernetes11.png) ![](Images/Day49_Kubernetes11.png)
### Services ### Servicios
- A single endpoint to access Pods Características de los Servicios:
- Un único punto final para acceder a los Pods
- Una forma unificada de dirigir el tráfico a un cluster y eventualmente a una lista de Pods.
- Usando un Servicio, los Pods pueden ser subidos y bajados sin afectar a nada.
- Los Servicios pueden ser expuestos interna o externamente. También pueden ser expuestos en diferentes puertos.
- a unified way to route traffic to a cluster and eventually to a list of Pods. Esto es sólo una visión general rápida y notas sobre los bloques de construcción fundamentales de Kubernetes, podemos tomar este conocimiento y añadir en algunas otras áreas alrededor de almacenamiento y de entrada para mejorar nuestras aplicaciones, pero entonces también tenemos un montón de opciones sobre dónde se ejecuta nuestro clúster Kubernetes. La siguiente sesión se centrará en esas opciones sobre dónde se puede ejecutar un clúster Kubernetes, mientras que también exploraremos algunos detalles sobre el almacenamiento.
- By using a Service, Pods can be brought up and down without affecting anything.
This is just a quick overview and notes around the fundamental building blocks of Kubernetes, we can take this knowledge and add in some other areas around Storage and Ingress to enhance our applications but we then also have a lot of choices on where our Kubernetes cluster runs. The next session will focus on those options on where can I run a Kubernetes cluster, whilst also exploring some specifics around Storage.
![](Images/Day49_Kubernetes12.png) ![](Images/Day49_Kubernetes12.png)
### What we will cover in the series on Kubernetes ## Recursos
- Kubernetes Architecture
- Kubectl Commands
- Kubernetes YAML
- Kubernetes Ingress
- Kubernetes Services
- Helm Package Manager
- Persistent Storage
- Stateful Apps
## Resources
- [Kubernetes Documentation](https://kubernetes.io/docs/home/) - [Kubernetes Documentation](https://kubernetes.io/docs/home/)
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do) - [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4) - [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8) - [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
See you on [Day 50](day50.md) Nos vemos en el [Día 50](day50.md)

View File

@ -1,42 +1,46 @@
## Choosing your Kubernetes platform ## Elegir tu plataforma Kubernetes
I wanted to use this session to break down some of the platforms or maybe distributions is a better term to use here, one thing that has been a challenge in the Kubernetes world is removing complexity. En esta sesión se va a desglosar algunas de las plataformas o tal vez distribuciones es un mejor término a utilizar aquí. Una cosa que ha sido un reto en el mundo Kubernetes es eliminar la complejidad.
Kubernetes the hard way walks through how to build out from nothing to a full-blown functional Kubernetes cluster this is to the extreme but more and more at least the people I am speaking to are wanting to remove that complexity and run a managed Kubernetes cluster. The issue there is that it costs more money but the benefits could be if you use a managed service do you need to know the underpinning node architecture and what is happening from a Control Plane node point of view when generally you do not have access to this. Kubernetes the hard way (el camino difícil) explica cómo construir desde la nada un clúster Kubernetes completamente funcional. Esto es extremo, pero cada vez más, al menos las personas con las que hablo, quieren eliminar esa complejidad y ejecutar un clúster Kubernetes gestionado. El problema es que cuesta más dinero, pero las ventajas podrían ser que, si se utiliza un servicio gestionado, es necesario conocer la arquitectura de los nodos y lo que ocurre desde el punto de vista del control plane, algo a lo que generalmente no se tiene acceso.
Then we have the local development distributions that enable us to use our systems and run a local version of Kubernetes so developers can have the full working environment to run their apps in the platform they are intended for. Luego tenemos las distribuciones de desarrollo local que nos permiten utilizar nuestros sistemas y ejecutar una versión local de Kubernetes para que los desarrolladores puedan tener el entorno de trabajo completo para ejecutar sus aplicaciones en la plataforma para la que están destinadas.
The general basis of all of these concepts is that they are all a flavour of Kubernetes which means we should be able to freely migrate and move our workloads where we need them to suit our requirements. La base general de todos estos conceptos es que todos son una variante de Kubernetes, lo que significa que deberíamos poder migrar y mover libremente nuestras cargas de trabajo donde las necesitemos para adaptarlas a nuestras necesidades.
A lot of our choice will also depend on what investments have been made. I mentioned the developer experience as well but some of those local Kubernetes environments that run our laptops are great for getting to grips with the technology without spending any money. Gran parte de nuestra elección dependerá también de las inversiones realizadas. También he mencionado la experiencia de los desarrolladores, pero algunos de esos entornos locales de Kubernetes que ejecutan nuestros portátiles son estupendos para familiarizarse con la tecnología sin gastar dinero.
### Bare-Metal Clusters ### Clusters Bare-Metal
An option for many could be running your Linux OS straight onto several physical servers to create our cluster, it could also be Windows but I have not heard much about the adoption rate around Windows, Containers and Kubernetes. If you are a business and you have made a CAPEX decision to buy your physical servers then this might be how you go when building out your Kubernetes cluster, the management and admin side here means you are going to have to build yourself and manage everything from the ground up. Una opción para muchos podría ser ejecutar su sistema operativo Linux directamente en varios servidores físicos para crear nuestro clúster, también podría ser Windows pero no he oído hablar mucho de la tasa de adopción en entornos Windows, puede ser anecdótica.
### Virtualisation Si en tu empresa se ha tomado la decisión de CAPEX para comprar sus servidores físicos, entonces esto podría ser una forma en la que construir la arquitectura, un clúster Kubernetes. La gestión y administración de lado significa que la vas a tener que construir tu mismo y gestionarlo todo desde el principio.
Regardless of test and learning environments or enterprise-ready Kubernetes clusters virtualisation is a great way to go, typically the ability to spin up virtual machines to act as your nodes and then cluster those together. You have the underpinning architecture, efficiency and speed of virtualisation as well as leveraging that existing spend. VMware for example offers a great solution for both Virtual Machines and Kubernetes in various flavours. ### Virtualización
My first ever Kubernetes cluster was built based on Virtualisation using Microsoft Hyper-V on an old server that I had which was capable of running a few VMs as my nodes. Independientemente de si se trata de entornos de prueba y aprendizaje o de clústeres Kubernetes listos para la funcionar, la virtualización es una gran opción, ya que permite crear máquinas virtuales que actúan como nodos y, a continuación, agruparlos en clústeres. Dispones de la arquitectura de apoyo, la eficiencia y la velocidad de la virtualización, además de aprovechar el gasto existente. VMware, por ejemplo, ofrece una gran solución tanto para máquinas virtuales como para Kubernetes en varias versiones.
### Local Desktop options Mi primer clúster Kubernetes se construyó sobre la base de la virtualización utilizando Microsoft Hyper-V en un servidor antiguo que tenía que era capaz de ejecutar algunas máquinas virtuales como mis nodos. Esto me permitió construir un clúster Kubernetes y empezar a jugar con él.
There are several options when it comes to running a local Kubernetes cluster on your desktop or laptop. This as previously said gives developers the ability to see what their app will look like without having to have multiple costly or complex clusters. Personally, this has been one that I have used a lot and in particular, I have been using minikube. It has some great functionality and adds-ons which changes the way you get something up and running. ### Opciones de escritorio local
### Kubernetes Managed Services Hay varias opciones cuando se trata de ejecutar un clúster local de Kubernetes en su ordenador de sobremesa o portátil. Esto, como se dijo anteriormente, ofrece a los desarrolladores la posibilidad de ver cómo se verá su aplicación sin tener que tener múltiples clústeres costosos o complejos. Personalmente, he utilizado mucho minikube. Tiene una gran funcionalidad y complementos que cambian la forma de poner algo en marcha.
I have mentioned virtualisation, and this can be achieved with hypervisors locally but we know from previous sections we could also leverage VMs in the public cloud to act as our nodes. What I am talking about here with Kubernetes managed services are the offerings we see from the large hyperscalers but also from MSPs removing layers of management and control away from the end user, this could be removing the control plane from the end user this is what happens with Amazon EKS, Microsoft AKS and Google Kubernetes Engine. (GKE) ### Servicios gestionados Kubernetes
### Overwhelming choice He mencionado la virtualización, y esto se puede lograr con hipervisores a nivel local, pero sabemos por secciones anteriores que también podríamos aprovechar las máquinas virtuales en la nube pública para actuar como nuestros nodos. De lo que estoy hablando aquí con los servicios gestionados Kubernetes son las ofertas que vemos de los grandes hiperescaladores, pero también de los MSP eliminando capas de gestión y control lejos del usuario final, esto podría ser eliminar el plano de control del usuario final, esto es lo que sucede con Amazon EKS, Microsoft AKS y Google Kubernetes Engine. (GKE)
I mean the choice is great but there is a point where things become overwhelming and this is not a depth look into all options within each category listed above. On top of the above, we also have OpenShift which is from Red Hat and this option can be run across the options above in all the major cloud providers and probably today gives the best overall useability to the admins regardless of where clusters are deployed. ### Elección abrumadora
So where do you start from your learning perspective, as I said I started with the virtualisation route but that was because I had access to a physical server which I could use for the purpose, I appreciate and in fact, since then I no longer have this option. Quiero decir que la elección es grande, pero hay un punto en el que las cosas se vuelven abrumadoras y esto no es una mirada en profundidad a todas las opciones dentro de cada categoría enumerada anteriormente.
My actual advice now would be to use Minikube as a first option or Kind (Kubernetes in Docker) but Minikube gives us some additional benefits which almost abstracts the complexity out as we can just use add-ons and get things built out quickly and we can then blow it away when we are finished, we can run multiple clusters, we can run it almost anywhere, cross-platform and hardware agnostic. No podemos olvidar que además de lo anterior también tenemos OpenShift que es de Red Hat. Esta opción se puede ejecutar a través de las opciones anteriores en todos los principales proveedores de nube y, probablemente, hoy en día ofrece la mejor facilidad de uso general para los administradores, independientemente de donde se despliegan los clusters.
I have been through a bit of a journey with my learning around Kubernetes so I am going to leave the platform choice and specifics here to list out the options that I have tried to give me a better understanding of Kubernetes the platform and where it can run. What I might do with the below blog posts is take another look at these update them and bring them more into here vs them being linked to blog posts. Por lo tanto, ¿por dónde empezar desde la perspectiva del aprendizaje? Como he dicho yo empecé por la ruta de la virtualización, pero eso fue porque tenía acceso a un servidor físico que podía utilizar para este fin, lo agradezco muchísimo.
Mi consejo actual sería utilizar Minikube como primera opción o Kind (Kubernetes en Docker), pero Minikube nos da algunos beneficios adicionales que casi abstrae la complejidad, ya que sólo podemos utilizar complementos y hacer las cosas rápidamente y luego podemos volarlo cuando hayamos terminado, podemos ejecutar múltiples clusters, podemos ejecutarlo casi en cualquier lugar, multiplataforma y agnóstico de hardware.
He estado a través de un poco de un viaje con mi aprendizaje en torno a Kubernetes así que voy a dejar la elección de la plataforma y los detalles aquí para enumerar las opciones que he probado para darme una mejor comprensión de Kubernetes la plataforma y donde se puede ejecutar. Lo que podría hacer con las siguientes entradas de blog es echar otro vistazo a estos actualizarlos y traerlos más aquí frente a ellos están vinculados a las entradas del blog.
- [Kubernetes playground How to choose your platform](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-1) - [Kubernetes playground How to choose your platform](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-1)
- [Kubernetes playground Setting up your cluster](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-2) - [Kubernetes playground Setting up your cluster](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-2)
@ -48,22 +52,11 @@ I have been through a bit of a journey with my learning around Kubernetes so I a
- [Getting started with CIVO Cloud](https://vzilla.co.uk/vzilla-blog/getting-started-with-civo-cloud) - [Getting started with CIVO Cloud](https://vzilla.co.uk/vzilla-blog/getting-started-with-civo-cloud)
- [Minikube - Kubernetes Demo Environment For Everyone](https://vzilla.co.uk/vzilla-blog/project_pace-kasten-k10-demo-environment-for-everyone) - [Minikube - Kubernetes Demo Environment For Everyone](https://vzilla.co.uk/vzilla-blog/project_pace-kasten-k10-demo-environment-for-everyone)
### What we will cover in the series on Kubernetes ## Recursos
- Kubernetes Architecture
- Kubectl Commands
- Kubernetes YAML
- Kubernetes Ingress
- Kubernetes Services
- Helm Package Manager
- Persistent Storage
- Stateful Apps
## Resources
- [Kubernetes Documentation](https://kubernetes.io/docs/home/) - [Kubernetes Documentation](https://kubernetes.io/docs/home/)
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do) - [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4) - [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8) - [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
See you on [Day 51](day51.md) Nos vemos en el [Día 51](day51.md)