Ander
Ander

Reputation: 5674

How to create Postgres backups from docker container

I have a Postgres 9.5.4 database running inside a docker container. I am using the official Postgres images and I have been trying to create backups from my database, but not luck so far. According docker documentation I was expecting the following command to store the dump.tar file in the /releases/ folder in the host machine (outside the temporal docker container)

  docker run -i --rm --link my_postgres:postgres --volume /releases/:/tmp/ postgres:latest pg_dumpall > /tmp/dump.tar

But this throws the following error:

pg_dumpall: could not connect to database "template1": could not connect to server: Connection refused
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Any idea what could be wrong?

Upvotes: 1

Views: 3764

Answers (1)

Ander
Ander

Reputation: 5674

Actually I have found the solution

docker run -i --rm --link my_container:postgres -v /releases/:/tmp/ postgres:latest bash -c 'exec pg_dumpall -h "$POSTGRES_PORT_5432_TCP_ADDR" -p "$POSTGRES_PORT_5432_TCP_PORT" -U postgres  > /tmp/my_backup.tar'

Where Docker arguments:

  • -i For interactive processes, like a shell, bash, etc.
  • --rm For deleting the container once the backup is finished
  • --link For linking this temporal container to my_container, which contains the currently running Postgres database.
  • -v /releases/:/tmp/ Creates shared volume. The content inside the folder /tmp/ in the container (In this case my_backup.tar) will be automatically visible on folder /releases/ in the host machine.

And bash arguments:

  • pg_dumpall To export PostgreSQL cluster into a script file.
  • -h "$POSTGRES_PORT_5432_TCP_ADDR" Obtains the ip address out of the Postgres variable.
  • -p "$POSTGRES_PORT_5432_TCP_PORT" Obtains the Port out of the Postgres variable (These variables are defined only in the temporal container we just created, as result of the linkage with my_container)
  • -U The username for connecting to the database

Upvotes: 2

Related Questions