Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres on Docker. How can I create a database and a user?

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?

like image 308
kharandziuk Avatar asked Oct 05 '14 09:10

kharandziuk


2 Answers

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.

like image 116
seanmcl Avatar answered Oct 14 '22 11:10

seanmcl


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
like image 44
Solway01 Avatar answered Oct 14 '22 11:10

Solway01