1

I have two python files a.py and b.py, the dir structure is like this:

  • files(dir)

    • main(dir)
      • a.py
      • Dockerfile
    • b.py

In a.py, there is some code like this:

import sys
sys.path.append('..')
import b

I can run it well through command line. But failed to run it with docker. Here is the code for building and running the docker image:

the Dockerfile:

FROM python:3.6
ADD a.py /.
WORKDIR /.
ENV PYTHONPATH /files/
CMD [ "python3", "a.py" ]

Commands for building the image:

# cd /files/main
# docker build -t a:1.0 .

The image was built successfully and the commands for running the image:

# docker run --name a a:1.0

It gives me:

Traceback (most recent call last):   
 File "a.py", line 3, in <module>
   import b
ModuleNotFoundError: No module named 'b'

My question is, given this example, how can I build and run the image in the correct way?

1
  • b.py isn't inside the container as you're only copying the contents of one script and not the whole directory. You need to copy at least all modules you want to use in order to import them Commented Apr 23, 2019 at 9:30

2 Answers 2

1

Change your Dockerfile to copy both a.py & b.py-

FROM python:3.6
ENV PYTHONPATH /files/
WORKDIR /app
COPY main/a.py b.py ./
CMD [ "python3", "a.py" ]

Run docker build from outside the main directory -

$ docker build -f main/Dockerfile -t a:1.0 .
$ docker run --name a a:1.0

Try it out!

Sign up to request clarification or add additional context in comments.

5 Comments

b.py must be in the files folder, because I have some other script using b.py, I'd like to keep my file structure.
You mean b.py is inside files and main is also inside files? Can you please edit your question to help us with the directory structure. Current representation looks bit unclear.
Updated the answer. See, if it helps!
Maybe change WORKDIR /app to WORKDIR /files?
Yes. You can remove the ENV statement to reduce #layers for the image.
0

You need to put b.py inside the Docker context and copy it into container. You can look at the official documentation if you want to learn more about the build context.

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.