Del CrashLoopBackOff a Hello World: Desplegando Flask en GKE

Despliegue de una app Flask en GKE que saluda y admite nombres para saludos personalizados; Docker, Artifact Registry y buenas prácticas de despliegue.

18 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Resumen del proyecto: desplegar una aplicación Python Flask que saluda a los usuarios usando Kubernetes en Google Kubernetes Engine GKE. Tech stack: Flask, Docker, Kubernetes, Google Kubernetes Engine. Objetivo: poner en producción una app simple que responda Hello mi nombre es Gerald y permita enviar un nombre para que la app responda con un saludo personalizado.

Acerca de Q2BSTUDIO: Q2BSTUDIO es una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida. Ofrecemos soluciones de inteligencia artificial, ciberseguridad, servicios cloud AWS y Azure, servicios inteligencia de negocio, ia para empresas, agentes IA y power bi. Diseñamos aplicaciones empresariales, integraciones seguras y consultoría para acelerar la transformación digital.

Paso 1 Aplicación Flask Resumen: la app define una ruta raiz que devuelve Hello, mi nombre es Gerald. What is your name y un endpoint POST para recibir el campo name desde un formulario y devolver Hello seguido del nombre. En modo producción la app debe ejecutarse en 0.0.0.0 y puerto 80 para que Kubernetes pueda enrutar el tráfico correctamente.

Paso 2 Dockerizar la app Dockerfile esencial: FROM python:3.12-slim WORKDIR /app COPY requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 80 CMD python app.py

Comandos para construir y subir imagen al Artifact Registry: docker build -t africa-south1-docker.pkg.dev/k8s-project-468723/my-docker-repo/my-python-app:v1 . docker push africa-south1-docker.pkg.dev/k8s-project-468723/my-docker-repo/my-python-app:v1

Paso 3 Despliegue en Kubernetes Despliegue básico: crear un Deployment con replicas 2 que use la imagen almacenada en Artifact Registry y que exponga el puerto 80 del contenedor. Aplicar el manifiesto con kubectl apply -f deployment.yaml y crear un Service tipo LoadBalancer con kubectl expose deployment my-python-app --type=LoadBalancer --port 80 --target-port 80

Depuración CrashLoopBackOff Primer síntoma: los pods entraban en estado CrashLoopBackOff al levantar. Comprobación rápida: kubectl get pods -l app=my-python-app y revisar logs con kubectl logs nombre-del-pod Para este caso el log indicaba que no se encontraba el archivo app.py en /app y además la aplicación estaba corriendo en el puerto 5000 mientras el Service esperaba respuestas en el puerto 80.

Correcciones aplicadas 1 Renombrar archivo o ajustar CMD Si el archivo principal se llamaba gerald.py la solución fue renombrarlo a app.py o cambiar la instrucción CMD en Dockerfile para arrancar el archivo correcto. 2 Alinear puertos Cambiar Flask para escuchar en el puerto 80 o ajustar la exposición del contenedor. En este proyecto se optó por ejecutar Flask en el puerto 80 y mantener EXPOSE 80 en el Dockerfile.

Resultado final Tras corregir el nombre del fichero y el puerto la aplicación respondió correctamente. Abrir la IP externa del LoadBalancer en el navegador mostraba el saludo Hello, mi nombre es Gerald. What is your name y el endpoint POST /greet respondía Hello seguido del nombre enviado desde el formulario.

Lecciones aprendidas Coincidir puerto del contenedor y targetPort del Service es crítico. Revisar logs de pods con kubectl logs es la forma más rápida de identificar errores como archivos ausentes o excepciones. Mantener coherencia entre nombres de archivos en el repositorio y comandos de arranque en Dockerfile evita errores de CrashLoopBackOff. Probar localmente antes de subir a Kubernetes permite iterar más rápido y reducir ciclos de depuración en la nube.

Buenas prácticas adicionales Para proyectos empresariales y para servicios cloud AWS y Azure recomendamos integrar pipelines CI CD que verifiquen la imagen antes de desplegar, aplicar políticas de seguridad y escaneo de vulnerabilidades para ciberseguridad, y monitorizar con herramientas de observabilidad. Integrar soluciones de inteligencia artificial e inteligencia de negocio permite añadir valor a las aplicaciones a medida; por ejemplo agentes IA para atención automatizada y paneles con power bi para análisis.

Recursos y enlace al código completo El proyecto completo está disponible en GitHub en la siguiente URL https://github.com/gerald475/simple-python-app

Invitación Si alguna vez has luchado contra CrashLoopBackOff comparte tu experiencia en los comentarios y ayuda a la comunidad a depurar más rápido.

Sobre Q2BSTUDIO Q2BSTUDIO desarrolla software a medida, aplicaciones a medida y soluciones de inteligencia artificial para empresas. Somos especialistas en ciberseguridad, servicios cloud AWS y Azure, servicios inteligencia de negocio, ia para empresas, agentes IA y power bi. Contacta con Q2BSTUDIO para acelerar tus proyectos con software de calidad, seguridad incorporada y capacidades de inteligencia artificial.

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.