How to Move a PostgreSQL Database from One Container to Another in a Docker Environment.
The following section explains how to move a PostgreSQL database from one container to another in a Docker environment.
-
Open your terminal and run the following commands to back up a database inside the container.
docker ps docker exec -it <database container name/database ID> bash pg_dump -U postgres -d <database name> -f <database name>.sql
Example:
docker psdocker exec -it some-postgres_A bash
pg_dump -U postgres -d bold_services -f bold_services.sql
-
Copy the backup SQL file from the container to the local machine using the following command.
docker cp <container name>:/<backup file location inside the container> <local machine path to paste a backup file>
Example:
docker cp some-postgres_A:/bold_services.sql /root -
Move a backup file to another container using the following command.
docker cp <local machine path to paste a backup file> <container name>:/<backup file location inside the container>
Example:
docker cp /root/bold_services.sql some-postgres_B:/ -
Bash a second container and navigate to that file location, then restore a database using that backup file.
docker ps docker exec -it -u postgres <database restore container name/database ID> bash psql Create database <database name>; exit psql <database name> < <sql file name>
Example:
docker psdocker exec -it -u postgres some-postgres_B bash
psql
Create database bold_services;
exit
psql bold_services < bold_services.sql
After following the above steps, the database was backed up and restored from one container to another.