Dockerfile - Node con TypeScript

Dockerfile para optimizar el uso de Node con TypeScript. Aprende cómo mejorar el rendimiento de tus aplicaciones con esta configuración especializada.

21 dic 2025 • 3 min read • Q2BSTUDIO Team

Dockerfile - Node with TypeScript Optimization

Buenos días espero que estéis bien y listos para optimizar imágenes Docker en proyectos Node con TypeScript. Comparto una estructura de Dockerfile multi stage que me permitió reducir una imagen inicial de alrededor de 1GB hasta aproximadamente 161MB en una aplicación sencilla creada con Hono aunque el tamaño final depende de tu código y dependencias.

Ejemplo sintetizado de Dockerfile en dos fases: FROM node:lts-alpine AS builder; WORKDIR /usr/src/app; COPY --chown=node:node package*.json tsconfig.json ./; COPY --chown=node:node /src ./src; RUN npm ci --silent; RUN npm run build; RUN npm ci --silent --omit=dev; FROM node:lts-alpine AS runner; WORKDIR /usr/src/app; COPY --from=builder /usr/src/app/node_modules ./node_modules; COPY --from=builder /usr/src/app/dist ./dist; USER node; EXPOSE 3000; ENTRYPOINT node ./dist/index.js

Consejos prácticos para usar este Dockerfile y personalizarlo según tus necesidades

1. Exponer la aplicación: Asegúrate de que tu servidor escuche en la interfaz correcta 0.0.0.0 y publica los puertos del contenedor al host con un comando como docker run image_name:image_tag -p 3000:3000. Si usas Docker Compose la sección ports se encarga de esto, por ejemplo en YAML mínimo: services: node_api: build: . ports: - 3000:3000

2. Build multi stage: La primera fase descarga dependencias y compila la aplicación. Tras la transpilación se eliminan las dependencias de desarrollo para reducir el tamaño final de la imagen.

3. Imagen base: Utilizo node lts alpine por simplicidad y tamaño, pero es buena práctica fijar versiones concretas o usar un hash para garantizar builds reproducibles, por ejemplo indicando node:24.12.0-alpine3.23 o un SHA en la fase builder.

4. Seguridad y ejecución: En la segunda fase solo copio lo estrictamente necesario para el runtime y cambio al usuario node en lugar de ejecutar como root, lo que reduce riesgos de seguridad.

5. Entrypoint: Expongo el puerto 3000 y ejecuto el JavaScript transpilado directamente. Alternativamente puedes llamar a un script definido en package.json si lo prefieres.

Notas adicionales: El uso de npm ci en ambas fases garantiza instalaciones reproducibles y la opción --omit=dev en la fase final ayuda a ahorrar espacio. Herramientas como Dive te permiten inspeccionar capas y detectar dónde reducir peso.

En Q2BSTUDIO somos una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones a medida para empresas. Si buscas crear una aplicación personalizada o mejorar una existente puedes ver más sobre nuestro trabajo en desarrollo de aplicaciones a medida. Además ofrecemos servicios avanzados de inteligencia artificial para empresas y desarrollo de agentes IA, conoce nuestras capacidades en servicios de inteligencia artificial.

Ofrecemos también ciberseguridad y pentesting, servicios cloud aws y azure, servicios de inteligencia de negocio y Power BI, automatización de procesos y mucho más para ofrecer soluciones integrales de software a medida. Palabras clave importantes que manejamos incluyen 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.

Espero que esta guía te ayude a construir imágenes Docker más eficientes para Node y TypeScript. Si quieres que adaptemos un Dockerfile a tu proyecto o necesitas asesoría en arquitectura cloud y seguridad no dudes en contactarnos en Q2BSTUDIO.

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