Docker expose link to host machine
I am using a docker-compose.yml file for an application service and a database service:
version: '2' services: app-service: image: app-image container_name: app-container ports: - "5000:5000" networks: - my-network links: - db-service db-service: image: db-image container_name: db-container ports: - "5432:5432" networks: - my-network networks: my-network: driver: bridge
The application service connects to the database using a connection string with the db-service as host:
That works fine on the running app container but I also need to access the database using the same connection string from my host machine. (for database migrations during development)
I thought about adding a route to my host machine:
db-service -> localhost But this is not a good solution since it depends on the host operating system.
I tried to use localhost in the connection string since my host machine then connects to the database container. But obviously the application container will not connect any more.
I also played around with network_mode settings and network driver in the compose file but had no luck with that.
How can I use the same hostname in a container like in my host machine?
One Solution collect form web for “Docker expose link to host machine”
The only way you could use the same connection string for both your app-service and your host would be to update your host’s
/etc/hosts file with:
(or use your if you’re running on Docker machine)
But this solution may not be the cleanest one.
The best one would, IMO, be not to use the same connection string.