I am trying to containerize a very simple Flask API that connects to mongodb. For the API’s output, I am using the pandas module. However, when I run ‘docker-compose up’, I get the following error:
app_1 | Traceback (most recent call last):
app_1 | File “app.py”, line 6, in
app_1 | import pandas as pd
app_1 | ModuleNotFoundError: No module named ‘pandas’
This is my dockerfile:
FROM python:3.8 ADD . /app WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt
And this is my docker-compose.yml:
app:
build: .
command: python -u app.py
ports:
- "5000:5000"
volumes:
- .:/app
links:
- db
db:
image: mongo:latest
My requirements.txt is as follows:
pymongo==3.11.4 Flask==1.1.2 pandas==1.1.3
Since I have pandas in the requirements.txt, shouldn’t the container have the module? I’m not getting this error for pymongo or Flask, which is why I am curious. I’m fairly new to Docker, so any help would be much appreciated.
Advertisement
Answer
A couple of things:
DOCKERFILE
FROM python:3.8 WORKDIR /app ADD . . COPY requirements.txt . RUN pip install -r requirements.txt ENTRYPOINT ["python","app.py"]
ENTRYPOINT (and CMD)
You would be better placed running the Python app from within the container. Add: ENTRYPOINT ["python","app.py"] to the end of the Dockerfile.
NOTE Docker
ENTRYPOINTis the default (entrypoint) when running the container. It’s a good practice to set this to the binary (i.e.python app.py) that you want to run when you run the container. DockerENTRYPOINTcan be overridden with Docker Composeentrypoint. There’s alsoCMD. It’s good practice to set this to the default arguments and flags that you want to run when you run the container. In thedocker-compose.yml,commandoverrides DockerCMD.
Then you can run the container standalone to test it:
docker build --tag=68567602:v1 --file=./Dockerfile . docker run --interactive --tty --rm --publish=5000:5000 68567602:v1
WORKDIR
In the Dockerfile, it’s a good idea to set the WORKDIR first to save duplicating the reference, i.e.
docker-compose.yml
app:
build: .
ports:
- "5000:5000"
db:
image: mongo:latest
command
The docker-compose.yml need not include command unless you want to override the container’s CMD settings
volumes
The docker-compose.yml should not overwrite the container’s /app directory with your host’s /app directory. Doing this overwrites the e.g. pip install that you ran and is causing the problem
links
I think you don’t want the links entry. Your python app can reference the MongoDB service by the name you gave it db