简体   繁体   中英

Connection refused to mongodb after running docker compose up

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?

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.

mongodb://root:example@container_name:27017/?authMechanism=DEFAULT

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