When I first started working with Docker, one of the things I needed to figure out was how to run a Python script efficiently within a container. Docker is a fantastic tool for containerizing applications, and running Python scripts in this environment can simplify dependencies and make your projects more portable. In this post, I’ll walk you through the process of setting up, running, and managing Python scripts in Docker, step by step.
Thank me by sharing on Twitter 🙏
By the end of this guide, you’ll feel confident executing Python scripts in a containerized environment.
Why Use Docker for Python Scripts?
Before jumping into the “how,” I think it’s helpful to understand the “why.” Docker allows you to isolate your Python environment, which means you won’t have to worry about version conflicts or missing libraries. Whether you’re working on a small script or a larger project, Docker ensures your code runs consistently across different systems.
Setting Up Your Python Script
The first step is to have a Python script ready to execute. For demonstration purposes, let’s create a basic script that prints a message.
# script.py
print("Hello from Docker!")
Save this file in a directory that you’ll use to build your Docker container. It’s important to keep your project organized, so place your Python script alongside any other files you’ll need.
Supremacy: AI, ChatGPT, and the Race that Will Change the World
$2.99 (as of January 11, 2025 10:31 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Co-Intelligence: Living and Working with AI
$13.78 (as of January 11, 2025 10:31 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Teeind USB Type C Cable Fast Charging, Tpc001 5 Pack(6Ft 3A) Braided C Charger Cables Compatible with Samsung S10e/note 9/s10/s9/s8 Plus/A80/A50/A20
$9.99 (as of January 9, 2025 10:16 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Writing the Dockerfile
To execute a Python script in Docker, you need a Dockerfile. This file defines the environment your script will run in. Here’s an example of what a simple Dockerfile might look like:
# Use the official Python base image
FROM python:3.9-slim
# Set the working directory
WORKDIR /app
# Copy the current directory contents into the container
COPY . /app
# Specify the command to run the Python script
CMD ["python", "script.py"]
Here’s what each line does:
FROM python:latest
specifies a lightweight Python image as the base for your container.WORKDIR /app
sets the working directory inside the container to/app
.COPY . /app
copies all the files from your current directory into the container’s/app
directory.CMD ["python", "script.py"]
tells Docker to execute your Python script when the container runs.
Save this file in the same directory as your script.py
.
Building the Docker Image
Once your Dockerfile is ready, you’ll need to build a Docker image. Think of an image as a snapshot of your container environment, complete with all the dependencies and files your script needs.
To build the image, open a terminal in your project’s directory and run:
docker build -t python-script .
The -t python-script
flag names the image python-script
, making it easier to reference later. The .
at the end tells Docker to use the current directory as the build context.
If everything is configured correctly, Docker will generate the image and display a series of build steps in your terminal. Once it’s finished, you’ll have a reusable image that contains your script.
Running Your Python Script in Docker
Now that you have an image, running the script is straightforward. Use the following command:
docker run python-script
When you run this command, Docker creates a container from your image and executes the script.py
file. If your script prints output to the terminal, you’ll see it here.
For example, if your script contains:
# script.py
print("Hello from Docker!")
The output will be:
Hello from Docker!
Dynamically Running Scripts Without Rebuilding
Rebuilding an image every time you modify a script can be tedious. Thankfully, there’s a faster way to execute Python scripts dynamically. You can mount your current directory to a Docker container and run the script without updating the image.
Here’s the command to do that:
docker run --rm -v $(pwd):/app -w /app python:latest python script.py<br>
Let’s break it down:
--rm
: Automatically removes the container after it stops.-v $(pwd):/app
: Mounts your current directory to/app
in the container.-w /app
: Sets the container’s working directory to/app
.python:latest python script.py
: Specifies the base Python image and runs the script directly.
This approach allows you to modify your script locally and test it in the Docker environment without rebuilding the image.
Managing Dependencies
If your script requires additional Python libraries, you can include them in your Docker image. Create a requirements.txt
file listing the libraries you need. For example:
requests
numpy
Then, update your Dockerfile to install these dependencies:
# Use the official Python base image
FROM python:3.9-slim
# Set the working directory
WORKDIR /app
# Copy the current directory contents into the container
COPY . /app
# Install dependencies
RUN pip install -r requirements.txt
# Specify the command to run the Python script
CMD ["python", "script.py"]
Rebuild your image using the docker build
command, and Docker will install the specified libraries during the build process.
Cleaning Up Docker Containers and Images
Over time, you may accumulate unused Docker images and containers. To keep your system clean, it’s a good idea to remove them when they’re no longer needed.
Here are a few commands that can help:
- List all containers:
docker ps -a
- Remove a container:
docker rm <container_id>
- List all images:
docker images
- Remove an image:
docker rmi <image_id>
Using these commands regularly ensures you don’t run out of disk space.
Final Thoughts
Running Python scripts in Docker opens up a world of possibilities for development and deployment. Whether you’re creating quick prototypes or working on complex projects, Docker provides a consistent and reliable environment for your code.
By following the steps above, you can efficiently set up, execute, and manage your Python scripts in a containerized environment. With Docker, there’s no need to worry about dependency conflicts or version mismatches. Everything just works as intended.