0

I am trying to deploy my FastAPI app to a docker container (P.S. I am a beginner in using docker). I used the below code. Without the DB, this code is working fine in the docker container. However, when I try to try to connect to DB, the path "URL:port/" is showing connection refused. I used the exact steps as mentioned in uvicorn-gunicorn-fastapi-docker

from fastapi import FastAPI
from pymongo import MongoClient


app = FastAPI()

client = MongoClient('localhost', port=27017)
db = client.safetypointer


@app.get("/")
def read_root():
    all_users = db.users.find({}, {"_id":0})
    return {"Hello": "World" , "allUsers": all_users}
robert patrik
  • 79
  • 3
  • 13
  • are you sure your fastapi container can see the mongo db? – Brown Bear Aug 22 '20 at 12:03
  • How can I test this? – robert patrik Aug 22 '20 at 12:06
  • Where is the database running? `localhost` in Docker usually means "this container", and your database is probably somewhere else. – David Maze Aug 22 '20 at 12:15
  • The mongo database is running in localhost. How can I make the container to see the mongo db? – robert patrik Aug 22 '20 at 12:25
  • Does this answer your question? [From inside of a Docker container, how do I connect to the localhost of the machine?](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach) – Brown Bear Aug 22 '20 at 15:02
  • No. I have a mongo container and another fast API container. I want to connect them so that the fast API container listens the mongo container. – robert patrik Aug 23 '20 at 07:27
  • You should use your host ip instead of localhost. Try setting your machine's ip. https://itsfoss.com/check-ip-address-ubuntu/ for ubuntu – lsabi Aug 23 '20 at 15:31

1 Answers1

0

Local host should likely be replaced with the name of your mongo container. I would also recommend taking a look at docker-composer as it can make deploying two connected containers easier.

Here is a link to an example with flask it would be similar with fastapi: awesome-compose