How to Run a Python Script Using Docker

Run Python Script Docker

Running Python scripts is one of the most common tasks in automation. However, managing dependencies across different systems can be challenging. That’s where Docker comes in. Docker lets you package your Python script along with all its required dependencies into a container, ensuring it runs the same way on any machine. In this step-by-step guide, we’ll walk through the process of creating a real-life Python script and running it inside a Docker container.

Why Use Docker for Python Scripts

When you’re working with Python scripts, things can get messy/complex very fast. Different projects need different libraries, and what runs on your machine might break on someone else’s. Docker solves that by packaging your script and its environment together. So instead of saying “It works on my machine”, you can be sure it works the same everywhere.

It also keeps your system clean. You don’t have to install every Python package globally or worry about version conflicts. Everything stays inside the container.

If you’re deploying or handing your script off to someone else, Docker makes that easy, too. No setup instructions, no “install this and that”. Just one command, and it runs.

Write the Python Script

Let’s create a project directory to keep your Python script and Dockerfile. Once created, navigate into this directory using the cd command:

mkdir docker_file_organizer
cd docker_file_organizer

Create a script named “organize_files.py” to scan a directory and group files into folders based on their file extensions:

nano organize_files.py

Paste the following code into the “organize_file.py” file. Here, we use two pre-built Python modules, named os and shutil, to handle files and create directories dynamically:

import os
import shutil

SOURCE_DIR = "/files"

def organize_by_extension(directory):
    try:
        for fname in os.listdir(directory):
            path = os.path.join(directory, fname)
            if os.path.isfile(path):
                ext = fname.split('.')[-1].lower() if '.' in fname else 'no_extension'
                dest_dir = os.path.join(directory, ext)
                os.makedirs(dest_dir, exist_ok=True)
                shutil.move(path, os.path.join(dest_dir, fname))
                print(f"Moved: {fname} → {ext}/")
    except Exception as e:
        print(f"Error organizing files: {e}")

if __name__ == "__main__":
    organize_by_extension(SOURCE_DIR)

In this script, we organize files in a given directory based on their extensions. We use the os module to list the files, check if each item is a file, extract its extension, and create folders named after those extensions (if they don’t already exist). Then, we use the shutil module to move each file into its corresponding folder. For each move, we print a message showing the file’s new location.

Create the Dockerfile

Now, create a Dockerfile to define the environment in which your script will run:

FROM python:latest
LABEL maintainer="you@example.com"
WORKDIR /usr/src/app
COPY organize_files.py .
CMD ["python", "./organize_files.py"]

We use this Dockerfile to create a container with Python, add our script to it, and make sure the script runs automatically when the container starts:

Create Docker File

Build the Docker Image

Before you can build the Docker image, you need to install Docker first. After that, run the following command to package everything into a Docker image:

sudo docker build -t file-organizer .

It reads our Dockerfile and puts together the Python setup and our script so they’re ready to run in a single container image:

Build Docker Image

Create a Sample Folder with Files

To see our script in action, we create a test folder named “sample_files” with a few files of different types. We created these files just to make the folder a bit messy and see how our Python script handles it:

mkdir ~/sample_files
touch ~/sample_files/test.txt
touch ~/sample_files/image.jpg
touch ~/sample_files/data.csv

Run the Script Inside Docker

Finally, we run our Docker container and mount the sample folder into it. The -v flag mounts your local “~/sample_files” directory to the “/files” directory in the container, which allows the Python script to read and organize files on your host machine:

docker run --rm -v ~/sample_files:/files file-organizer

Here, we use the --rm option to remove the container automatically after it finishes running, which saves disk space:

Run Script In Docker

In the end, we use the tree command to check if the files have been sorted into folders based on their extensions:

tree sample_files
Verify Result With Tree Command

Note: The tree command isn’t pre-installed on most systems. You can easily install it using a package manager like apt on Ubuntu, brew on macOS, and so on.

Final Thoughts

With your Python script running inside Docker, you’re all set to take full advantage of a clean, portable, and consistent development setup. You can easily reuse this containerized workflow for other automation tasks, share your script without worrying about dependencies, and keep your system clutter-free. As a next step, consider exploring how to build multi-script Docker images, schedule containers with cron jobs, or integrate your scripts with other tools like Git, Jenkins, or even cloud platforms to streamline your automation and deployment process.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Anees Asghar Avatar

Read next

In 1969, László Bélády and two IBM colleagues published a paging-machine anomaly showing FIFO could make four memory frames suffer ten page faults after three frames suffered nine, leaving generations of operating-systems students staring at the moment more memory became the wrong answer
In 1964, IBM risked its entire corporate empire on the System/360, a chaotic gamble to make all of its future machines compatible with the same software — and the architecture proved so robust that modern enterprise mainframes today are still running sections of binary code written more than sixty years ago
In 1982, a Soviet pipeline suddenly exploded with the force of a tactical nuclear weapon, and the disaster was traced back to a stolen piece of Canadian pipeline software — and years later, it was revealed the CIA had intentionally allowed the KGB to steal the code, after subtly altering the software’s logic to trigger a catastrophic pressure surge months down the line.
In 1988, a graduate student launched an experimental script to measure the size of the internet, and a tiny programming oversight caused it to accidentally replicate out of control — infecting ten percent of all connected computers in hours and creating the world’s first massive digital crisis.
The Voyager 1 spacecraft launched in 1977 is now over 15 billion miles from Earth, and a radio signal from NASA takes more than 22 hours to reach it, meaning every command is really an instruction for where the probe will be by tomorrow
Every time you book a flight or check a hotel room, your request is routed through a green-screen mainframe system that traces back to the 1960s — and the entire multi-billion-dollar travel industry still relies on this ancient digital foundation because replacing it would be enormously expensive, dangerous, and slow
In 1997, a team of engineers hid an entire flight simulator inside the code of Microsoft Excel as an unlisted “Easter egg” — and to this day, it remains one of the most sophisticated pieces of hidden software ever secretly shipped to millions of corporate computers
A 65-year-old programming language called COBOL still quietly processes over $3 trillion in banking transactions every single day — and because the original engineers are rapidly retiring, banks are scrambling to pay younger developers fortunes just to keep the ancient infrastructure from breaking