Desplegar React en Ubuntu en AWS Cloud (Semana 1)

Guía práctica y paso a paso para desplegar una app React SPA en una instancia Ubuntu EC2 con Nginx. Aprende a construir, servir archivos estáticos y asegurar el enrutado SPA.

24 ago 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Descripción general alto nivel: Guía práctica y orientada a la acción para desplegar una aplicación React SPA en una instancia Ubuntu EC2 usando Nginx. Repetible y pensada para principiantes.

Resumen corto: Objetivo hospedar una aplicación React como archivos estáticos generados por npm run build en una instancia Ubuntu EC2 pública, servirlos con Nginx y asegurar el enrutado de la SPA hacia index.html.

Por qué existe esta guía: Esta guía nace de una experiencia real al encontrar la página por defecto de Nginx en producción. Aquí tienes un playbook con comandos reales y pasos claros para que no te pille desprevenido a medianoche.

Requisitos previos: Cuenta activa en AWS (Free Tier sirve), una app React local o en GitHub, par de claves EC2 pem, conocimientos básicos de SSH y terminal.

Paso 1 Lanzar instancia Ubuntu EC2: Elegir Ubuntu Server 22.04 LTS, tipo t2.micro o t3.micro si buscas Free Tier, crear y descargar par de claves demo-react-key.pem y guardarlo con seguridad.

Paso 2 Grupo de seguridad y par de claves: Añadir reglas de entrada SSH TCP 22 restringida a tu IP preferentemente como /32 o como /24 si estás en un rango NAT pequeño, y HTTP TCP 80 abierto a 0.0.0.0 0. Mantener SSH cerrado al mundo es una buena práctica de ciberseguridad.

Paso 3 Conexión SSH: En tu máquina local ajustar permisos de la llave y conectarte a la instancia

chmod 400 demo-react-key.pem ssh -i demo-react-key.pem ubuntu@EC2_PUBLIC_IP

Paso 4 Instalar Node npm git y Nginx en el servidor

sudo apt update sudo apt install -y nodejs npm git nginx node -v && npm -v

Paso 5 Iniciar y verificar Nginx

sudo systemctl start nginx sudo systemctl enable nginx systemctl status nginx Visita https://EC2_PUBLIC_IP para ver la página por defecto de Nginx.

Paso 6 Clonar el repositorio React en la instancia

git clone https://github.com/USUARIO/REPO.git cd REPO

Paso 7 Pequeño cambio de UI para comprobar flujo: editar src/App.js, cambiar un texto y confirmar que el flujo de desarrollo funciona.

Paso 8 Instalar dependencias y construir archivos de producción

npm install npm run build Resultado esperado directorio build con index.html y carpetas estáticas.

Paso 9 Copiar build a la raíz de Nginx

Importante confirmar que estás en la raíz del proyecto y no dentro de src. Comandos recomendados sudo rm -rf /var/www/html/* sudo cp -r build/* /var/www/html/ sudo chown -R www-data:www-data /var/www/html sudo chmod -R 755 /var/www/html Comprueba ls build y confirma que aparece index.html antes de copiar.

Paso 10 Editar la configuración de Nginx y validar: El archivo activo está en /etc/nginx/sites-available/default. Edita manualmente y añade un bloque de ubicación que permita la reescritura para SPA y evita reemplazos automáticos sin verificación.

Ejemplo de bloque server a insertar o adaptar en /etc/nginx/sites-available/default

server { listen 80; server_name _; root /var/www/html; index index.html; location / { try_files $uri /index.html; } error_page 404 /index.html; }

Validar y reiniciar Nginx solo tras comprobar sintaxis

sudo nginx -t sudo systemctl restart nginx sudo systemctl status nginx

Paso 11 Lista rápida de resolución de problemas: Si no ves sitio verificar Security Group puerto 80, si Nginx no está activo ejecutar sudo systemctl status nginx, si hay errores de configuración ejecutar sudo nginx -t, para app en blanco revisar consola del navegador y ls /var/www/html, revisar logs con sudo tail -n 100 /var/log/nginx/error.log.

Bloque de comandos completo para copiar y pegar en el orden indicado

chmod 400 demo-react-key.pem ssh -i demo-react-key.pem ubuntu@EC2_PUBLIC_IP sudo apt update sudo apt install -y nodejs npm git nginx sudo systemctl start nginx sudo systemctl enable nginx git clone https://github.com/USUARIO/REPO.git cd REPO npm install npm run build pwd sudo rm -rf /var/www/html/* sudo cp -r build/* /var/www/html/ sudo chown -R www-data:www-data /var/www/html sudo chmod -R 755 /var/www/html sudo nano /etc/nginx/sites-available/default validar con sudo nginx -t y reiniciar sudo systemctl restart nginx

Próximos pasos para producción: reservar una Elastic IP para que la IP pública no cambie, añadir HTTPS con Certbot Lets Encrypt, automatizar build y deploy con GitHub Actions o scripts deploy.sh, y considerar contenerizar con Docker para portabilidad y escalado.

Sobre Q2BSTUDIO: Q2BSTUDIO es una empresa de desarrollo de software que ofrece aplicaciones a medida y software a medida para clientes que necesitan soluciones personalizadas. Somos especialistas en inteligencia artificial IA para empresas, agentes IA, ciberseguridad y servicios cloud AWS y Azure. También brindamos servicios de inteligencia de negocio e implementaciones Power BI para convertir datos en decisiones. Nuestro enfoque combina buenas prácticas de DevOps, seguridad y soluciones escalables para proyectos web y móviles.

Palabras clave y servicios: aplicaciones a medida software a medida inteligencia artificial ciberseguridad servicios cloud aws servicios cloud azure servicios inteligencia de negocio ia para empresas agentes ia power bi Estas palabras clave están integradas para mejorar el posicionamiento y reflejan la oferta de Q2BSTUDIO en desarrollo, seguridad y analítica.

Si necesitas que Q2BSTUDIO despliegue tu aplicación React en AWS o Azure o que diseñemos una solución de software a medida con integración de IA y ciberseguridad, contacta con nuestro equipo para una consultoría y presupuesto.'

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