I am unable to connect to my database inside Docker when I try to trigger an SQL query through an API call. When I do it without Docker, it works.
Details:
When I start the uvicorn server directly with the following command:
uvicorn api:app --host 0.0.0.0 --port 5001 --reload
My uvicorn server starts, and is accessible at http://localhost:5001/
. It has an endpoint fetch_data
, which when called, executes an SQL select query and the endpoint returns the data as a JSON -> this works fine
Now, I run a docker container, which has a kafka service and the same uvicorn server running simultaneously. The docker commands are as follows:
docker build . -t container_name -f docker/Dockerfile
docker run -p 5001:5001 container_name
(I map port 5001 to access the API externally through the browser at localhost)
Both the kafka messages and the API trigger some SQL query. The SQL query works when triggered via kafka message within docker (it returns data, which means that the app is able to connect to the database within the docker container), but when triggered through the API, it is not able to connect to the database -> this doesn't work
In the latter case, I start the uvicorn server directly in python like this (if that makes a difference at all):
uvicorn.run(app=app, host='0.0.0.0', port=5001)
I checked through the logs and it seems this line gets stuck indefinitely (it doesn't give any error):
connection = DriverManager.getConnection(connection_url, user, password)
I can provide additional information if required, but can anyone provide me a clue as to why my API, when triggered within the docker container, might not be able to interact with the database when the connection is working when triggered through a kafka message?
The swagger page of the API is accessible at http://localhost:5001/
, and it shows all the endpoints, so I can assure that the API is working fine when I start the uvicorn server within Docker.
Any help would be appreciated. Thanks in advance.