Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete and recreate a postgres database using a single docker command?

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:

  1. Create database named

  2. Drop database named

Or even:

  1. Delete all tables of the to make it completely empty in one command.

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.

like image 217
sshussain270 Avatar asked Dec 30 '18 00:12

sshussain270


People also ask

How do I delete a PostgreSQL database?

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.

Can you Dockerize a database?

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.

What is -- rm command in docker?

On Docker, --rm option means automatically remove the container when it exits.


1 Answers

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:

  • get inside the container with a shell

docker exec -it <container-id> /bin/sh

and then run psql and do whatever you want inside the psql command line.

  • run psql directly in docker

docker exec -it <container-id> psql -U <username> -d <database-name>

  • have psql installed locally and run it to access the postgres instance in docker

psql -U <username> -h localhost

  • run the commands with psql

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>;"

like image 184
MrE Avatar answered Sep 20 '22 10:09

MrE