I am writing a microservice application which has a docker container for postgres database. I know that when dumping SQL to database, we use this docker command in terminal:
cat <dump sql file> | docker exec -i <container ID> psql -U <postgres username> <database name>
I was wondering if there is a similar linux terminal docker command that i can run from outside the container to:
Create database named
Drop database named
Or even:
Note that i should be able to run the docker command from outside the container through the host OS terminal (linux).
Any suggestions will be appreciated. Thanks in advance.
The first method to remove a PostgreSQL database is to use the following SQL statement: DROP DATABASE <database name>; The command removes the directory containing the database information and the catalog entries. Only the database owner can execute the DROP DATABASE command.
Docker is great for running databases in a development environment! You can even use it for databases of small, non-critical projects which run on a single server. Just make sure to have regular backups (as you should in any case), and you'll be fine.
On Docker, --rm option means automatically remove the container when it exits.
is the Postgres storage local to the container? If so, then removing the container and recreating it will reset your DB in itself. If your data is mounted from a local or network folder, then reseting it means running commands on psql
You have several options:
docker exec -it <container-id> /bin/sh
and then run psql and do whatever you want inside the psql command line.
docker exec -it <container-id> psql -U <username> -d <database-name>
psql -U <username> -h localhost
You cannot DROP and CREATE a database on the same command unfortunately, but you can run 2 separate commands
docker exec -it <container-id> psql -U <username> -d postgres -c "DROP DATABASE <dbname>;"
docker exec -it <container-id> psql -U <username> -d postgres -c "CREATE DATABASE <dbname>;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With