This prompt is designed for containerization engineers and CI/CD pipeline operators who need to automatically recover from failed Docker image builds. The core job is to consume a Dockerfile and the complete build error log, then produce a corrected Dockerfile that resolves the build failure while preserving the original intent. The prompt also generates layer optimization notes, helping teams improve build caching and image size in the same recovery step. This is not a general Dockerfile authoring assistant—it is a targeted recovery tool for build-time failures such as missing base images, COPY failures, RUN command errors, package installation conflicts, and multi-stage build misconfigurations.
Prompt
Docker Build Failure Recovery Prompt

When to Use This Prompt
Defines the job, ideal user, required inputs, and boundaries for the Docker Build Failure Recovery Prompt.
Use this prompt when you have a concrete build failure with a captured error log and the offending Dockerfile. The prompt works best with deterministic, reproducible build errors rather than transient network or resource issues. It requires the full build context: the Dockerfile content, the exact error output from the build command, and optionally the build context structure if the error involves file paths. Do not use this prompt for runtime container debugging, orchestration-level failures (e.g., Kubernetes pod crashes), or security vulnerability scanning—those require different diagnostic workflows. The prompt assumes a single Dockerfile as input; multi-service builds with docker-compose or complex build arguments should be broken into individual Dockerfile recovery steps.
Before wiring this into an automated pipeline, ensure you have a validation harness that rebuilds the corrected Dockerfile in an isolated environment and runs a basic smoke test (e.g., container starts, expected process runs, health check passes). The prompt produces a corrected Dockerfile, but the fix may introduce subtle behavioral changes—layer reordering, base image version bumps, or package version shifts—that require human review for production images. For high-risk production deployments, route the corrected Dockerfile to a pull request workflow with mandatory human approval rather than auto-merging. The next section provides the copy-ready prompt template you can adapt to your specific build environment and error format.
Use Case Fit
Where this prompt works and where it does not. Understand the operational boundaries before wiring it into a CI pipeline.
Good Fit: Deterministic Build Errors
Use when: The build fails with a clear error message from the Docker daemon (e.g., COPY source not found, package install failure, missing file). Why: The prompt can map a specific error line to a specific instruction in the Dockerfile and propose a surgical fix.
Bad Fit: Flaky Network or Infrastructure Issues
Avoid when: The error is a transient network timeout, a registry 503, or a disk pressure eviction on the build node. Why: The prompt will attempt to rewrite the Dockerfile to fix a problem that is environmental, not structural. This wastes cycles and may introduce unnecessary complexity.
Required Inputs: Error Log and Dockerfile
Guardrail: The prompt requires both the full build error log and the complete Dockerfile. Without the log, it hallucinates fixes. Without the Dockerfile, it cannot map errors to line numbers. Check: Validate that both inputs are non-empty and that the error log contains a non-zero exit code before invoking the model.
Operational Risk: Layer Cache Invalidation
Risk: A naive fix that reorders COPY or RUN instructions can invalidate the Docker build cache, causing long rebuilds and increased CI costs. Guardrail: Add a constraint in the prompt to preserve layer ordering unless strictly necessary, and flag any cache-impacting changes in the output explanation.
Operational Risk: Security Regression
Risk: A recovery prompt might suggest RUN apt-get update && apt-get install -y without pinning versions or cleaning up the package cache, increasing image size and attack surface. Guardrail: Include a policy instruction to enforce package pinning, non-root users, and cleanup steps in any generated RUN line.
Boundary: Multi-Stage Build Complexity
Use when: The error is isolated to a single stage. Avoid when: The failure is a missing artifact from a previous stage that requires a full re-architecture of the build graph. Guardrail: If the error crosses stage boundaries, escalate to a human for a design review rather than attempting an automated fix.
Copy-Ready Prompt Template
A reusable prompt template that consumes a Dockerfile and build error log to produce a corrected Dockerfile with layer optimization notes.
The prompt below is designed to be dropped into an automated CI/CD recovery harness. It expects a failed Dockerfile and the corresponding build error log, and it instructs the model to act as a senior containerization engineer. The output is a corrected Dockerfile with a structured explanation of the fix and any layer-caching improvements. Use this template as the core instruction in a retry step after a docker build command returns a non-zero exit code.
textYou are a senior containerization engineer debugging a failed Docker build. Your task is to analyze the provided Dockerfile and the build error log, then produce a corrected Dockerfile that builds successfully. ## INPUT [DOCKERFILE] [BUILD_ERROR_LOG] ## CONSTRAINTS - Preserve the original application logic and entrypoint behavior. - Do not change base image versions unless the error log indicates an incompatibility. - Prefer minimal fixes over rewrites. - If the error is a transient network or registry issue, note that in your explanation and suggest a retry rather than a Dockerfile change. - If the error is caused by a missing file or incorrect COPY path, verify the path against common project structures and suggest the likely correct path. - If the error is a layer-caching issue, reorder instructions to maximize cache reuse (e.g., move rarely-changing COPY commands before frequently-changing ones). ## OUTPUT_SCHEMA Return a JSON object with the following fields: { "diagnosis": "One-sentence summary of the root cause.", "fix_type": "One of: dependency_version, file_path, syntax_error, layer_order, network_retry, permission, resource_limit, multi_stage_fix, unknown", "corrected_dockerfile": "The full corrected Dockerfile as a single string with newlines escaped as \n.", "changes": [ { "line_range": "Lines 12-14", "before": "RUN apt-get install curl", "after": "RUN apt-get update && apt-get install -y curl", "reason": "Missing apt-get update before install causes 404 errors on stale package lists." } ], "layer_optimization_notes": "Optional string describing any reordering for cache efficiency.", "confidence": "high | medium | low" } ## EXAMPLES ### Example 1: Missing apt-get update Input Dockerfile: FROM ubuntu:22.04 RUN apt-get install -y curl Error Log: E: Unable to locate package curl The command '/bin/sh -c apt-get install -y curl' returned a non-zero code: 100 Output: { "diagnosis": "Package list is stale; apt-get update is required before installing packages.", "fix_type": "syntax_error", "corrected_dockerfile": "FROM ubuntu:22.04\nRUN apt-get update && apt-get install -y curl", "changes": [ { "line_range": "Line 2", "before": "RUN apt-get install -y curl", "after": "RUN apt-get update && apt-get install -y curl", "reason": "apt-get update refreshes the package index, preventing 404 errors." } ], "layer_optimization_notes": null, "confidence": "high" } ### Example 2: COPY path not found Input Dockerfile: FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY src/ ./src/ Error Log: COPY failed: file not found in build context or excluded by .dockerignore: stat package*.json: no such file or directory Output: { "diagnosis": "package.json is not in the build context root; it may be in a subdirectory or the build context is misconfigured.", "fix_type": "file_path", "corrected_dockerfile": "FROM node:18-alpine\nWORKDIR /app\nCOPY ./app/package*.json ./\nRUN npm ci --only=production\nCOPY ./app/src/ ./src/", "changes": [ { "line_range": "Line 3", "before": "COPY package*.json ./", "after": "COPY ./app/package*.json ./", "reason": "The build context likely points to the repository root, and the application is in an 'app' subdirectory." }, { "line_range": "Line 5", "before": "COPY src/ ./src/", "after": "COPY ./app/src/ ./src/", "reason": "Consistent path correction for the source directory." } ], "layer_optimization_notes": "Layer order is already optimal: package files are copied before source to maximize npm ci cache reuse.", "confidence": "medium" } ## RISK_LEVEL [RISK_LEVEL] If RISK_LEVEL is "high", include a warning in the diagnosis and set confidence to "low" if the fix involves changing base images, altering entrypoints, or modifying multi-stage build logic without full context.
To adapt this template for your pipeline, replace the [DOCKERFILE] and [BUILD_ERROR_LOG] placeholders with the actual file content and error output from your build system. Set [RISK_LEVEL] to "high" for production deployments, "medium" for staging, or "low" for development environments. The JSON output schema is designed to be machine-readable: your harness should parse the corrected_dockerfile field, write it to disk, and re-run docker build. If confidence is "low" or fix_type is "unknown", route the suggestion to a human for review before applying. Always validate the corrected Dockerfile with docker build --dry-run or a linting tool like Hadolint before committing the change to your repository.
Prompt Variables
Placeholders required by the Docker Build Failure Recovery Prompt. Replace each with concrete values before sending the prompt. Validation notes describe how to confirm the input is usable.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DOCKERFILE] | The original Dockerfile that failed to build | FROM node:18\nCOPY . .\nRUN npm install | Must be valid plain text. Check for non-printable characters and encoding issues before insertion. |
[BUILD_ERROR_LOG] | The complete build error output from the Docker daemon | Step 3/5 : RUN npm install\nERROR: npm ERR! code ERESOLVE | Must include the full error text. Truncated logs will cause incomplete diagnosis. Verify the log contains the exit code and the failing step. |
[BASE_IMAGE_CONSTRAINT] | Optional allowed base image or registry restriction | node:18-alpine | If provided, the corrected Dockerfile must not switch to a disallowed base image. Validate against an allowlist if one exists. |
[TARGET_PLATFORM] | Target architecture for the build | linux/amd64 | Must match a valid Docker platform string. Check against the build environment capabilities. |
[SECURITY_POLICY] | Optional security policy rules to enforce | No root user, no latest tag | If provided, the corrected Dockerfile must pass a policy-as-code check. Validate with a tool like Conftest or a custom scanner. |
[SMOKE_TEST_COMMAND] | Command to run after a successful build to confirm the image works | docker run --rm [IMAGE] curl -f http://localhost:3000/health | Must be a non-interactive command that exits zero on success. Test the command manually against a known-good image first. |
[OUTPUT_FORMAT] | Desired output structure for the corrected Dockerfile and notes | JSON with 'dockerfile' and 'layer_optimization_notes' fields | Must be a valid schema definition. The harness should parse the model output against this schema and reject non-conforming responses. |
Implementation Harness Notes
How to wire the Docker Build Failure Recovery Prompt into an automated CI pipeline or a developer CLI tool.
This prompt is designed to be called programmatically after a docker build command exits with a non-zero code. The application harness should capture the full build log from stdout/stderr, read the original Dockerfile, and assemble the prompt with both artifacts. Do not truncate the error log; the model needs the complete context to diagnose multi-stage build failures, missing file errors, and layer-specific issues. The harness should also inject the target platform and any build arguments used so the model can reason about architecture mismatches.
The implementation should follow a strict retry budget. After receiving the corrected Dockerfile from the model, the harness must write it to a temporary location and execute docker build again. If the build succeeds, proceed to a smoke test that runs the image with a basic health check command (e.g., docker run --rm [image] [healthcheck]). If the build fails again, feed the new error log back into the prompt for a second attempt, but cap total retries at three. After three failures, log the full interaction, flag the build for human review, and do not deploy. Each retry cycle should be logged with the prompt version, model used, build duration, and whether the fix was applied successfully.
For model selection, use a capable code-generation model such as claude-sonnet-4-20250514 or gpt-4o. Avoid smaller or faster models for this task because Dockerfile repair requires precise syntax knowledge, understanding of layer caching implications, and the ability to reason about build context. If the pipeline runs in a cost-sensitive environment, you can attempt the first retry with a smaller model and escalate to a larger model on the second attempt. Always validate the model's output before applying it: check that the response contains a valid Dockerfile in a fenced code block, that it does not introduce unvalidated COPY or ADD instructions from unexpected paths, and that it preserves the original image base and essential build stages. Never apply a model-generated Dockerfile directly to production without a successful build and smoke test in the pipeline.
Expected Output Contract
Defines the required fields, types, and validation rules for the corrected Dockerfile and build report. Use this contract to validate the model's response before applying the fix in a CI/CD pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
corrected_dockerfile | string (plain text) | Must be syntactically valid Dockerfile content. Parse check: no unclosed quotes, valid FROM/COPY/RUN directives. Must differ from [ORIGINAL_DOCKERFILE] in at least one line. | |
build_error_summary | string | Must contain a concise root cause analysis. Length check: 50-500 characters. Must reference at least one specific error line from [BUILD_ERROR_LOG]. | |
layer_optimization_notes | array of strings | If present, each string must describe a specific optimization (e.g., cache ordering, multi-stage build suggestion). Null allowed if no optimizations are applicable. | |
fix_type | enum string | Must be one of: 'syntax_fix', 'dependency_fix', 'configuration_fix', 'layer_order_fix', 'multi_stage_fix', 'other'. Enum check against allowed values. | |
smoke_test_command | string | Must be a valid shell command string. Parse check: no command injection characters (;, &&, |) unless explicitly part of the intended test. Must be executable in a standard sh environment. | |
requires_human_review | boolean | Must be true if the fix involves changing base images, modifying exposed ports, or altering security-related directives (USER, COPY --chown). Otherwise false. | |
confidence_score | number (0.0-1.0) | Must be a float between 0.0 and 1.0. Range check. If below 0.8, [requires_human_review] must be true. Used for retry threshold gating. |
Common Failure Modes
Docker build failures often stem from a few predictable patterns. These cards cover the most common failure modes for a Docker Build Failure Recovery Prompt and how to guard against them in your harness.
Layer Caching Misdiagnosis
What to watch: The model suggests clearing the entire build cache or reordering COPY commands without understanding the dependency graph, leading to slower builds or no fix at all. Guardrail: Provide the model with the Dockerfile's build context structure and explicitly instruct it to preserve layer caching unless a change invalidates a specific layer's dependencies.
Hallucinated Package Versions
What to watch: To resolve a dependency error, the model invents a package version or a package name that doesn't exist in the target registry, creating a new, different build failure. Guardrail: Instruct the prompt to only suggest package versions that are explicitly mentioned in the provided error log or to recommend a version-agnostic constraint. Add a post-patch validation step that checks the base image's package manager for the existence of any suggested package.
Ignoring Multi-Stage Build Context
What to watch: The model proposes a fix that copies a file from a previous stage that doesn't exist or uses the wrong stage alias, breaking the multi-stage build's internal contract. Guardrail: The prompt must require the model to explicitly reference stage names (FROM ... AS [name]) and --from=[name] flags in its analysis. The harness should parse the corrected Dockerfile to verify all cross-stage references are valid.
Security Context Regression
What to watch: In an attempt to fix a permissions error, the model suggests running the container as root (USER root) or using overly permissive chmod 777 commands, silently degrading the image's security posture. Guardrail: Add a hard constraint to the prompt: "Do not suggest running as root or using world-writable permissions as a fix. Propose the least-privilege solution." The harness should scan the output for these anti-patterns and fail the validation if found.
Network and External Resource Flakiness
What to watch: The model treats a transient network error or a temporarily unavailable external resource (e.g., a package mirror) as a permanent configuration error, suggesting unnecessary changes to URLs or network settings. Guardrail: The prompt should instruct the model to first classify the error as transient or permanent based on the error message (e.g., "Could not resolve host" vs. "404 Not Found"). For transient errors, the primary recommendation should be a retry with exponential backoff, not a config change.
Incomplete Error Log Analysis
What to watch: The model focuses on the first error in a long build log, missing a root cause buried deeper in the output, resulting in a fix that doesn't resolve the actual problem. Guardrail: Structure the prompt to require a "Root Cause Analysis" section before the "Corrected Dockerfile" section. Instruct the model to scan the entire log for the first occurrence of a fatal signal (e.g., ERROR, failed to solve, signal SIGKILL) and base its diagnosis on that event.
Evaluation Rubric
Use this rubric to evaluate the quality of the Dockerfile and build recovery output before integrating it into an automated CI/CD pipeline. Each criterion should be tested programmatically or via a manual review checklist.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Build Success | The corrected Dockerfile builds successfully with | The build exits with a non-zero code or produces a new error. | Automated: Execute |
Error Root Cause Addressed | The explanation correctly identifies the specific line or instruction causing the original build failure. | The explanation describes a generic fix or misidentifies the faulty instruction. | Manual Review: Compare the identified root cause against the original [BUILD_ERROR_LOG]. |
Layer Optimization | The corrected Dockerfile includes at least one concrete optimization note (e.g., cache ordering, multi-stage build, | The output only fixes the error without any optimization notes or suggests harmful anti-patterns. | Manual Review: Check for a dedicated 'Optimization Notes' section with actionable advice. |
Smoke Test Pass | A container launched from the corrected image passes a basic health check or entrypoint test. | The container exits immediately, crashes on start, or fails to bind to the expected port. | Automated: Run |
Original Intent Preservation | The corrected Dockerfile does not remove or fundamentally alter the application's core entrypoint or dependencies. | The fix deletes critical | Manual Diff: Compare the original [DOCKERFILE] with the corrected output to ensure no critical logic was removed. |
Security Context Check | The fix does not introduce | The output adds | Static Analysis: Scan the corrected Dockerfile with a linter (e.g., Hadolint) to check for severity-level violations. |
Idempotency | The corrected Dockerfile builds successfully on two consecutive runs without modification. | The build fails on a second run due to a non-deterministic instruction or a missing version pin. | Automated: Run the build test twice in sequence and confirm both attempts pass. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single Dockerfile and error log. Skip layer optimization notes and smoke test validation. Focus on getting a buildable Dockerfile quickly.
codeYou are a Docker build recovery assistant. Given a Dockerfile and a build error log, output a corrected Dockerfile. Dockerfile: [DOCKERFILE] Build Error Log: [BUILD_ERROR_LOG] Return only the corrected Dockerfile.
Watch for
- The model may change base images without warning
- Multi-stage builds can confuse simpler models
- No validation that the fix actually builds

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us