How can I run a Python script in a remote Docker container? How can I run a Python script in a remote Docker container? kubernetes kubernetes

How can I run a Python script in a remote Docker container?


Off the top of my head I can think of two approaches, both of which I've used:

  • If you want the script to start immediately, use CMD or ENTRYPOINT in your Dockerfile to kick off the script at start of the container

So, abstracted, something like this

FROM pythonCOPY myscript.py /tmpCMD ["python", "/tmp/myscript.py"]
  • If you want the script to only run when triggered, say, by an event of web request, "wrap" the Python code inside something like flask, bottle or uwsgi.

This could look like this:

Your wrapper script is mywrapper.py which has:

#!usr/bin/env pythonimport bottleapp = bottle.Bottle()@app.route('/')def main():   call_my_python_code()

In that case your Dockerfile may set this up through exposing a port and then starting the web server:

FROM pythonCOPY wrapper.py runserver.sh myscript.py /tmpEXPOSE 80CMD ["/bin/bash", "-x", "/tmp/runserver.sh" ]

With runserver.sh just setting up the server bit:

#!/bin/bashset -eexec uwsgi --http 0.0.0.0:80 --wsgi-file wrapper.py --callable app