[Python] How to save a generated picture.png from the Docker image to the host machine?

Discussão em 'Python' iniciado por Stack, Junho 26, 2025.

  1. Stack

    Stack Membro Participativo

    The goal of the program is to save a picture (such as .png), generated using matplotlib in Python, to the host directory. The expected result is for picture.png to appear in the directory containing the files necessary to build the docker-image.

    docker build -t bar-graph-image . builds the docker-image successfully. docker run bar-graph-image runs the image, but I can not find the generated picture.png. Docker also does not show a newly created container. docker run -v <host\directory\path>:. bar-graph-image results in an error saying that '.' is an invalid mount path, and the path must be absolute. I do not know what the absolute path of the container would be though, nor does Docker seem to build a container at all to find a path in. This is the full error message: docker: Error response from daemon: invalid volume specification: '<host\directory\path>:.': invalid mount config for type "bind": invalid mount path: '.' mount path must be absolute

    Here is the code:

    Dockerfile

    # Use a slim Python base image for a smaller image size
    FROM python:3.9-slim-buster

    # Set the working directory inside the container
    WORKDIR .

    # Install system dependencies required by Matplotlib
    # These might include build tools and libraries for font rendering, image formats, etc.
    RUN apt-get update && \
    apt-get install -y \
    build-essential \
    pkg-config \
    libfreetype6-dev \
    libpng-dev \
    && rm -rf /var/lib/apt/lists/*

    # Copy your requirements.txt file and install Python dependencies
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    # Copy your application code into the container
    COPY . .

    # Command to run your application (adjust as needed)
    CMD ["python", "bar_graph.py"]


    requirements.txt

    matplotlib


    bar_graph.py

    import matplotlib.pyplot as plt

    # Data for the bar graph
    categories = ['Apples', 'Bananas', 'Oranges', 'Grapes']
    values = [10, 15, 7, 12]

    # Create the bar graph
    plt.bar(categories, values)

    # Add labels and title
    plt.xlabel('Fruit Type')
    plt.ylabel('Quantity')
    plt.title('Fruit Quantities in Stock')

    # Save graph as an image
    plt.savefig("my_plot.png")

    # Display the graph
    plt.show()

    Continue reading...

Compartilhe esta Página