Define lo que quieres: Docker ligero

Optimiza imágenes Docker para CLIP en CPU en GKE: usa PyTorch CPU wheels, builds multi-stage, base slim y limpieza de caches para reducir de 7GB a ~1GB.

16 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Al construir una imagen Docker con multi stage para alojar el modelo CLIP de OpenAI en GKE me encontré con el problema clásico de la imagen demasiado grande. Inicialmente el requirement instalaba torch y torchvision con soporte por defecto para CUDA y GPUs, lo que infló la imagen hasta alrededor de 7GB cuando en realidad el modelo iba a ejecutarse en CPU.

La solución más rápida y efectiva fue forzar la instalación de las ruedas CPU only de PyTorch. En el requirements bastó indicar explicitamente las versiones CPU y el índice de ruedas CPU como por ejemplo torch==2.2.0+cpu torchvision==0.17.0+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html ftfy regex tqdm fastapi uvicorn pillow numpy<2 python-multipart. Con esto la imagen descendió drásticamente de ~7GB a ~1GB.

Además de usar las ruedas CPU, estas buenas prácticas ayudan a obtener una imagen mucho más ligera y mantenible: usar una imagen base slim como python:3.11-slim, emplear multi stage builds para separar fases de compilación y runtime, instalar paquetes con pip --no-cache-dir, fijar versiones, y limpiar caches y archivos temporales. También conviene eliminar archivos innecesarios de site-packages como directorios tests y examples que fácilmente ahorran 50MB a 60MB adicionales.

Un flujo recomendado sin mostrar un Dockerfile completo es: 1) usar una etapa builder donde se instalen las dependencias necesarias y se compile solo lo imprescindible, 2) copiar al stage final únicamente la carpeta de la aplicación y los paquetes instalados necesarios, 3) limpiar caches pip y borrar __pycache__, tests y ejemplos, y 4) exponer el servicio con uvicorn en modo asíncrono para optimizar recursos. El resultado típico para un servicio que sirve CLIP en CPU puede ser alrededor de 1GB o menos si se aplica limpieza agresiva.

Si tu proyecto requiere despliegue en la nube considera además optimizar la imagen según el proveedor y usar soluciones gestionadas para escalabilidad y seguridad. En Q2BSTUDIO ofrecemos servicios de despliegue y consultoría en nube para optimizar costes y rendimiento, incluidos servicios cloud AWS y Azure y arquitecturas adecuadas para modelos de inteligencia artificial. Con experiencia en desarrollo de software a medida y aplicaciones a medida podemos ayudarte a preparar una imagen Docker ligera y segura y a integrar la solución con pipelines CI/CD.

Q2BSTUDIO es una empresa de desarrollo de software que crea aplicaciones a medida, soluciones de inteligencia artificial y servicios de ciberseguridad. Somos especialistas en ia para empresas, agentes IA, servicios inteligencia de negocio y Power BI, además de ofrecer pentesting y controles de seguridad avanzados. Si necesitas asesoría para desplegar modelos o construir software a medida visita nuestra página de IA para empresas y soluciones de inteligencia artificial y consulta también nuestros servicios cloud AWS y Azure para despliegues gestionados y seguros.

Palabras clave relevantes para este artículo y para tu posicionamiento: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA y power bi.

Si quieres que revisemos tu Dockerfile o armemos una imagen optimizada para GKE y modelos CPU, en Q2BSTUDIO podemos auditar tu build, proponer un Dockerfile multi stage y aplicar las limpiezas necesarias para minimizar la imagen sin sacrificar estabilidad ni seguridad.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat