AlwaysLearner
AlwaysLearner

Reputation: 473

Docker postgres starting automation can not create database due to error

I want to create a shell script which automates the creation and running and creating database in a postgres database using docker.

I want to use the docker postgres official package for postgres in docker.

The script that I use is as follows:

docker network create --subnet=172.18.0.0/16 shared_network;
docker kill postgres_linker;
docker rm postgres_linker;
docker run --name postgres_linker -e POSTGRES_PASSWORD=blahblahblah -d --net shared_network --ip 172.18.0.2 postgres:10-alpine;
docker exec -it postgres_linker psql -U postgres -c "create database linker;";

But when I run this I get the following output without any database being created:

Error response from daemon: network with name shared_network already exists
postgres_linker
postgres_linker
b2a9fd4d6e25b62d60adb05c8b6b653a1b55ec7a869c4728677d6289f5cddd63
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"?

The first line of this log is OK, the second and third are too, The problem is that psql does not run the command on the postgres container althogh the command I am trying to run is correct. If I run the last command seperately from my shell script:

docker exec -it postgres_linker psql -U postgres -c "create database linker;";

It does not give me error! and it works!
Why is this behavior happening?

Upvotes: 1

Views: 727

Answers (1)

AlwaysLearner
AlwaysLearner

Reputation: 473

I found the solution to my problem.
Unfortunately I thought that when postgres container is run the server is up and running immediately.
It was not true and it takes some time to come up. so I have needed to add some delay.
So the resulting script file should look like this:

docker network create --subnet=172.18.0.0/16 shared_network;
docker kill postgres_linker;
docker rm postgres_linker;
docker run --name postgres_linker -e POSTGRES_PASSWORD=blahblahblah -d --net shared_network --ip 172.18.0.2 postgres:10-alpine;
sleep 5;
docker exec -it postgres_linker psql -U postgres -c "create database linker;";

Upvotes: 1

Related Questions