🚀 Optimizing Docker Images for Nextjs

Recently, I had the chance to work on a healthcare project focused on optimizing the production environment. The setup was already in place, but the challenge was clear: make it leaner and developer-friendly.
Here’s the scenario:
The initial Docker image size? A hefty 800MB 🤯. The Dockerfile was poorly written, which meant I had to rewrite it from scratch.
The Process:
- Multi-Stage Builds:
By switching to a multi-stage Dockerfile, I managed to reduce the size to 350MB. A big improvement, but still not good enough. - Next.js Optimization:
I dug into the Next.js documentation and discovered theoutput: "standalone"
option. This allowed me to excludenode_modules
during the production stage. Result? The image size dropped to a sleek 120MB! 🎯
Developer Experience:
Here’s where it gets better. My goal was to ensure developers could test production issues locally without the hassle of pulling images from ECR. To achieve this, I:
- Unified the Dockerfile for both development and production environments.
- Introduced targeted builds with the
--target
flag:docker build -t dev --target dev
docker build -t prod --target production
This centralized approach keeps things simple, avoids multiple Dockerfiles, and gives developers the same experience across environments.
The Outcome:
- Image size: Reduced from 800MB → 120MB
- Developer happiness: 🎉
- Efficiency: Centralized, streamlined workflow
Lessons learned? Never underestimate the power of well-crafted Dockerfile and Next.js optimizations!
What’s your favorite Docker optimization tip? Let’s share ideas! 🌟