Kush Sharma
Kush Sharma

Reputation: 59

Unable to run psql command inside a postgres docker container

I have recently started using Docker. However, while I was able to run a postgres container and run a bash command "psql" inside it. Now, I am facing error in trying to do the same after sometime. Here is what worked for me sometime back and now it does not work anymore:

docker run --rm -it postgres bash

The above command opens a bash inside the postgres container. When I type psql inside this container, it shows error:

root@3615146cf679:/# psql

psql: error: could not connect to server: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket “/var/run/postgresql/.s.PGSQL.5432”?

Upvotes: 0

Views: 4671

Answers (2)

Kush Sharma
Kush Sharma

Reputation: 59

I myself figured it out that using "bash" at the time of starting the container was causing the problem. Once we run it using:

docker run --rm postgres

Above command says that we need to provide a Password or Auth Method. Hence, we do so. Anyone of below 3 commands can start a postgres container:

docker run --rm -e POSTGRES_PASSWORD=postgres postgres

or

docker run --rm -e POSTGRES_HOST_AUTH_METHOD=trust postgres

or

docker run --rm -e POSTGRES_HOST_AUTH_METHOD=trust -e POSTGRES_USER=postgres -e 
POSTGRES_PASSWORD=postgres postgres

Then, we can execute:

docker exec -it <container_id> bash
psql -U postgres
CREATE TABLE tutorials (id int, tutorial_name text);
INSERT INTO tutorials VALUES (1, 'C++');
select * from tutorials;

Upvotes: 1

Vahid
Vahid

Reputation: 1417

You need to use these commands in order: start the container with:

$ sudo docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

enter the container with:

$ sudo docker exec -it some-postgres /bin/bash

when you entered the container, run:

$ psql -U postgres

Upvotes: 7

Related Questions