In a Docker environment, it is often necessary to access services running on the host machine from inside a container. This can be particularly useful when working with a PostgreSQL database hosted on the host machine. In this post, we will explore the steps required to connect to a Postgres database in the host machine from within a Docker container.

  1. First, let’s determine the IP address of the host machine. Open a terminal and run the following command:

    ip addr show docker0
    

    Make a note of the IP address displayed. By default, it is set to 172.17.0.1 if not manually configured. This IP address will be used to connect to the host’s Postgres database.

    next, we need to find the IP address of the Docker container. Run the following command in the terminal:

    docker network inspect bridge  | jq '.[0].Containers'
    

    Identify the IP address associated with your container and take note of it. We will use this IP address to configure the Postgres server to accept connections from the container.


  2. Now, we need to edit the postgresql.conf file on the host machine. Locate the file and open it in a text editor. Look for the listen_addresses configuration option. There are two possible configurations: To listen for connections from any IP address, set listen_addresses as follows:

    listen_addresses = 'localhost,<your container ip address>'
    

    to listen from localhost and container only

    OR,

    listen_addresses = '*'
    

    to listen from every ip.


  3. Additionally, we need to modify the pg_hba.conf file to accept connections from the container’s IP address. Open the pg_hba.conf file and add the following line:

    host all all <your container ip address>/32  trust
    

    Replace with the IP address of your container. The /32 at the end of the IP address indicates that we want to listen to exactly that IP, not the entire subnet.


  4. Save the configuration files and restart the Postgres service by running the following command:

    systemctl restart postgresql.service
    

With these configurations in place, you can now connect to your host’s Postgres database from within the Docker container. The host IP address for accessing the database will be the IP address of the host machine that we noted earlier, which is 172.17.0.1.

By following these steps, you can seamlessly access a Postgres database hosted on your host machine while working within a Docker environment. This flexibility allows for efficient development and testing workflows without the need for additional infrastructure.

Happy coding!