close

How to run my python script on docker?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to run my python script on docker in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to run my python script on docker?

  1. How to run my python script on docker?

    mkdir /home/pi/Desktop/teasr/capturing
    Copy your dockerfile and script in there and change the current context to this directory.

  2. run my python script on docker

    mkdir /home/pi/Desktop/teasr/capturing
    Copy your dockerfile and script in there and change the current context to this directory.

Method 1

Alright, first create a specific project directory for your docker image. For example:

mkdir /home/pi/Desktop/teasr/capturing
Copy your dockerfile and script in there and change the current context to this directory.

cp /home/pi/Desktop/teasr/capturing.py /home/pi/Desktop/teasr/dockerfile /home/pi/Desktop/teasr/capturing/

cd /home/pi/Desktop/teasr/capturing
This is for best practice, as the first thing the docker-engine does on build, is read the whole current context.

Next we’ll take a look at your dockerfile. It should look something like this now:

FROM python:latest

WORKDIR /usr/local/bin

COPY capturing.py .

CMD [“capturing.py”, “-OPTIONAL_FLAG”]
The next thing you need to do is build it with a smart name. Using dots is generally disencouraged.

docker build -t pulkit/capturing:1.0 .
Next thing is to just run the image like you’ve done.

docker run -ti –name capturing pulkit/capturing:1.0
The script now get executed inside the container and will probably exit upon completion.

Edit after finding the problem that created the following error:

“standard_init_linux.go:195: exec user process caused “exec format error”

There’s a different architecture beneath raspberry pi’s (ARM instead of x86_64), which COULD’VE BEEN the problem, but wasn’t. If that would’ve been the problem, a switch of the parent image to FROM armhf/python would’ve been enough.

BUT! The error kept occurring.

So the solution to this problem is a simple missing Sha-Bang on top of the python script. The first line in the script needs to be #!/usr/bin/env python and that should solve the problem.

Method 2

Going by question title, and if one doesn’t want to create docker image but just want to run a script using standard python docker images, it can run using below command

docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:3.7-alpine python script_to_run.py

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read