To perform a backup of a PostgreSQL database running in a Docker container, you can use the pg_dump
command to export the database to a SQL script file, and then use the docker cp
command to copy the file from the container to your local machine.
For example, assuming that your PostgreSQL container is named “my-Postgres”, you could use the following pg_dump
command to export the contents of the “mydb” database to a file named “mydb.sql”:
docker exec my-postgres pg_dump mydb > mydb.sql
This will create a file named “mydb.sql” in the current directory on the host machine, containing the SQL commands needed to recreate the “mydb” database.
To copy the “mydb.sql” file from the container to your local machine, you can use the docker cp
command, specifying the name of the container and the path to the file in the container, followed by the destination path on your local machine:
docker cp my-postgres:/mydb.sql .
This will copy the “mydb.sql” file from the “my-postgres” container to the current directory on your local machine.
You can then use this file to restore the database on the same or another PostgreSQL server, using the psql
command or another tool. For example, to restore the “mydb” database on the same server, you could use the following command:
cat mydb.sql | docker exec -i my-postgres psql mydb
This will run the SQL commands in the “mydb.sql” file on the “my-postgres” container, restoring the “mydb” database.
Overall, using pg_dump
and docker cp
to perform a backup of a PostgreSQL database in a Docker container is a simple and effective way to ensure that your data is safe and can be restored in case of a failure or data loss.