I am getting the following error after running docker compose up and going in 0.0.0..:8000/docs to use a get method, in a fastapi project,
The .env file content
MONGODB_URL = mongodb://localhost:27017/
MONGO_HOST = "0.0.0.0"
MONGO_PORT = 27017
MONGO_USER = ""
MONGO_PASS = ""
DATABASE_NAME = "myDatabase"
TEST1_COLLECTION="TEST1_COLLECTION"
TEST2_COLLECTION="TEST2_COLLECTION"
TEST3_COLLECTION="TEST3_COLLECTION"
The Dockerfile content:
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
COPY ./requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
COPY ./app /app/app
WORKDIR /app/app/
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
The docker-compose.yml content
version: "3.9"
services:
app:
build: .
command: uvicorn app.main:app --host 0.0.0.0
ports:
- "8000:8000"
depends_on:
- db
db:
image: mongo
ports:
- "27017:27017"
volumes:
- ./data:/data/db
What am I doing wrong, cause I just need to use the environment variables in docker and run the application?
2
Answers
I believe @MatsLindh might be right. You need to address the host of another container with running instance of MongoDB inside the Docker internal network (which is
db
container in your case).Try using
MONGODB_URL = mongodb://db:27017/
add
container_name
to db service in docker-compose, and then use it’s name as host when connecting to in python code.eg.