How to Run a Simple Python Program in a Docker Container

Date: 2024-09-30 | create | tech | python | docker | containers |

Dealing with programming environment setup and differences from machine to machine is annoying. That's why I prefer to develop inside containers - they're the closest thing we have to deterministic builds for any kind of program.

In this post we'll walk through how to run a simple Python program in a Docker container.

The Python Program

First we'll look at the Python Program. It's a very simple hello world script.

  • You run it
  • It prints out hello world

main.py:

print("hello world")

Running a Python Program in Docker

I'm going to assume that you already have Docker setup on your machine - if not, go do that.

Now all we have to do is tell Docker how to create this container. We do that with a Dockerfile - it tells Docker what steps to run and how to start the program.

Our Dockerfile does a few things:

  • Clone an official Python image - here we're using python 3.12 but you can use a different version if you want
  • Copy our source code into the container
  • Install any requirements - as listed in our requirements.txt
  • Run our Python program - python ./main.py

Dockerfile:

# Use base Python image
FROM python:3.12

# Copy repo into container
COPY . . 

# Install any requirements
RUN pip install --no-cache-dir -r requirements.txt

# Run Python program
CMD [ "python", "./main.py" ]

We can then run our program by spinning up our Dockerfile:

docker run --rm -it $(docker build -q .)

(this command basically cleans up any existing image, builds the docker file in our current directory, and opens it in interactive mode)

Next

That should get you started running Python programs inside a Docker container. This is how I'm running a lot of my own experimental Python programs now that Replit removed it's free tier (sad!)

Want the full project source code? HAMINIONs members get access to this project's full source code (github) as well as dozens of other example projects.

If you liked this post you might also like:

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.