Home Navigation

Monday 20 July 2020

Postgres docker volume backup and restore

They way we are going to backup and restore postgres database docker volume we will use docker exec to get into the container and will use pg_dump utility to achieve our goal.

Postgres volume backup:

start your postgres container using docker or docker-compose.
execute the below command to get the container id
$docker ps

Backup database: 
    $docker exec -u postgres <containerId> pg_dump -Fc -d <databaseName> > dabase-backup.dump

Restore database:
    $docker exec -u <postgresUser> <containerId > psql -c 'DROP DATABASE <databaseName>'

    $docker exec -i -u < postgresUser > <containerId> pg_restore --clean -C -d postgres < dabase-backup.dump


Backup Schema:
    $docker exec -u postgres <containerId> pg_dump -Fc -d <databaseName> -n <schemaName> > schema-db-backup.dump
Restore Schema:
    $docker exec -it -u postgres <containerId> psql 
you will be in interactive mode, in the prompt terminal execute the below commands
    postgres=# \connect bdd
    # drop schema <schemaName> cascade
    # create schema <schemaName>
    \q to quit the interactive mode postgres
    Then execute the below command to reload db
    $docker exec -i -u postgres <containerId> pg_restore --clean -C -d <databaseName> -n <schemaName> < schema-db-backup.dump
Last step, validate your data using a database browser or you can use the below command to get into the database terminal and use sql query to validate your data.

    $docker exec -it -u postgres <containerId> psql 

No comments:

Post a Comment