Dockerfile Parser

3.4.0 · active · verified Thu Apr 16

The 'dockerfile' Python library (version 3.4.0) provides a high-level representation parser for Dockerfiles, leveraging the official Go parser. It allows programmatic inspection and manipulation of Dockerfile instructions, making it useful for static analysis, linting, or generating Dockerfile content. The library is actively maintained with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a Dockerfile from a file path using `dockerfile.parse_file()`. It then iterates through the parsed commands, printing their type, value, and original line, and shows how to filter for specific command types (e.g., 'RUN').

import dockerfile
import os

# Create a dummy Dockerfile for demonstration
with open("temp_Dockerfile", "w") as f:
    f.write("FROM python:3.9-slim\n")
    f.write("WORKDIR /app\n")
    f.write("COPY requirements.txt .\n")
    f.write("RUN pip install --no-cache-dir -r requirements.txt\n")
    f.write("COPY . .\n")
    f.write("CMD [\"python\", \"app.py\"]\n")

dockerfile_path = "temp_Dockerfile"

# Parse a Dockerfile from a file
try:
    commands = dockerfile.parse_file(dockerfile_path)

    print(f"Parsed {len(commands)} commands from {dockerfile_path}:")
    for cmd in commands:
        print(f"  Command: {cmd.cmd:<10} Value: {cmd.value}, Original: '{cmd.original}'")

    # Example: Find all RUN commands
    run_commands = [c.value for c in commands if c.cmd == 'run']
    print(f"\nRUN commands found: {run_commands}")

finally:
    # Clean up the dummy Dockerfile
    if os.path.exists(dockerfile_path):
        os.remove(dockerfile_path)

view raw JSON →