To import a database from another PostgreSQL database into a Docker PostgreSQL container, you can use the pg_dump
and psql
tools. Here's a step-by-step guide to achieve this:
Step 1: Export the Database from the Source PostgreSQL
On the source PostgreSQL server, use the pg_dump
tool to create a dump file of the database you want to export. Replace source_db
, source_user
, and source_host
with your actual database name, username, and host.
pg_dump -h source_host -U source_user -d source_db -F c -b -v -f /path/to/backup/source_db_backup.dump
This command creates a custom-format dump file named source_db_backup.dump
. You can use other formats (plain SQL, directory, or tar) if preferred.
Step 2: Copy the Dump File to Your Local Machine
If the dump file is on a remote server, you need to copy it to your local machine. You can use scp
for this:
scp source_user@source_host:/path/to/backup/source_db_backup.dump /local/path/to/backup/
Step 3: Copy the Dump File into the Docker PostgreSQL Container
You can copy the dump file into the running Docker container using the docker cp
command. Replace container_id
with the ID or name of your Docker PostgreSQL container.
docker cp /local/path/to/backup/source_db_backup.dump container_id:/source_db_backup.dump
Step 4: Restore the Database in the Docker PostgreSQL Container
Now, you can use the psql
tool inside the Docker container to restore the database from the dump file. First, ensure the target database exists in the container. If it does not, create it:
docker exec -it container_id psql -U myuser -c "CREATE DATABASE target_db;"
Then, restore the database from the dump file:
docker exec -it container_id pg_restore -U myuser -d target_db /source_db_backup.dump
Step 5: Verify the Import
Finally, verify that the import was successful by connecting to the PostgreSQL container and listing the tables in the restored database:
docker exec -it container_id psql -U myuser -d target_db -c '\dt'
Summary
- Export the database from the source PostgreSQL using
pg_dump
. - Copy the dump file to your local machine (if needed).
- Copy the dump file into the Docker PostgreSQL container.
- Restore the database in the Docker PostgreSQL container using
pg_restore
. - Verify the import.