简体   繁体   中英

How to correctly install custom package in Docker with docker-compose?

I am building a flask api and want to create a docker image of it. However, when I do docker-compose run (after build), it cannot find the module.

Error:

api_1  | Traceback (most recent call last):
api_1  |   File "app.py", line 6, in <module>
api_1  |     from api.classify.classify import get_prediction
api_1  | ModuleNotFoundError: No module named 'api'

My folder structure looks like this:

- api
-- classify
--- classify.py
-- app.py
-- Dockerfile
-- requirements.txt
-- setup.py

The setup.py looks like this:

from setuptools import setup, find_packages


setup(
    name='image_api',
    keywords='',
    version='0.1',
    packages=find_packages()
)

And the Dockerfile looks like this:

FROM python:3
WORKDIR /user/src/app
ENV PYTHONPATH=/api
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python setup.py install
CMD ["python", "app.py"]

How do I fix this and what is best practice to install custom packages when building a Docker image?

You should never over-write PYTHONPATH like that, nstead append your path, or the system will not find the installed Python packages.

You can do either of the following to make it work:

  1. RUN export PYTHONPATH="$PYTHONPATH:/api"
  2. ENV PYTHONPATH="$PYTHONPATH:/api"

Also your Dockerfile should be on api level, it wont be able to look for it in the present directory structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM