Postgres on Docker. How to create a database and user?

I am trying to create a simple postgres server with docker. I use the official postgres image as the base for my container. My Dockerfile contains the following 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 the server: there is no such file or directory. The server runs locally and accepts connections to the Unix domain "/var/run/postgresql/.s.PGSQL.5432"?

What am I doing wrong?

+5
source share
4 answers

It may take some time for postgres to start accepting connections. As you wrote it, it will call CREATE USER right after the start function returns. Try to sleep there and see if the problem is all.

+2
source

Had the same problem inside the script at the entry point. Below is a snippet of my Dockerfile

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

with the following commands inside an 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 on @seanmcl suggested a fix for me:

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

Use pg_ctl with the -w flag to terminate the command when the server starts. I would not want us to wait any longer. And we can actually stop the server in 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 
+1
source

The problem is that the postgres unix socket is not located on your main 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 important part is the --volume flag. It binds the folder that contains the unix.s.PGSQL.5432 socket file to the host machine to read other processes.

This seems like a duplicate question. Installing PostgreSQL in a docker container - is this the right OP?

+1
source

Source: https://habr.com/ru/post/1204038/


All Articles