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 Answer
See docker build --help:
Usage: docker build [OPTIONS] PATH | URL | -\ Options: -f, --file string Name of the Dockerfile (Default is 'PATH/Dockerfile')
- The
PATHhere isbuild contextwhich usually you will specify as., means current dictory. - Usually you won't specify
-f, means it will useDockerfilein $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
PATHto..to have ability to accessrun.py - Now, the
Dockerfileno longer the defaultPATH/Dockerfile, so we should change it toDockerfilewhich means it in current folder. COPY run.py /implict means copy the file fromPATH/run.py.
./script.pyorpython3 ./script.py, without involving Docker. Do you have a more specific setup that needs Docker?