Home > postgresql, vagrant > Allow remote hosts to connect to PostgreSQL database server on vagrant box

Allow remote hosts to connect to PostgreSQL database server on vagrant box

Problem: How to connect to PostgreSQL database server on a vagrant box.
Getting the following error when trying to connect using pgAdmin3.

could not connect to server: 
Connection refused Is the server running on host "192.168.33.10" 
and accepting TCP/IP connections on port 5432? 

Solution:

1. Ensure you have forwarded the ports on the vagrant box.

$less Vagrantfile
  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
   config.vm.network "forwarded_port", guest: 5432, host: 5431

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
   config.vm.network "private_network", ip: "192.168.33.10"

2. Install postgresql database. As per instructions here.

3. Create a user and a database. As per examples here.

4. Change listen_addresses

$ sudo vim /etc/postgresql/9.4/main/postgresql.conf
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

listen_addresses = '*'         # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
                                        # (change requires restart)
port = 5432                             # (change requires restart)

5. Add the ip of the vagrant box to pg_hba.conf

$ sudo vim /etc/postgresql/9.4/main/pg_hba.conf
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
host    all             all             192.168.33.10/24        md5

6. Restart PostgreSQL database server.

$ sudo service postgresql restart
 * Restarting PostgreSQL 9.4 database server                                      [ OK ]

You should now be able to connect.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: