'Cannot connect to fast api server at localhost:8000 from my application which is running under a docker container
I a newbie to working with fastapi. I have a main.py inside docker container.When I connect to fastapi using
uvicorn main:app —-reload
from my container.I am prompted to connect to http://127.0.0.1:8000. On copying the address to Firefox I am getting the error:
unable to connect.
How can I connect to fastapi server ?
P.S The git branch I am working from was developed by another colleague so I have little to no idea how was fastapi was set up inside the docker
Solution 1:[1]
You need to use the command
uvicorn main:app --reload --host 0.0.0.0
Your docker container is like a computer, which is independent. Thus it does not allow access from external sources. With the --host option, you allow external connections (outside of localhost from the point of view of the container). Basically, docker's localhost is different from your computer's localhost.
Solution 2:[2]
A workaround solution. Through on deploy app will have public address and webdriver.Remote can take it, in dev it is ok to run selenium locally.
test_my_web.py
import unittest
from selenium import webdriver
import os
from dotenv import find_dotenv, load_dotenv
from webdriver_manager.chrome import ChromeDriverManager
load_dotenv(find_dotenv())
class TestWebListAll(unittest.TestCase):
def setUp(self) -> None:
chrome_options = webdriver.ChromeOptions()
if os.environ.get("LOCAL_DEV"): # == 'True'
self.url = 'http://127.0.0.1:8000/'
self.driver = webdriver.Chrome(ChromeDriverManager().install())
else:
self.driver = webdriver.Remote(
command_executor='http://localhost:4444',
options=chrome_options
)
self.url = 'insert public addres' #
def tearDown(self) -> None:
self.driver.quit()
def test_(self):
self.driver.get(self.url)
print(self.driver.title)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lsabi |
| Solution 2 | Evgene |
