Hassan Baig
Hassan Baig

Reputation: 15804

psycopg2.connect failing with error 'connection refused' (Django app+db hosted on separate VMs)

I have a Django app where the app and database reside in two separate VMs. I use Azure. In trying to connect to a postgresql backend hosted in a separate Azure VM, I'm writing: conn = psycopg2.connect("dbname='dbname' host='dnsname'"), where value of host was gotten off the Azure portal from here:

enter image description here

I have also tried the Virtual IP address above as the host. Both approaches fail and I get a connection error: could not connect to server: Connection refused. Is the server running on host "myapp.cloudapp.net" (23.132.341.192) and accepting TCP/IP connections on port 5432? Please note that I changed the IP address when pasting the error here.

The Azure VM hosting the postgresql database has port 5432 added to its Endpoints. Moreover, my app to which this postgresql backend belongs is a Django/Python app. My VMs have Ubuntu 14.04. In setting up postgresql, I ran the following installation commands on both app and database VMs separately:

sudo apt-get update

sudo apt-get install PostgreSQL postgresql-contrib

sudo apt-get install postgresql-server-dev-all

sudo apt-get install libpq-dev

And even though both app and database VMs have all of the above installed in them, the database itself was only created in the latter VM. I didn't create a separate user; I instead did: sudo su postgres

psql -d postgres -U postgres

And then

CREATE DATABASE dbname;


How do I fix the psycopg2.connect error? Ask for more information if needed.

Upvotes: 1

Views: 1526

Answers (1)

Gary Liu
Gary Liu

Reputation: 13918

As to separate PostgreSQL into another Azure VM, we need to configure several settings both on Azure VM side and your PostgreSQL service.

1, modify the listen_addresses="*" at /etc/postgresql/9.4/main/postgresql.conf ,to allow other client beside local to request your PostgreSQL service.

2, Add the following line as the first line of /etc/postgresql/9.4/main/pg_hba.conf. It allows access to all databases for all users with an encrypted password:

# TYPE DATABASE USER CIDR-ADDRESS METHOD host all all 0.0.0.0/0 md5

3, run command sudo service postgresql restart to restart the service

4, login Azure manage portal, add a request rule in Endpoints page of your VM, configure public port 5432 to private port 5432: enter image description here

Upvotes: 2

Related Questions