Skip to content

Instantly share code, notes, and snippets.

@markgreene74
Last active September 27, 2023 18:34
Show Gist options
  • Select an option

  • Save markgreene74/53805ba9477a76dcd302afed6c8315ba to your computer and use it in GitHub Desktop.

Select an option

Save markgreene74/53805ba9477a76dcd302afed6c8315ba to your computer and use it in GitHub Desktop.

A simple Python in docker workflow

Build the container

Create the dockerfile

$ cat ~/docker/Dockerfile 
FROM python:3
RUN apt-get update && apt-get install -y vim
RUN python -m pip install black pytest
CMD [ "python" ]

Ignore the CMD I usually just drop into a shell, see below.

Move into the directory where the Dockerfile is located and build the container

$ docker build -t mypython .

...
Removing intermediate container 0449ae0049da
 ---> b3786bb79d9d
Successfully built b3786bb79d9d
Successfully tagged mypython:latest

Congratulations! Your container is ready!

Run the container

Now you can run the container without any fancy volume mapping and just drop into a bash shell

$ docker run -it --rm mypython bash

Or you can run the container with the volume option so you can access/run the files in your current directory from within the container

$ cd ~/tmp && docker run -v "$PWD":/usr/src/myapp -w /usr/src/myapp -u $(id -u):$(id -g) -it --rm mypython bash
root@00182c4cb118:/usr/src/myapp# ls
root@00182c4cb118:/usr/src/myapp# vim something.py
root@00182c4cb118:/usr/src/myapp# black something.py 
reformatted something.py
All done! ✨ 🍰 ✨
1 file reformatted.
root@00182c4cb118:/usr/src/myapp# python something.py 
Hello world
root@00182c4cb118:/usr/src/myapp# python
Python 3.8.2 (default, Feb 26 2020, 14:58:38) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
root@00182c4cb118:/usr/src/myapp# exit

This makes easy, for example, to run pytest or use black on a script and keep everything clean without having to worry about envs. It als fits very well into my workflow: drop into the container to run/test the script, drop out of the container to continue working (git commit, push etc).

Useful links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment