CodingDevOpsIntermediate30 minSaves 30 minutes

Optimize Docker Images: Reduce 1.2GB to under 150MB for CI/CD

Platform engineers looking to streamline CI/CD pipelines can reduce oversized 1.2GB Docker images to under 150MB, improving build times, security, and deployment efficiency without impacting application functionality.

This guide helps platform engineers optimize Docker images, shrinking them from 1.2GB to under 150MB. It provides a detailed process to achieve significant size reduction and enhance security, all while ensuring application runtime stability for efficient CI/CD pipelines.

READY-TO-USE PROMPT

Copy Prompt

prompt.txt
As an experienced Docker optimization and container security engineer, your objective is to refine existing Dockerfiles for production environments.

**Context**
An existing Docker image for a `{{project_name}}` application currently measures 1.2GB. This substantial size is causing several issues: prolonged CI/CD build and deployment times, increased storage costs across registries, and an expanded attack surface. The immediate goal is to reduce this image size to under 150MB without compromising the application's runtime functionality or stability. You have access to the original Dockerfile and general knowledge of the application's core requirements.

**Task**
Refactor the provided `{{original_dockerfile_content}}` to achieve significant size reduction. Focus on implementing multi-stage builds, selecting minimal base images, and efficiently managing application dependencies. The output should provide a fully functional, smaller, and more secure Docker image.

**Constraints**
*   The final Docker image size must be less than 150MB. Strict adherence to this target is essential.
*   The application must function correctly post-deployment, without errors, performance degradation, or unexpected behavior.
*   Prioritize security best practices. This includes running processes as a non-root user, minimizing installed packages, and removing build-time tools from the final image.
*   The solution must be production-minded, easily auditable, and integrate seamlessly into existing CI/CD workflows.
*   Assume the application uses `{{application_language_or_framework}}` (e.g., Node.js, Python, Go) and its primary dependencies are `{{application_dependencies}}` (e.g., `npm install`, `pip install -r requirements.txt`).
*   The application's entrypoint command is `{{application_entrypoint_command}}` (e.g., `npm start`, `python app.py`).

**Output**
Provide the following:
1.  **Optimized Dockerfile**: A complete, refactored Dockerfile that implements the size reduction strategies. Include concise comments explaining the purpose of each major optimization step, such as stage transitions, dependency caching, and user setup.
2.  **Build Arguments or Docker Compose**: Suggest any necessary build arguments or a `docker-compose.yml` snippet if specific environment variables or external services are crucial for the optimized build or runtime. If no specific additions are required beyond standard Docker CLI commands for this optimization, state that clearly.
3.  **Image Size and Security Notes**: A brief analysis detailing how the proposed Dockerfile reduces image size and enhances security. Include an estimated final image size based on typical optimizations for `{{application_language_or_framework}}` applications, and highlight key security improvements.

Estimated results

DifficultyIntermediate
Setup time30 min
Time saved30 minutes
Best modelsClaude, ChatGPT, Gemini
Best audiencesoftware-development, devops

Editor's note

Why this prompt matters

Large Docker images often become a bottleneck in CI/CD pipelines, causing prolonged build times, increased storage costs across registries, and an expanded attack surface. When a typical application image grows to over a gigabyte, the cumulative impact on development velocity and operational expenses is substantial. This workflow is for platform engineers and DevOps teams facing such inefficiencies, offering a practical method to significantly reduce container sizes.

Optimizing Docker images is more than just saving disk space; it directly translates to faster iteration cycles and more secure deployments. Smaller images transmit quicker, build faster, and reduce the chance of carrying unnecessary vulnerabilities from extraneous packages. This process focuses on transforming an unwieldy 1.2GB image into a lean container under 150MB, ensuring the application's functionality remains intact.

The workflow guides you through implementing essential strategies like multi-stage builds and selecting minimal base images. It also emphasizes critical security practices, such as running processes as non-root users and eliminating build-time dependencies from the final production image. By applying these techniques, engineers can achieve substantial improvements in their CI/CD performance and overall operational posture, making deployments both swift and secure.

Anatomy

Prompt engineering breakdown

Role

The model assumes the role of an experienced Docker optimization and container security engineer.

Context

The task involves optimizing a 1.2GB Docker image for a {{project_name}} application, which is causing slow CI/CD, high storage costs, and an increased attack surface. The goal is to reduce it to under 150MB without affecting runtime functionality or stability.

Goal

To refactor the provided {{original_dockerfile_content}} using multi-stage builds, minimal base images, and efficient dependency management to produce a smaller, more secure, and fully functional Docker image.

Constraints

Strict size limit of under 150MB, no compromise on application functionality or stability, adherence to security best practices (non-root user, minimal packages, no build tools), production-minded and auditable solution, and assumptions about {{application_language_or_framework}} and {{application_entrypoint_command}}.

Output format

The required output is an optimized Dockerfile with comments, suggested build arguments or a docker-compose.yml snippet, and a brief analysis of image size reduction and security enhancements.

Why this structure works

This prompt uses role priming to align the model with an expert persona, ensuring a production-ready solution. Explicit constraints like the 150MB size limit and security best practices guide the model towards specific, measurable outcomes. The structured output format ensures all necessary components are generated, making the response immediately usable and auditable.

Pick your version

Prompt variations

BeginnerWorks with any model

When you are new to Docker image optimization or using AI prompts, and need a straightforward explanation and output without complex jargon.

prompt.txt
You are a helpful Docker expert. I have a big Docker image, about 1.2GB, for my {{project_name}} app. It's slowing down my deployments. I need to make it much smaller, under 150MB, but the app must still work perfectly. Please look at my {{original_dockerfile_content}} and suggest changes. Focus on making it smaller and more secure. Tell me how to build it and explain how it's smaller and safer. The app uses {{application_language_or_framework}} and starts with {{application_entrypoint_command}}. Make sure the app runs fine.
ProfessionalBest with claude

For experienced engineers seeking a detailed, production-grade Docker optimization strategy with explicit constraints and a focus on best practices.

prompt.txt
As a senior Docker architect specializing in container efficiency and security, your task is to overhaul a {{project_name}} application's Dockerfile. The current 1.2GB image is unsustainable due to CI/CD bottlenecks, storage costs, and security risks. Your objective is to reduce its footprint to less than 150MB while maintaining full runtime stability. Analyze the {{original_dockerfile_content}} and apply advanced multi-stage build techniques, minimal base images, and precise dependency management. Deliver an optimized Dockerfile with clear comments, essential build arguments or a docker-compose.yml fragment, and a concise analysis of the achieved size reduction and security posture. Ensure the solution is auditable and compatible with existing {{application_language_or_framework}} applications, using {{application_entrypoint_command}} for startup.
Short VersionWorks with any model

For quick iterations or when you need a concise, direct prompt to get an optimized Dockerfile without extensive contextual setup.

prompt.txt
Refactor the {{original_dockerfile_content}} for {{project_name}} ({{application_language_or_framework}} with {{application_entrypoint_command}}). The goal is to shrink the 1.2GB Docker image to under 150MB, preserving full application functionality and stability. Implement multi-stage builds, choose minimal base images, and apply security best practices like running as non-root and removing build-time dependencies. Provide the optimized Dockerfile, any critical build arguments or a docker-compose.yml snippet, and a concise summary of the achieved image size reduction and security enhancements. This solution must be production-ready and easily auditable.
EnterpriseBest with gemini

In environments requiring rigorous adherence to corporate standards, security policies, compliance frameworks, and detailed documentation for stakeholder review.

prompt.txt
Assume the role of a Principal Containerization Consultant. Your mandate is to execute a critical Docker image optimization project for a {{project_name}} application within a regulated enterprise environment. The current 1.2GB image poses significant operational and compliance risks, including extended build times, increased attack surface, and non-conformance with cost-efficiency metrics. Your primary objective is a validated image reduction to below 150MB, strictly preserving {{application_language_or_framework}} application functionality (entrypoint: {{application_entrypoint_command}}). Beyond size, the solution must enhance security posture, demonstrate auditability for compliance, and minimize long-term operational overhead. Refactor the {{original_dockerfile_content}} utilizing multi-stage builds, approved minimal base images, and explicit dependency hygiene. Provide the optimized Dockerfile with detailed inline comments explaining security and size benefits, any required build parameters for secure deployment, and a formal analysis report detailing risk mitigation, compliance alignment, and the quantitative impact on image size and security.

What you'll get

Expected output

Here is an example of an optimized Dockerfile, demonstrating a multi-stage build for a Python application. This approach separates build-time dependencies and tools from the final runtime image, significantly reducing its size. The goal is to move from a hypothetical 1.2GB image to under 150MB by using minimal base images and carefully copying only necessary artifacts. A simple docker-compose.yml snippet is also included for local testing.

Optimized Dockerfile

```dockerfile # Stage 1: Builder - Install application dependencies # Uses a 'slim-buster' base for installing Python packages, including any C extensions. FROM python:3.9-slim-buster as builder

# Set working directory for the build process. WORKDIR /app

# Install build tools like 'build-essential' if Python packages require compilation. # Clean up apt caches immediately to avoid carrying unnecessary data. RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ && rm -rf /var/lib/apt/lists/*

# Copy 'requirements.txt' first to use Docker layer caching. # Only reinstall dependencies if this file changes. COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt

# Copy the remaining application source code. COPY . .

# Stage 2: Production - Create a minimal runtime image # Uses a 'python:alpine' base for a significantly smaller final image. FROM python:3.9-alpine

# Create a dedicated non-root user and group ('appuser', 'appgroup') for security. # This minimizes potential attack surface by not running as root. RUN addgroup -S appgroup && adduser -S appuser -G appgroup USER appuser

# Set the working directory for the application's runtime. WORKDIR /app

# Copy only the installed Python packages from the builder stage. # This leaves behind build tools and intermediate files. COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages # Copy the application code from the builder stage. COPY --from=builder /app /app

# Declare the port the application expects to listen on. EXPOSE 8000

# Define the default command to execute when the container starts. CMD ["python", "app.py"] ```

Docker Compose Snippet

This docker-compose.yml provides a basic configuration to build and run the optimized application image locally. It maps the container's exposed port to the host and sets a production environment variable.

``yaml version: '3.8' services: my-app: build: context: . dockerfile: Dockerfile ports: - "8000:8000" environment: - APP_ENV=production # Add other production environment variables as needed, e.g., database connection strings. # - DATABASE_URL=postgres://user:pass@db:5432/myapp ``

Under the hood

Why this prompt works

This prompt is effective because it establishes a clear persona from the outset, instructing the model to act as an "experienced Docker optimization and container security engineer." This immediately sets the expectation for expert-level, production-minded solutions that prioritize both efficiency and security.

The inclusion of a quantifiable, challenging goal—reducing a 1.2GB image to under 150MB—is critical. This specific target pushes the model to apply aggressive, proven optimization strategies like multi-stage builds and minimal base images, rather than superficial adjustments. The detailed constraints further refine the output, ensuring the solution maintains application functionality, adheres to strict security best practices (e.g., non-root user, minimal packages), and is auditable for CI/CD integration. These guardrails prevent the generation of impractical or insecure Dockerfiles.

Providing specific context about the current image size and its negative impact (build times, storage, attack surface) grounds the task in a realistic engineering problem. The prompt then explicitly directs the model towards key optimization techniques, such as multi-stage builds and dependency management, which are essential for achieving the stated goal.

Finally, the structured output request for an "Optimized Dockerfile" complete with explanatory comments, alongside suggestions for build arguments or Docker Compose snippets, ensures the response is immediately actionable. This format allows platform engineers to quickly implement and audit the generated solution, making it highly practical for streamlining CI/CD pipelines.

Model fit

Best AI models for this prompt

Claude

Claude models handle multi-stage Dockerfile generation well, often producing clear, commented code. They are strong at explaining the rationale behind security choices and base image selection. However, they sometimes require minor edits to optimize the order of RUN commands for better cache utilization. See the full Claude hub for deeper guidance.

ChatGPT

ChatGPT excels at refactoring existing Dockerfiles, identifying redundant layers, and suggesting appropriate slim base images. It's particularly effective at integrating docker-compose.yml snippets for development or specific build arguments. Verify the generated security practices as they can sometimes be generic. See the full ChatGPT hub for deeper guidance.

Gemini

Gemini models are adept at generating concise and efficient Dockerfiles, particularly when dealing with common language runtimes. They tend to provide accurate estimations for image size reduction and can quickly adapt to different application dependency management systems. Review their suggestions for complex security configurations. See the full Gemini hub for deeper guidance.

When to use

  • To significantly reduce CI/CD pipeline build and deployment times.
  • When facing escalating storage costs for Docker images in registries.
  • For environments where network bandwidth or disk space is a critical constraint.
  • To decrease the attack surface of containerized applications for security hardening.
  • When migrating legacy Dockerfiles that were not initially designed for production optimization.

When not to use

  • For initial development builds where rapid iteration and debugging tools are prioritized over image size.
  • If the application relies on a very specific, large set of OS packages or libraries that cannot be easily pruned.
  • When a pre-existing, validated base image already meets all performance, size, and security requirements.
  • During complex troubleshooting that might require full debugging toolsets present in larger images.

Get more from it

Pro tips

  • 1

    Always use specific version tags for base images, preventing unexpected breakage from `latest` updates and ensuring build reproducibility.

  • 2

    Implement multi-stage builds to prevent build-time dependencies and tools from contaminating the final runtime image, significantly reducing its size.

  • 3

    Use `.dockerignore` effectively to exclude irrelevant files like test data, documentation, and Git metadata from the build context, avoiding unnecessary bloat.

  • 4

    Run `docker build --no-cache` occasionally to verify all build steps are idempotent and not relying on stale cached layers, preventing subtle dependency issues.

  • 5

    Prioritize smaller, purpose-built base images like Alpine or Distroless when possible, as they inherently provide a minimal starting point, preventing OS-level bloat.

  • 6

    Scan your final image with tools like Trivy or Clair to proactively identify vulnerabilities and ensure security baselines are met before deployment, preventing critical security oversights.

Don't ship this

Common mistakes

  • Copying the entire application context into the image without filtering.

    Fix — Utilize a `.dockerignore` file to exclude development files, test data, and version control metadata, reducing build context size.

  • Not removing build-time dependencies or caches in the final image.

    Fix — Implement multi-stage builds to separate build environments from runtime, or include cleanup commands for package managers.

  • Running application processes as the root user by default.

    Fix — Create a dedicated non-root user and group, then `USER` switch to run the application with minimal privileges.

  • Installing unnecessary system packages that aren't critical for runtime.

    Fix — Audit `apt install` or `yum install` commands, removing any packages not strictly required for application function.

  • Ignoring the order of Dockerfile instructions, leading to inefficient layer caching.

    Fix — Place frequently changing layers (like application code) after stable layers (like dependencies) to maximize cache hits.

  • Not validating application functionality and performance after optimization.

    Fix — Implement comprehensive integration and performance tests in CI/CD to confirm the optimized image behaves as expected.

People also ask

Frequently asked questions

Q.Will this optimization process impact my application's runtime performance?

Generally, no. Reducing image size primarily affects build and deployment times, and storage. A smaller image might even start faster due to less disk I/O. Focus remains on functional equivalence.

Q.What if my application has a large, unavoidable dependency that prevents reaching the target size?

If a critical dependency is large, explore its 'slim' or 'alpine' variants if available. Alternatively, consider if parts of the dependency can be externalized or if a custom minimal base image can be created.

Q.How can I verify the image size and ensure it's under the 150MB target?

After building, use docker images to check the size. For deeper analysis of layer contributions, tools like dive can help visualize and identify large components within the image layers.

Q.Is it always necessary to use a non-root user? What are the risks if I don't?

Using a non-root user is a critical security best practice. Running as root allows any compromised process within the container to have full root privileges on the host, significantly increasing the potential impact of a breach.

Q.Can I apply these optimization strategies to any programming language or framework?

The core principles like multi-stage builds, minimal base images, and efficient dependency management are language-agnostic. Specific commands for package installation and cleanup will vary based on your chosen language and framework.

Q.How do I ensure application stability after such significant image size reduction?

Thorough testing is crucial. Implement functional tests, integration tests, and performance benchmarks in your CI/CD pipeline. Verify all critical application features work correctly and that performance metrics remain within acceptable bounds before deployment.

Version 1.0Last reviewed July 20, 2026
Reviewed by PromptInFlow Editorial Team