Despliegue de FastAPI en Digital Ocean con Nginx y CI/CD

Guía detallada para desplegar FastAPI en Digital Ocean con Nginx, systemd y CI/CD con GitHub Actions, optimizando DevOps, seguridad y despliegues automáticos.

16 sept 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Despliegue de FastAPI en Digital Ocean con Nginx y CI/CD explicado paso a paso por Q2BSTUDIO, empresa de desarrollo de software y aplicaciones a medida especializada en inteligencia artificial, ciberseguridad y servicios cloud AWS y Azure.

Introducción y objetivos: este artículo guía desde la creación de un Droplet en Digital Ocean hasta la configuración de Nginx como reverse proxy, ejecución de FastAPI en segundo plano con systemd y automatización del despliegue con GitHub Actions. Es ideal para equipos que buscan implantar aplicaciones a medida y beneficiarse de prácticas de DevOps y seguridad.

Requisitos previos: una cuenta en Digital Ocean, una aplicación FastAPI en un repositorio GitHub y conocimientos básicos de línea de comandos y SSH. Si necesitas desarrollo de aplicaciones a medida o una solución personalizada visita nuestras soluciones de software a medida.

Parte 1 Creación del Droplet: en el panel de Digital Ocean crear un Droplet con Ubuntu 22.04 o 24.04 LTS. Elegir un plan acorde, región cercana y preferir autenticación por clave SSH en lugar de contraseña por seguridad. Tras crear el Droplet anotar la IP pública y acceder con ssh root@tu_droplet_ip.

Parte 2 Preparación del servidor: crear un usuario no root para desplegar la aplicación es buena práctica. Ejemplo de comandos: adduser deployer usermod -aG sudo deployer y copiar las claves SSH del root al nuevo usuario: rsync --archive --chown=deployer:deployer ~/.ssh /home/deployer luego desconectar y entrar como deployer ssh deployer@tu_droplet_ip. Actualizar el sistema con sudo apt update && sudo apt upgrade -y.

Instalación de dependencias: instalar Python y pip con sudo apt install python3-pip -y luego instalar pipenv con pip3 install pipenv. Instalar Nginx con sudo apt install nginx -y y configurar el firewall UFW permitiendo OpenSSH y Nginx Full: sudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' sudo ufw enable.

Parte 3 Configurar Nginx como reverse proxy: crear un archivo en /etc/nginx/sites-available por ejemplo fastapi_app con una configuración que redirija el tráfico al puerto donde corre FastAPI. Un ejemplo del bloque server en formato texto es: server { listen 80; server_name tu_droplet_ip_o_dominio; location / { proxy_pass https://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Habilitar la configuración con sudo ln -s /etc/nginx/sites-available/fastapi_app /etc/nginx/sites-enabled/fastapi_app comprobar sintaxis con sudo nginx -t y reiniciar nginx sudo systemctl restart nginx.

Parte 4 Despliegue manual de la app: clonar el repositorio en el servidor git clone https://github.com/tu_usuario/tu_repo.git /home/deployer/app cambiar al directorio cd /home/deployer/app instalar dependencias con pipenv pipenv install y probar ejecutando la app con Uvicorn pipenv run uvicorn main:app --host 0.0.0.0 --port 8000. Acceder desde el navegador a https://tu_droplet_ip para verificar que Nginx y FastAPI funcionan correctamente.

Parte 5 Ejecutar la app como servicio systemd: crear un servicio para ejecutar la aplicación en segundo plano, arrancar al iniciar y facilitar reinicios. Crear el archivo /etc/systemd/system/fastapi.service con contenido similar a: [Unit] Description=FastAPI Application After=network.target [Service] User=deployer Group=www-data WorkingDirectory=/home/deployer/app Environment=PATH=/home/deployer/.local/bin ExecStart=/usr/local/bin/pipenv run uvicorn main:app --host 0.0.0.0 --port 8000 [Install] WantedBy=multi-user.target Luego recargar demonio y habilitar servicio sudo systemctl daemon-reload sudo systemctl enable fastapi.service sudo systemctl start fastapi.service y comprobar estado con sudo systemctl status fastapi.service.

Parte 6 Automatizar despliegues con GitHub Actions CI CD: crear dos secretos en el repositorio GitHub desde Settings Secrets Actions: HOST con la IP del Droplet y SSH_PRIVATE_KEY con el contenido de la clave privada que coincide con la pública instalada en el servidor. Crear el workflow en .github/workflows/deploy.yml que, al hacer push a main, haga checkout del código y utilice una acción SSH para conectar al Droplet, hacer git pull, instalar dependencias con pipenv y reiniciar el servicio systemd. La acción appleboy/ssh-action permite ejecutar los comandos remotos y con ello lograr despliegues automáticos seguros.

Resumen del flujo CI CD: al hacer push a la rama main la Action SSH se conectará al servidor, actualizará el código, instalará nuevas dependencias y ejecutará sudo systemctl restart fastapi.service para aplicar los cambios sin intervención manual.

Buenas prácticas y seguridad: usar claves SSH, mantener el sistema y dependencias actualizadas, configurar certificados TLS con LetsEncrypt y certbot para servir sobre HTTPS, limitar accesos con firewall y revisar logs. Si necesitas auditoría o pruebas de seguridad profesionales revisa nuestros servicios de ciberseguridad y pentesting en Q2BSTUDIO ciberseguridad y pentesting.

Por qué elegir Q2BSTUDIO: ofrecemos desarrollo de software a medida, aplicaciones a medida, integración de inteligencia artificial para empresas, agentes IA, servicios cloud AWS y Azure, soluciones de inteligencia de negocio y Power BI. Combinamos experiencia en DevOps, seguridad y arquitectura cloud para desplegar aplicaciones FastAPI escalables y seguras. Para soluciones cloud revisa también nuestros servicios cloud AWS y Azure.

Palabras clave integradas: 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 te ayudemos a desplegar tu aplicación FastAPI o a diseñar un pipeline CI CD profesional contacta con Q2BSTUDIO y te acompañamos desde la arquitectura hasta la puesta en producción.

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