7

I'm trying to create simple postgres server with docker. I use the official postgres image as a base for my container. My Dockerfile contains these commands:

FROM postgres
USER postgres
RUN /etc/init.d/postgresql start &&\
    psql --command "CREATE USER user WITH SUPERUSER PASSWORD 'user';" &&\
    createdb -O user app

And when I try to run it I have an error:

psql: 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"?

What I'm doing wrong?

kharandziuk
  • 12,020
  • 17
  • 63
  • 121
  • 2
    Did you check that "*Is the server running locally and accepting connections on Unix domain socket*"? –  Oct 05 '14 at 09:47

4 Answers4

2

It's possible that it takes some time for postgres to start accepting connections. The way you've written it, it will call CREATE USER immediately after the start function returns. Try putting a sleep in there and see if it's still a problem.

seanmcl
  • 9,740
  • 3
  • 39
  • 45
2

Use pg_ctl with the -w flag so the command will finish when the server has started. No more wondering about whether we have waited long enough. And we can actually stop the server the same way

sudo -u postgres pg_ctl start -w -D ${PGDATA}

sudo -u postgres psql --command "CREATE USER user WITH SUPERUSER PASSWORD 'user';" &&\
sudo -u postgres createdb -O user app

sudo -u postgres pg_ctl stop -w
Solway01
  • 61
  • 4
1

Had the same problem inside a script in entry point. Following is my Dockerfile excerpt

# init execution
ENTRYPOINT ["/usr/local/sbin/initpostgres.sh"]

with following commands inside the intipostgres.sh script

 su postgres -c "pg_ctl start -l /var/lib/postgresql/logpostgres"
 su postgres -c "createuser -s $OPENERPUSER"

adding sleep 1 before the createuser command per @seanmcl suggested correction worked for me :

 su postgres -c "pg_ctl start -l /var/lib/postgresql/logpostgres"
 sleep 1
 su postgres -c "createuser -s $OPENERPUSER"
Yves Nicolas
  • 6,901
  • 7
  • 25
  • 40
1

The problem seems to be that the postgres unix socket is not on your host machine. You can fix this by running the following command.

docker run -p 5432:5432 --volume="/run/postgresql:/run/postgresql" -d --name postgres postgres

The essential part is the --volume flag. It links the folder that includes the unix socket file .s.PGSQL.5432 to the host machine in order to be read by other processes.

This seems like a duplicate question of Installing PostgreSQL within a docker container, is that right OP?

Community
  • 1
  • 1
Vasspilka
  • 1,135
  • 1
  • 10
  • 22