2

What is best practice to access the host's services within a docker container?

I'd like to access PostgreSQL running on the host within my application which runs in a docker container.

The easiest approach I've found is to use docker container run --net="host" which, based on this answer, behaves as follows:

Such a container will share the network stack with the docker host and from the container point of view, localhost (or 127.0.0.1) will refer to the docker host.

Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the -p or -P docker run option.

Which does not seem to be best practice since the containers should be isolated from the host.

Other approaches I've found are awking the hosts IP. May this be the way to go?

Community
  • 1
  • 1
nintschger
  • 1,786
  • 5
  • 30
  • 45

1 Answers1

4

The best option in this case to treat the host as a remote machine. That way the container will be portable and would not have a strict dependency on network locations when connecting to the database.

In addition to what is mentioned on the drawbacks of using --network=host, this option will tightly couple the container to the host by assuming that the database is found on localhost.

The way to treat the machine as a remote one, is to use standard network constructs such as IP and DNS. Define a new DNS entry for the container that will point to the host where the DB is found using the --add-host option to docker run.

docker run --add-host db-static:<ip-address-of-host> ...

Then inside the container you connect to the database via db-static

yamenk
  • 46,736
  • 10
  • 93
  • 87