3

I have a python script in my local machine.The file is not in the docker file directory.Is it possible to reference the path of python script inside the docker file and we able to run the script while creating container

1
  • 1
    You should just be able to run the script, ./script.py or python3 ./script.py, without involving Docker. Do you have a more specific setup that needs Docker? Commented Sep 3, 2021 at 14:34

1 Answer 1

1

See docker build --help:

Usage:  docker build [OPTIONS] PATH | URL | -\
Options:
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
  • The PATH here is build context which usually you will specify as ., means current dictory.
  • Usually you won't specify -f, means it will use Dockerfile in $PATH(Usually . as current folder)

When docker build, docker will compress all items in build context, then pass it to build daemon, all files outside of build context can't be accessed by Dockerfile.

So, for your scenario, you have to change build context to the folder which has py script in it, or the parent folder. Then, specify Dockerfile explicitly.

A minimal example as next for your reference.

Folder structure:

cake@cake:~/20210904$ tree
.
├── docker
│   └── Dockerfile
└── run.py

1 directory, 2 files

run.py:

print("hello")

docker/Dockerfile:

FROM python:3
COPY run.py /
RUN python run.py

Execution:

cake@cake:~/20210904/docker$ docker build -t abc:1 -f Dockerfile ..
Sending build context to Docker daemon  3.584kB
Step 1/3 : FROM python:3
 ---> da24d18bf4bf
Step 2/3 : COPY run.py /
 ---> 6a4c4a76a7fb
Step 3/3 : RUN python run.py
 ---> Running in 4b736175e410
hello
Removing intermediate container 4b736175e410
 ---> 951dd3de7299
Successfully built 951dd3de7299
Successfully tagged abc:1

Expalination:

  • Above change build context PATH to .. to have ability to access run.py
  • Now, the Dockerfile no longer the default PATH/Dockerfile, so we should change it to Dockerfile which means it in current folder.
  • COPY run.py / implict means copy the file from PATH/run.py.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.