Skip to content
Advertisement

How to run python code from linux via a docker containing a specific python version

I have a linux server running in which I want to be able to run some python scripts. To do so, I created a docker image of python (3.6.8) with some specific dependencies to run my code.

I am new to linux command line and need help on how to write a line that would run a given python script based on my docker (python 3.6.8)

My server’s directory structure looks like this :

Server structure

My docker is named geomatique_python and its image is located in docker_image.

As for the structure of the code itself, I am starting from scratch and am looking for some hints and advices.

Thanks

Advertisement

Answer

I’m very much for a all the things in docker approach. Ref. your mention of having specific versions set in stone, the declaritive nature of docker is great for that. You can extend an official python docker image with your libraries then bind-mount the folders into your container during the run. A minimal project might look like:

.
├── app.py
└── Dockerfile

My app.py is a simple requests script:

#!/usr/bin/env python3                                                                                                                                                                                  

import requests

r = requests.get('https://api.github.com')

if r.status_code == 200:
    print("HTTP {}".format(r.status_code))

My Dockerfile contains the runtime dependencies for my app:

FROM python:3.6-slim

RUN python3 -m pip install requests

Note: I’m extending the official python image in this example.

After building the docker image (i.e. docker build --rm -t so:57697538 .) you can run a container from the image bind-mounting the directory that contains the scripts inside the container and execute them: docker run --rm -it -v ${PWD}:/src --entrypoint python3 so:57697538 /src/app.py

Admittedly for python virtualenv / virtualenvwrapper can be convenient however it’s very much python-only whereas docker is language agnostic.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement