6

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...

Eddysanoli
  • 481
  • 2
  • 8
  • 17
  • 10
    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. – Hans Kilian Apr 13 '22 at 21:31
  • This worked perfectly! Thank you. I just changed the API binding and everything started working. – Eddysanoli Apr 14 '22 at 02:19
  • @Eddysanoli it would be nice to know what exactly did you do to get it work. – cheack Jul 11 '22 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. – Eddysanoli Jul 12 '22 at 06:12
  • @cheack I tried this by, for my project, which is a sort of wsgi python server, changing the hosting url in a settings file somewhere from `localhost:9000` to `0.0.0.0:9000` directly, which caused my python server to run on `0.0.0.0` instead of `localhost`. However, I was still getting `connection refused` errors, so the solution may not work for everyone. – Caleb Jay Jul 18 '22 at 08:57
  • Oh, thats unfortunate. Sorry to hear that. Did you manage to solve it in any other way @CalebJay? – Eddysanoli Jul 18 '22 at 15:51
  • No, sorry. I'll update here if I do. We're still trying to get our application working on linux machines, something about the way docker handles networks is different on osx vs linux distros it seems. – Caleb Jay Jul 20 '22 at 06:30

2 Answers2

9

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
A.Wan
  • 1,818
  • 3
  • 21
  • 34
7

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 admin@machine.ip

After:

ssh -N -L 0.0.0.0:5435:endpoint.rds.amazonaws.com:5432 admin@machine.ip
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43