DEV Community

Cover image for Accessing Host Services from Docker Containers

Accessing Host Services from Docker Containers

Mohammad Javad Naderi on February 18, 2024

Accessing a host service from within a Docker container is a common requirement. For instance, you might have a HTTP proxy running on the host syst...
Collapse
 
suriya786 profile image
suriya786

Thank you for the great article.

Collapse
 
mjnaderi profile image
Mohammad Javad Naderi

You're welcome. :)

Collapse
 
itismoej profile image
Mohammad

Awesome! I used it to port my proxy, which was alive in my host machine, to my containers without giving them access to the host network. Thanks Mohammad Javad :)

Collapse
 
mjnaderi profile image
Mohammad Javad Naderi

You're welcome! I'm glad that this post was helpful to you.

Collapse
 
jquintanilla4 profile image
jquintanilla4

Mate, cheers for this. I've been looking for a solution like this for days.

Collapse
 
mjnaderi profile image
Mohammad Javad Naderi

Thank you for your feedback!

Collapse
 
ledlamp profile image
Lamp

You can bind the database server to both 127.0.0.1 and 172.17.0.1. SMH.

Also. If you're connecting on the same host it's better to use UNIX sockets. Just mount the socket dir into the container.

volumes:
  - "/run/postgresql:/run/postgresql"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mjnaderi profile image
Mohammad Javad Naderi • Edited

Thanks for your feedback.

You can bind the database server to both 127.0.0.1 and 172.17.0.1.

I mentioned this solution in the article: "The other workaround is to bind the database server to 172.17.0.1, but other apps that rely on 127.0.0.1:5432 will break."

I know that PostgreSQL can bind to multiple IP addresses (so we can bind to both 127.0.0.1 and 172.17.0.1), but I did not mention that our database is PostgreSQL. Plus, "database" is just an example. It could be any service, for example, an HTTP proxy, or anything else that other apps expect to be available at 127.0.0.1 and that service may have no configuration to bind to multiple IP addresses or use UNIX sockets.

And what if the IP 172.17.0.1 changes in a new version of Docker? This solution does not rely on hard-coded IP 172.17.0.1.

Update: I edited the post and made it more general (removed "database" and 5432).

Collapse
 
amitpatelbotreeconsulting profile image
Amit Patel

Saved many hours. It works as it claims. Thanks!!!

Collapse
 
enilec_vepres profile image
Enilec

hanks a lot, you saved me with this!

Collapse
 
computerhirn profile image
Ralf • Edited

Let me thank you for that great article.

Could you please point out how to use socat, connecting to port 53 UDP on a host running a podman container listening to 5353 UDP?