Is it possible to connect to the database directly from a separate app?

Anyone have any ideas why this isn’t working please?

I followed some of the posts by @pfaffman and @Nacho_Caballero in this topic: How to make the database (or part of it) accessible to a cloud data processor? and @mpalmer’s post in this one: Accessing to the database from outside the container.

First I edited app.yml with:

expose:
  - "127.0.0.2:5432:5432"

Rebuilt container. In the container I set a password for the postgres user, and can then connect with the following from inside the container:

psql -h localhost -d discourse -U postgres

However when I exit the container and try connecting I get:

# psql -h 127.0.0.2 -p 5432 -d discourse -U postgres
psql: server closed the connection unexpectedly
	This probably means the server terminated abnormally
	before or while processing the request.

I have also tried changing the port to something else but I get the same thing. I got the 127 IP from docker ps and inspect under Network Settings (I have three standalone Discourse instances running).

If I change the IP (to that of one of the other Discourse forums) I get a (more immediate and) different response/message, so the above does appear to be partly correct:

# psql -h 127.0.0.3 -p 5432 -d discourse -U postgres
psql: could not connect to server: Connection refused
	Is the server running on host "127.0.0.3" and accepting
	TCP/IP connections on port 5432?

Any ideas on what I’m doing wrong? Googling psql: server closed the connection unexpectedly seems to suggest a networking issue - so do I need to alter anything else inside the container?