El auge del contenedor ha sido un cambio de juego para todos nosotros, no solo en el lado del servidor donde prácticamente cualquier nueva carga de trabajo que implementamos se despliega en forma de contenedor, sino también en nuestros entornos locales ocurre el mismo cambio.
Adoptamos contenedores para gestionar fácilmente las diferentes dependencias que necesitamos manejar como desarrolladores. Incluso si la tarea en cuestión no estaba relacionada con contenedores. ¿Necesitas una base de datos en funcionamiento? Usas una versión en contenedor de ella. ¿Necesitas un sistema de mensajería para probar algunas de tus aplicaciones? Inicias rápidamente un contenedor que proporciona esa funcionalidad.
Y tan pronto como no los necesitas, se eliminan, y tu sistema sigue tan limpio como estaba antes de comenzar esta tarea. Pero siempre hay cosas que necesitamos manejar incluso cuando tenemos una solución maravillosa frente a nosotros, y en el caso de un entorno Docker local, el uso del disco es uno de los más críticos.
Este proceso de lanzar cosas nuevas una y otra vez y luego deshacernos de ellas es cierto en cierto modo porque todas estas imágenes que hemos necesitado y todos estos contenedores que hemos lanzado todavía están allí en nuestro sistema esperando una nueva ronda y durante ese tiempo usando nuestros recursos de disco como puedes ver en una imagen actual de mi entorno Docker local con más de 60 GB utilizados para ese propósito.
Imagen de la página de configuración del panel de control de Docker que muestra la cantidad de disco que Docker está usando.
Lo primero que necesitamos hacer es verificar qué está usando esta cantidad de espacio para ver si podemos liberar algunos de ellos. Para hacer eso, podemos aprovechar el comando docker system df que la CLI de Docker nos proporciona:
La salida de la ejecución del comando docker system df
Como puedes ver, los 61 GB que están en uso son 20.88 GB por las imágenes que tengo en uso, 21.03 MB solo para los contenedores que he definido, 1.25 GB para los volúmenes locales y 21.07 para la caché de construcción. Como solo tengo activos 18 de las 26 imágenes definidas, puedo reclamar hasta 9.3 GB, que es una cantidad importante.
Si quisiéramos obtener más detalles sobre estos datos, siempre podemos usar la opción verbose como un añadido al comando, como puedes ver en la imagen a continuación:
Salida detallada y detallada del comando docker system df -v
Entonces, después de obtener toda esta información, podemos proceder y ejecutar una limpieza de tu sistema. Esta actividad eliminará cualquier contenedor e imagen no utilizados que tengas en tu sistema, y para ejecutar eso, solo necesitas escribir esto:
docker system prune -af
Tiene varias opciones para ajustar un poco la ejecución que puedes consultar en la página oficial de Docker :
En mi caso, eso me ayudó a recuperar hasta 40.8 GB de mi sistema, como puedes ver en la imagen a continuación.
Pero si quisieras avanzar un paso más, también puedes ajustar algunas propiedades para considerar dónde estás ejecutando esta limpieza. Por ejemplo, el defaultKeepStorage te ayudará a definir cuánto disco quieres usar para este sistema de caché de construcción para optimizar la cantidad de uso de red que haces al construir imágenes con capas comunes.
Para hacer eso, necesitas tener el siguiente fragmento en tu sección de configuración del motor de Docker, como se muestra en la imagen a continuación:
Configuración del motor de Docker con el defaultKeepStorage hasta 20GB
Espero que todo este proceso de mantenimiento ayude a que tus entornos locales brillen nuevamente y aproveches al máximo sin necesidad de desperdiciar muchos recursos en el proceso.
The rise of the container has been a game-changer for all of us, not only at the server-side where pretty much any new workload that we deploy is deployed in a container form but also in our local environments happens same change.
We embrace containers to easily manage the different dependencies that we need to handle as developers. Even if the task at hand was not a container-related thing. Do you need a Database up & running? You use a containerized version of it. Do you need a Messaging System to test some of your applications? You quickly start a container providing that functionality.
And as soon as you don’t need them, those are killed, and your system is still as clean as it was before starting this task. But there are always things that we need to handle even when we have a wonderful solution in front of us, and in the case of a local docker environment, Disk Usage is one of the most critical ones.
This process of launching new things over and over and then we get rid of them is true in some way because all these images that we have needed and all these containers we have launched are still there in our system waiting for a new round and during that time using our disk resources as you can see in a current picture of my local Docker environment with more than 60 GB used for that purpose.
Docker dashboard settings page image showing the amount of disk Docker is using.
The first thing we need to do is to check what is using this amount of space to see if we can release some of them. To do that, we can leverage on the docker system df command the docker CLI provides to us:
The output of the execution of the docker system df command
As you can see, the 61 GB that is in use are 20.88 GB per the images that I have in use, 21.03 MB just for the containers that I have defined, 1.25 GB for the local volumes 21.07 for the build cache. As I only have active 18 of the 26 images defined I can reclaim up to 9.3 GB that is an important amount.
If we would like to get more details about this data, we can always use the verbose option as an append to the command, as you can see in the picture below:
Detailed verbose output of the docker system df -v command
So, after getting all this information, we can go ahead and execute a prune of your system. This activity will get rid of any unused container and image that you have in your system, and to execute that, you only need to type this:
docker system prune -af
It has several options to turn a little bit the execution that you can check on the Docker Oficial web page :
In my case, that help me to recover up to 40.8 GB of my system, as you can see in the picture below.
But if you would like to move one step ahead, you can also tune some properties to consider where you are executing this prune. For example, the defaultKeepStorage will help you define how much disk you want to use for this build-cache system to optimize the amount of network usage you do when building images with common layers.
To do that, you need to have the following snippet in your Docker Engine configuration section, as shown in the image below:
Docker Engine configuration with the defaultKeepStorage up to 20GB
I hope that all this housekeeping process will help your location environments to shine again and get the most of it without needing to waste a lot of resources in the process