Zaheer Ahmad
2 min readJan 10, 2025

🚀 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:

  1. 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.
  2. Next.js Optimization:
    I dug into the Next.js documentation and discovered the output: "standalone" option. This allowed me to exclude node_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! 🌟

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Zaheer Ahmad
Zaheer Ahmad

Written by Zaheer Ahmad

Upwork Top Rated | DevOps Engineer | AWS Certified | Github Action | Docker | Terraform

No responses yet

Write a response