If you're working with PostgreSQL inside Docker, at some point youโll need to reset your database.
Maybe:
- You want a clean start
- You imported the wrong data
- Or something just went wrong (it happens ๐ )
Dropping a database sounds simple โ but thereโs one important rule that can trip you up.
โ ๏ธ The Rule Most People Miss
๐ You cannot drop a database while you're connected to it
So if your database is my_database, you must connect to a different one (usually postgres) before dropping it.
๐ The Correct Command
Hereโs the safe and correct way to drop your database from a Docker container:
docker exec -i postgres_container psql -U postgres -d postgres -c "DROP DATABASE my_database;"
๐ง Whatโs Happening Here?
-
docker execโ runs a command inside your container -
postgres_containerโ your container name -
psqlโ PostgreSQL CLI -
-d postgresโ connect to default database (not the one you're deleting) -
DROP DATABASE my_database;โ removes the database
๐ In simple terms:
โConnect to a safe database and delete the target database from there.โ
๐ Drop and Recreate (Clean Reset)
If you want a fresh database:
docker exec -i postgres_container psql -U postgres -d postgres -c "DROP DATABASE IF EXISTS my_database;"
docker exec -i postgres_container psql -U postgres -d postgres -c "CREATE DATABASE my_database;"
๐ฅ Full Reset (Docker Way)
If you want to completely wipe everything:
docker-compose down -v
docker-compose up -d
This removes:
- All databases
- Volumes
- Stored data
๐ You get a completely fresh start.
๐งฉ When Youโll Need This
- Resetting development databases
- Fixing broken migrations
- Cleaning test environments
- Re-importing fresh data
๐ Final Thoughts
Dropping a PostgreSQL database inside Docker is straightforward โ once you understand the connection rule.
The key takeaway:
Always connect to a different database before dropping the target one.
Itโs a small detail, but it saves a lot of confusion.
Top comments (0)