How to run Python scripts using Docker
Running a Python script is one of the most common tasks in automation. However, managing dependencies across different systems can be a challenge. That's where Docker comes in. Docker allows you to package a Python script along with all the necessary dependencies into a container, ensuring it runs the same way on every machine. Today's article will walk you through the process of creating an actual Python script and running it inside a Docker container.
Write Python script
Create a project directory to store your Python script and Dockerfile. Once created, navigate to this directory using the cd command :
mkdir docker_file_organizer cd docker_file_organizer
Create a script called 'organize_files.py' to scan a directory and group files into directories based on their extensions:
nano organize_files.py
Paste the following code into the 'organize_file.py' file. Here, we use two built-in 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 sort the files in a given directory based on their extensions. We use the os module to list the files, check if each entry is a file, extract the file extensions, and create directories named after those extensions (if they don't already exist). Then, we use the shutil module to move each file into its corresponding directory. For each move, a message showing the new location of the file is output.
Create Dockerfile
Now, let's create a Dockerfile to define the environment in which the 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 in Python , add a script to it, and make sure the script runs automatically when the container starts:
Build Docker image
Before you can build a Docker image, you first need to install Docker. Then, run the following command to package everything into a Docker image:
sudo docker build -t file-organizer .
It reads the Dockerfile, combines the Python setup and scripts so they are ready to run in a single container image:
Create a sample folder with the files
To see the script in action, create a test directory called 'sample_files' with a few files of different types. Create these files just to clutter the directory a bit and see how the Python script handles it:
mkdir ~/sample_files touch ~/sample_files/test.txt touch ~/sample_files/image.jpg touch ~/sample_files/data.csv
Run scripts inside Docker
Finally, run the Docker container and mount the sample directory into it. The -v flag mounts the local '~/sample_files' directory into the '/files' directory in the container, allowing the Python script to read and sort the files on your host:
docker run --rm -v ~/sample_files:/files file-organizer
Here, the article uses the --rm option to automatically delete the container after it finishes running, helping to save disk space:
Finally, use the tree command to check if the files are sorted into directories based on their extensions:
tree sample_files
Note : The tree command does not come pre-installed on most systems. You can easily install it using a package manager like apt on Ubuntu , brew on macOS, etc.
You should read it
- How to create an effective Docker image for a Python project
- Protect Python scripts against reverse engineering with Pyarmor
- Docker best practices you need to know
- Python online editor
- Docker Hub is used by hackers to spread Cryptojacking malware
- How to Open a Python File
- How to safely check desktop applications with Docker
- TOP 6 websites that support online Python programming compilation
May be interested
- 5 useful tips to learn Docker in 2018do you want to study docker in 2018? here are 5 helpful tips that can help you learn docker effectively.
- How to safely check desktop applications with Dockerdocker allows applications to run in their own sandbox world. these applications share resources but do not interfere with programs running on the system.
- Containerize Go App with Dockerlearn how to use docker to efficiently package and deploy go applications, making them flexible and manageable. here are detailed instructions.
- Common commands in Dockerdocker is a computer program that performs os-level virtualization, also known as containerization.
- What is Docker Compose? Summary of knowledge about Docker composedocker compose is a tool used to define and run docker programs using multiple containers (multi-containers).
- How to automate GIMP by scriptif you're willing to work with scripts, you can use gimp to automate some actions, saving you time and effort.
- How to install Docker in Linuxdocker is a containerized utility that has become very popular, simplifying such tasks. moreover, when there is a problem with the operating system, instead of installing and reconfiguring the application, users only need to reinstall the operating system, copy the container again.
- 5 tips to learn Docker effectively for beginnersto keep up with this new technology trend, many people are starting to learn docker. for beginners familiar with docker, please refer to the article below to achieve high results.
- How to import Excel data into Python scripts with Pandasinstead of manually copying data into a database, here is a quick guide on how to load excel data into python using pandas.
- More than 100 Python exercises have solutions (sample code)more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.