54 lines
2.0 KiB
Markdown
54 lines
2.0 KiB
Markdown
Create Back Up File
|
||
docker exec -t phoenixDB pg_dump -U postgres -d phoenix > phoenix_backup.sql
|
||
|
||
# PostgreSQL Database Backup in Docker
|
||
|
||
## 🛠️ Backup Commands for `phoenixDB`
|
||
|
||
### 1️⃣ **Dump Database (Including DROP Statements)**
|
||
```sh
|
||
docker exec -t phoenixDB pg_dump -U postgres -d phoenix -c > phoenix_backup.sql
|
||
```
|
||
📖 Explanation:
|
||
• docker exec -t phoenixDB → Runs the pg_dump command inside the phoenixDB container.
|
||
• pg_dump -U postgres -d phoenix -c:
|
||
• -U postgres → Connect as user postgres.
|
||
• -d phoenix → Dump the phoenix database.
|
||
• -c → Includes DROP statements (cleans tables before restoring).
|
||
• > phoenix_backup.sql → Saves the dump to your host machine.
|
||
|
||
🔹 When to Use?
|
||
• Use this when you want to completely overwrite an existing database on restore.
|
||
• Ensures that old tables are dropped before new ones are created.
|
||
|
||
# Dump Database (Without DROP Statements)
|
||
```sh
|
||
docker exec -t phoenixDB pg_dump -U postgres -d phoenix > phoenix_backup.sql
|
||
```
|
||
|
||
📖 Explanation:
|
||
• Similar to the previous command, but without -c.
|
||
• This does NOT include DROP TABLE statements, meaning:
|
||
• It will fail if restoring to a database that already has tables with the same names.
|
||
• Use this when restoring to a new empty database.
|
||
|
||
🔹 When to Use?
|
||
• If you’re backing up for archival purposes.
|
||
• If you don’t want to drop existing data on restore.
|
||
|
||
# 🛠️ How to Restore the Backup?
|
||
## Restore to a Database (bkp1)
|
||
```sh
|
||
cat phoenix_backup.sql | docker exec -i phoenixDB psql -U postgres -d bkp1
|
||
```
|
||
📖 Explanation:
|
||
• cat phoenix_backup.sql → Reads the dump file.
|
||
• | → Pipes it into the psql command inside the container.
|
||
• docker exec -i phoenixDB psql -U postgres -d bkp2
|
||
• -i → Allows input redirection.
|
||
• -U postgres → Connects as the postgres user.
|
||
• -d bkp2 → Restores to the bkp2 database
|
||
|
||
# 🎯 Final Notes
|
||
• Use the -c flag when restoring into an existing database and you want to drop old tables first.
|
||
• Omit -c when restoring into a new, empty database. |