14

I have an API running on my host machine on port 8000. Meanwhile, I have a docker compose cluster with one container that's supposed to connect said API. To get the url for the request, I use "host.docker.internal:8000" on my windows machine and it works wonderfully. However, I have a linux deployment server and in there, "host.docker.internal" doesn't resolve to anything, causing a connection error to the API. I saw on another post on stackoverflow, that you solve this on linux by adding the following on your docker-compose.yaml

services: service_name: extra_hosts: - host.docker.internal:host-gateway 

This added the docker0 IP to /etc/hosts, but when I try to do a GET request, the resulting message is:

Failed to connect to host.docker.internal port 8000: Connection refused

I'm really confused right now. I don't know if this is a firewall issue, a docker issue, a docker compose issue, a docker on linux issue. Please help...

8
  • 12
    Make sure your API binds to 0.0.0.0 and not to localhost. If it binds to localhost, it won't accept connections from containers. Commented Apr 13, 2022 at 21:31
  • This worked perfectly! Thank you. I just changed the API binding and everything started working. Commented Apr 14, 2022 at 2:19
  • @Eddysanoli it would be nice to know what exactly did you do to get it work. Commented Jul 11, 2022 at 11:16
  • So previously my API was listening for requests on localhost. After changing the API so that it listens on 0.0.0.0, everything worked with the setup described above. Commented Jul 12, 2022 at 6:12
  • 1
    In my case, binding to 0.0.0.0 did not fix the issue but binding to 127.0.0.1 did. Leaving this here incase it can help someone else Commented Sep 16, 2023 at 15:13

3 Answers 3

19

Credit to @Hans Kilian:

  • Add extra_hosts to docker-compose file
  • Change URL to use host.docker.internal instead of localhost
  • Change service to serve on 0.0.0.0 instead of localhost
Sign up to request clarification or add additional context in comments.

Comments

9

I had a similar problem and got it working by making sure that my tunnel accepted connections from everywhere.

Before:

ssh -N -L 5435:endpoint.rds.amazonaws.com:5432 [email protected] 

After:

ssh -N -L 0.0.0.0:5435:endpoint.rds.amazonaws.com:5432 [email protected] 

Comments

0

Just in case anyone encounters a similar issue, if one of your containers has a wsgi/usgi server (uvicorn, gunicorn, etc) make sure that wherever you start such web server, play around with setting any bind argument or host argument to both 127.0.0.1 and 0.0.0.0

for example in my fastapi server, when I did uvicorn.run, I had to pass 0.0.0.0 so other containers would be able to interact with it, passing none, or other, did not help.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.