picardo
picardo

Reputation: 24886

How to connect to a Postgres server in a Docker (1.12.0) container on a Mac?

The latest release of Docker doesn't use a virtual machine anymore, instead using a hypervisor to connect to the containers. This means I can no longer login to postgres with psql:

➜  postgres git:(master) ✗ docker run -d -p 5433:5432 db postgres
<sha>
➜  postgres git:(master) ✗ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
111f3bed4c52        db                  "/docker-entrypoint.s"   17 minutes ago      Up 17 minutes       0.0.0.0:5433->5432/tcp   zen_hugle
➜  postgres git:(master) ✗ psql -p 5433 -U postgres
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5433"?

I have also tried specifying localhost as the host, but that results in a strange output:

➜  postgres git:(master) ✗ psql -h localhost -p 5433 -U postgres
psql: %

Does anyone know what to do in this case? Thank you.

Upvotes: 3

Views: 2425

Answers (2)

Sameer Azazi
Sameer Azazi

Reputation: 1497

With follwing command,

docker run -d -p 5433:5432 db postgres

You are exporting your docker's 5432 port to docker-engine's 5433 port. Not your host machine's 5433.

Fetch your docker-machine's IP address with following command (assuming your docker vm name is default)

docker-machine env default

This should give you result similar to following lines

> export DOCKER_TLS_VERIFY="1"
> export DOCKER_HOST="tcp://192.168.99.100:2376"
> export DOCKER_CERT_PATH="/Users/<your-user>/.docker/machine/machines/default"
> export DOCKER_MACHINE_NAME="default"

Use your docker-machine's IP address to connect to Postgres running in container

>psql -h 192.168.99.100 -p 5433 -U postgres

psql (9.5.0, server 9.5.5)
Type "help" for help.

postgres=#

Upvotes: 1

ldg
ldg

Reputation: 9402

You can connect over tcp by using an IP like psql -h 0.0.0.0 -p 5433 -U postgres (or 127.0.0.1, etc.).

Using the default or "localhost" will try using the local domain socket (although the version of Docker doesn't change this behavior, you will generally need to connect to a containerized db via tcp).

Upvotes: 0

Related Questions