Steve Quezadas
Steve Quezadas

Reputation: 744

How load psql through docker?

I am trying to load psql through docker. I went through the instructions on the official dockerhub page: https://hub.docker.com/_/postgres

The official command in the documentation is here:

docker run -it --rm --network some-network postgres psql -h 127.0.0.1 -U postgres

I replaced "some-network" with various network_ids and they all didn't work. The following error I get is this:

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

I read through the documentation, so I assume this must be some sort of error. Does anyone know what is wrong?

Upvotes: 1

Views: 82

Answers (2)

ROOT
ROOT

Reputation: 11622

--network some-network is an option to add the container you are trying to run to a network, you can just omit this option for simple docker usage.

The command you are executing will create a container from PostgreSQL and try to use psql client utility to connect to PostgreSQL server, so you need a running Postgres server, to make it work just follow these steps:

step one: run a container:

docker pull postgres && docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

step two: connect to the container you already have PostgreSQL server running and to do so you have to get the ip address for this container using inspect (note that we are specifying container name some-postgres we created in the previous step):

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' some-postgres

step three: this will print out the IP address for the container that we want to connect to, then run this

docker run -it --rm postgres psql -U postgres -h IP_ADDRESS

this will prompt you to insert password (in our case mysecretpassword)


This is not really an efficient way to connect, so what I suggest you do after step one, is to just run exec, which allow you do connect/run psql and connect to already exsiting container without the need to get all the network options.

docker exec -it some-postgres psql -U postgres

Upvotes: 2

Haim Raman
Haim Raman

Reputation: 12023

The description in the documentation in not so clear. As it starts the server and immediately try to connect to it. The client pqsl is running too early and fails to connect.

If you just want to "play with postgres" i suggest doing this in two steps.

 # docker run -d --rm  \
 -e POSTGRES_HOST_AUTH_METHOD='trust' \
postgres

43319e274a61394f111afb8a43b9bdfd4a46795ea5c8f9c78be4698135e45b33 <-container id 

# docker exec -it \
    <continer id> \
    psql -U postgres

\\psql (12.3 (Debian 12.3-1.pgdg100+1))
Type "help" for help.

postgres=#

Upvotes: 2

Related Questions