Docker Community Forums

Share and learn in the Docker community.

Access Host Port from Container on localhost without --net host

docker

(Freeqaz) #1

Howdy y’all,

I’ve got a question that I haven’t been able to find an answer for on the net so far.

I have a host machine that provides a service (say MySQL) on port 9001. When I run my container, I want to be able to access this service as localhost:9001 in the app running on the container. I want to do this without using --net host and instead have a whitelisted approach.

I’m guessing that I’ll have to do this via IPTables, but I wanted to get a second opinion before I continue. Having the bridge adapter is something that I want to maintain for network isolation.

My goal is to firewall off the Docker container from the rest of the network, with the exception of the port that I whitelist that the Host controls.

For additional context, I might have many services all accessing the same host port (MySQL example) so binding the container’s port the host won’t work (as far as I understand).

Thanks for the help!

Best,
-Free


(David Maze) #2

Why?

Stepping out of Docker land for a moment: many home routers run Linux, and there are alternate firmwares for them, so it’s totally possible to run a service (say MySQL) on your router. When you run an application on your home system, why would you expect to be able to access the database on the router on 127.0.0.1?

On native Linux it’s often possible to refer to the host as 172.17.0.1, but this doesn’t reliably work on other platforms.

Really the best way is to pass in the location of the database server as configuration to your process (could be via environment variables), and to use your host system’s DNS name (if it has one) or a current IP address.

That sounds like you want to run a mysql container, and to put your application and its database on a private Docker network.


(Freeqaz) #3

Hey dmaze,

Thanks for getting back to me!

The reason for this change is because I’m currently using --network host and I’d like to not change all of the code that’s relying on services currently using localhost:9001. Whitelisting what ports get bound to localhost is my current goal.

I do agree that the architecture “smells” and I’d prefer to do this another way (via /etc/hosts or something). If it’s possible to hack this for now, it will give me time to fix this at a lower level.

Best,
-Free


(Freeqaz) #4

I’m going to bump this thread because I still haven’t found a clean answer.