Alpha Coder

How to connect to a host’s database from inside a Docker container

There are several ways to interact with a DB when developing using Docker:

  1. Connect to an online DB instance.
  2. Connect to a local DB running in another container.
  3. Connect to a local DB running on a host machine (e.g your laptop).

The first option can be easy and fast to setup i.e if you’re using a managed DB service. But these conveniences come at a monetary cost. Plus, you won’t be able to develop without an internet connection.

While the second and third options are similar in the sense that the DB runs locally, using a DB running on the host might be a more convenient option if you have that already setup, or if you don’t want to have to mount a volume on the host in order to persist your data or run an additional container.

Connecting to a host DB from a container via localhost doesn’t work because both container and host have their own localhosts. When you try to connect to localhost, it fails because no DB instance is running in the container’s localhost as you might imagine. You need to go outside the container by using your computer’s internal IP address.

You can point to your host’s DB by setting the following environment variable in your container for instance.

Docker for Mac/Windows:



DB_HOST=$(ip route show default | awk '/default/ {print $3}')

Need help getting something to work in your project? Try Alpha Coder Support!

Subscribe to the Alpha Coder Newsletter!

Get timely updates on new articles, courses and more from Nicholas Kajoh. Unsubscribe anytime.

Enjoy the content on Alpha Coder? Please buy me a coffee. 😊

Previous post: Here's a quick Elasticsearch-Kibana setup via Docker for development

comments powered by Disqus