Search code examples
pythondockerflask

How to solve problem with psycopg2 on Docker?


I have an application image that I am trying to run from Docker with the command docker run -p 5000:5000 api

Every time I try to run it gets an error

'File "/usr/local/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 690, in import_dbapi import psycopg2 ModuleNotFoundError: No module named 'psycopg2'.'

Although psycopg2 is installed in the lib directory.

I've tried a lot of solutions, looked through a lot of threads and nothing helps.

ImportError: No module named psycopg2


Solution

  • It seems the problem lies within your Dockerfile. Python couldn't find the module because it hasn't been installed, it might be installed on your machine but not on the container.

    Make sure you install the module on the container at the builder stage.

    At the root of your project directory run pip freeze > requirements.txt. then ensure that your Dockerfile includes the following:

    COPY requirements.txt .
    RUN pip install -r requirements.txt