0

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,enter image description here

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?

andu
  • 413
  • 1
  • 4
  • 10
  • Do you really use an empty password and username or did you just removed it for the question? – Enak Aug 08 '22 at 12:04
  • 1
    `mongodb://db:27017/` ? `localhost` refers to inside the container, you need to reference the other running container over docker's network. – MatsLindh Aug 08 '22 at 12:17
  • 1
    You seem to have attached a hard-to-read PNG file in place of the error message; can you [edit] the question to include the text of the error instead? The `MONGODB_URL=localhost` looks suspicious to me in that it will tell the `app` container to connect to itself and not the `db` container; see perhaps [pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111\] Connection refused](https://stackoverflow.com/questions/49499438/pymongo-errors-serverselectiontimeouterror-localhost27017-errno-111-connect). – David Maze Aug 08 '22 at 12:17

2 Answers2

1

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/

Herman L
  • 36
  • 1
0

add container_name to db service in docker-compose, and then use it's name as host when connecting to in python code.

eg.

mongodb://root:example@container_name:27017/?authMechanism=DEFAULT
Vedprakash Singh
  • 522
  • 8
  • 22