본문 바로가기
Python

[Python] Running Python with Docker

by llHoYall 2021. 8. 28.

In this posting, we will be looking into running python with docker.

Install Docker

I will use docker on MAC with homebrew.

$ brew install --cask docker

Please refer to the official site for installing docker if you want to use it another way or use another OS.

https://docs.docker.com/get-docker/

 

Get Docker

 

docs.docker.com

Now, run the docker.

Then docker is automatically downloaded and you can see this screen.

Python on Docker Hub

You can find the supported python on the official docker hub.

https://hub.docker.com/_/python

 

Python - Official Image | Docker Hub

Quick reference Supported tags and respective Dockerfile links (See "What's the difference between 'Shared' and 'Simple' tags?" in the FAQ.) Simple Tags 3.10.0rc1-bullseye, 3.10-rc-bullseye, rc-bullseye 3.10.0rc1-slim-bullseye, 3.10-rc-slim-bullseye, rc-sl

hub.docker.com

 

Running Python with Docker

Try to input this command via the terminal.

$ docker run -it --rm python:3.9.6 python3 -V

I used Python v3.9.6 and ran a command "python3 -V" that gets the version of used Python.

The first time you run this command, it takes a long time because docker downloads a container first.

But it is faster after at this time because docker just uses the downloaded container.

Running Local Python Script with Docker

Now, let's take a look at how to use local python scripts with docker.

# test.py

print("Hello, Python with Docker")

First, prepare the test script.

Now, run this command.

$ docker run -it --rm -v $(pwd):/usr/src/app -w /usr/src/app python:3.9.6 python3 test.py

I mounted a directory using -v and -w options and ran a command "python3 test.py".

It is so easy!

Running Python with 3rd Party Module on Docker

You can install 3rd party module using docker.

Let's make a script using numpy.

# test.py
import numpy as np

arr = np.array([1, 2, 3])
print(arr)

Run this command.

$ docker run -it --rm -v $(pwd):/usr/src/app -w /usr/src/app python:3.9.6 bash -c 'pip install numpy; python3 test.py'

I used bash command for this command.

Running Python with Environment Variable on Docker

You can also use specific environment variables on docker.

# test.py
import sys

print(sys.path)

Let's use our own PYTHONPATH.

$ docker run -it --rm -v $(pwd):/usr/src/app -w /usr/src/app -e PYTHONPATH=/usr/bin:/bin python:3.9.6 python3 test.py

This can be achieved using -e option.

In Conclusion

I prefer the virtual environment to docker, but using docker gives us convenience in many cases.

It has less flexibility but we can easily test our program on various version of python.

It is also easy to automate.

I hope you would learn it in this posting and feel free to use it when you need it.

'Python' 카테고리의 다른 글

[Python] logging  (0) 2021.10.25
[Python] Docstring  (0) 2021.10.18
[PyQt6] Getting Started  (0) 2021.08.10
[Python3] typing module  (0) 2021.07.03
[Python] Decorator  (0) 2021.06.29

댓글