Best 3 Steps To Run a Python Script in a Linux Docker Container
This guide aims to teach you how to Run a Python Script in a Linux Docker Container. As you know, Docker is an excellent choice for containerizing applications and running them in a specific environment. You might have a Python script you want to execute within a Docker container. For this purpose, you can leverage a Dockerfile to define your Python image.
Continue reading to discover how you can achieve this. Here, we use Docker in Ubuntu 22.04 as an example to demonstrate how you can Run a Python Script in a Linux Docker Container.
Because we use Ubuntu 22.04 as our Linux server, you can use the following requirements for this server which are Initial Server Setup and Docker installation on Ubuntu 22.04.
You must log in to your server as a non-root user with sudo privileges. To do this, you can visit this guide on Initial Server Setup with Ubuntu 22.04.
Also, you must have Docker installed on your server. To do this, you can check this guide on Install Docker on Ubuntu 22.04.
Now proceed to the following steps to Run a Python Script in a Linux Docker Container.

Step 1 – Create a Python Script in Linux
First, you must create the Python script that you want to use in the Docker Container. In this guide, we create a Hello World script as an example for you. To do this, you can use your desired text editor like Vi Editor:
vi hello.py
Then, copy the following sample Python script inside the file:
print("Hello, world!")
When you are done, save and close the file.
Step 2 – Create a Dockerfile for Python Script
At this point, you must create a Dockerfile for your Python script. Dockerfile will help you build your Python image and run your script in a Docker container. Just remember to create the Dockerfile inside the directory where you have defined your Python script.
To create your Dockerfile, you can use your desired text editor, here we use vi:
vi Dockerfile
In the file, you can copy the following content as an example:
# Use an official Python runtime as a parent image
FROM python:3.11
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Run hello.py when the container launches
CMD ["python", "hello.py"]
When you are done, save and close the file.
As you can see, we use Python 3.11 as the base image. Copy the contents into the /app directory and run the hello.py script
using the CMD
instruction.
Step 3 – Build and Run Python Script in a Docker Container
In this step of Run a Python Script in a Linux Docker Container, you must build your Docker image for Python. Remember to do these steps in the same directory as your Dockerfile. To build your Docker image, you can use the following command and set a name for it, here we named it testapp.
docker build -t testapp .
This command will use the base image that you have defined in the Dockerfile to build your Docker image.
When it is finished, you will get the following output:
**Output**
[+] Building 0.6s (8/8) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 364B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/python:3.11 0.5s
=> [1/3] FROM docker.io/library/python:3.11@sha256:02808bfd640d6fd360c30 0.0s
=> [internal] load build context 0.0s
=> => transferring context: 9.96kB 0.0s
=> CACHED [2/3] WORKDIR /app 0.0s
=> [3/3] COPY . /app 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:61136d3236e6b4aab3eabcc5df8ea0771ad9cc07b7b8d 0.0s
=> => naming to docker.io/library/testapp 0.0s
Finally, you can use the following docker command to Run a Python Script in a Linux Docker Container:
docker run testapp
This will run and print your Python script in a Docker Container:
**Output**
Hello, world!
Conclusion
At this point, you have learned to Build a sample Dockerfile for Python and Run a Python Script in a Linux Docker Container. As you can see working with Docker is so easy and useful. If you are looking for any help or have an idea, feel free and comment for us.
Hope you enjoy it. For more guides on Docker, you can visit the Docker Tutorials.
Alternative Solutions for Running a Python Script in a Docker Container
While the method described above, using a Dockerfile to build an image, is a standard and recommended approach, there are alternative ways to achieve the same result. These alternatives can be useful in different scenarios, such as when you need a quick solution for testing, or when you want to avoid creating a full Dockerfile.
Alternative 1: Using Docker Run Directly with a Volume Mount
This approach avoids building a dedicated Docker image. Instead, it leverages a pre-existing Python image from Docker Hub and mounts your local Python script into the container. This method is faster for development and testing because you don’t need to rebuild an image every time you change your script.
Explanation:
- We use the
docker run
command with the-v
flag to mount a local directory into the container. The-v
flag takes two arguments, separated by a colon: the host path and the container path. - We specify the Python image we want to use (e.g.,
python:3.11
). - We specify the command to execute inside the container, which in this case is
python /app/hello.py
.
Code Example:
First, ensure your hello.py
script is in a directory (e.g., a directory named my_python_app
). Then, run the following command:
docker run -v $(pwd)/my_python_app:/app python:3.11 python /app/hello.py
Breakdown:
-v $(pwd)/my_python_app:/app
: This mounts your current working directory’smy_python_app
subdirectory (wherehello.py
is located) to the/app
directory inside the container.$(pwd)
expands to the absolute path of your current directory.python:3.11
: This specifies the Python 3.11 image from Docker Hub.python /app/hello.py
: This tells Docker to execute the Python interpreter inside the container, running thehello.py
script located in the/app
directory (which is the mounted volume).
Benefits:
- Faster Iteration: Changes to your script are immediately reflected when you rerun the
docker run
command, without needing to rebuild an image. - Simpler Workflow: Avoids the need to create and manage Dockerfiles for simple scripts.
Drawbacks:
- Dependencies: Relies on the availability of the specified Python image and any necessary system libraries within that image. If your script has dependencies not included in the base image, you’ll need to address that (see below).
- Not Production-Ready: Primarily for development and testing. For production, a Dockerfile is generally preferred for reproducibility and dependency management.
Handling Dependencies:
If your script relies on external Python packages (e.g., using requests
), you’ll need to ensure those packages are available inside the container. You can achieve this by using a Dockerfile with a pip install
step, or by using the volume mount approach along with a virtual environment:
-
Create a
requirements.txt
file in yourmy_python_app
directory listing your dependencies:requests
-
Create a shell script named
run.sh
in themy_python_app
directory with the following content:#!/bin/bash python3 -m venv venv source venv/bin/activate pip install -r requirements.txt python hello.py
-
Make the script executable
chmod +x run.sh
-
Run the container with a volume mount:
docker run -v $(pwd)/my_python_app:/app -w /app python:3.11 bash ./run.sh
-w /app
: This sets the working directory inside the container to/app
.bash ./run.sh
: This executes therun.sh
script, which creates the virtual environment, installs dependencies, and runs your Python script.
Alternative 2: Using Docker Compose for Multi-Service Applications
While not directly related to running a single Python script, Docker Compose becomes invaluable when your Python script is part of a larger application involving multiple services (e.g., a web server, a database). Docker Compose allows you to define and manage these multi-container applications with a single docker-compose.yml
file.
Explanation:
Docker Compose uses a YAML file (docker-compose.yml
) to define the services that make up your application, their dependencies, and how they interact.
Code Example (docker-compose.yml
):
version: "3.9"
services:
web:
image: python:3.11
volumes:
- .:/app
working_dir: /app
command: python hello.py
ports:
- "5000:5000" # Example: if your script starts a web server on port 5000
restart: always # Ensure the container restarts if it crashes
Breakdown:
version: "3.9"
: Specifies the Docker Compose file version.services:
: Defines the services that make up the application. In this simplified example, we only have one service namedweb
.image: python:3.11
: Specifies the Docker image to use for the service.volumes: - .:/app
: Mounts the current directory (containing yourhello.py
script) to the/app
directory inside the container.working_dir: /app
: Sets the working directory inside the container to/app
.command: python hello.py
: Specifies the command to execute when the container starts.ports: - "5000:5000"
: Maps port 5000 on the host machine to port 5000 inside the container (useful if your Python script starts a web server).restart: always
: Configures the container to restart automatically if it crashes.
How to Run:
- Save the above content as
docker-compose.yml
in the same directory as yourhello.py
script. -
Run the following command in the terminal:
docker-compose up -d
docker-compose up
: Starts the services defined in thedocker-compose.yml
file.-d
: Runs the services in detached mode (in the background).
To stop the services, run:
docker-compose down
Benefits:
- Simplified Multi-Container Management: Makes it easy to define and manage complex applications with multiple interconnected services.
- Dependency Management: You can define dependencies between services in the
docker-compose.yml
file, ensuring that services are started in the correct order. - Scalability: Docker Compose can be used to scale individual services within your application.
Drawbacks:
- Overhead for Simple Scripts: For a single, simple script, Docker Compose might be overkill. The volume mount approach (Alternative 1) is often more appropriate.
- Requires Learning Docker Compose: There’s a learning curve associated with understanding Docker Compose syntax and concepts.
These alternative solutions offer flexibility when working with Docker and Python. Choose the approach that best suits your specific needs and the complexity of your application.