Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i backup a database in docker

Tags:

i'm running my app using docker-compose with the below yml file

  postgres:     container_name: postgres     image: postgres:${POSTGRES_VERSION}     volumes:       - postgresdata:/var/lib/postgresql/data     expose:       - "5432"     environment:       - POSTGRES_DB=42EXP       - POSTGRES_USER=${POSTGRES_USER}       - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}    node:     container_name: node     links:       - postgres:postgres     depends_on:       - postgres  volumes:   postgresdata: 

As you can see here ,i'm using a named volume to manage postgres state.

According to the official docs, i can backup a volume like the below

docker run --rm --volumes postgresdata:/var/lib/postgresql/data -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata 

Some other tutorials suggested i use the pg-dump function provided by postgres for backups.

pg_dump -Fc database_name_here > database.bak 

I guess i would have to go inside the postgres container to perform this function and mount the backup directory to the host.

Is one approach better/preferable than the other?

like image 652
Kannaj Avatar asked Aug 29 '16 15:08

Kannaj


People also ask

How do I copy a database to a docker container?

If you need to restore a database backup file to a SQL Server instance that's running inside a Docker container (for example, on a Mac or Linux), you can copy the . bak file from your Mac/Linux machine over to the Docker container.


1 Answers

To run pg_dump you can use docker exec command:

To backup:

docker exec -u <your_postgres_user> <postgres_container_name> pg_dump -Fc <database_name_here> > db.dump

To drop db (Don't do it on production, for test purpose only!!!):

docker exec -u <your_postgres_user> <postgres_container_name> psql -c 'DROP DATABASE <your_db_name>'

To restore:

docker exec -i -u <your_postgres_user> <postgres_container_name> pg_restore -C -d postgres < db.dump

Also you can use docker-compose analog of exec. In that case you can use short services name (postgres) instead of full container name (composeproject_postgres).

docker exec

docker-compose exec

pg_restore

like image 112
tck Avatar answered Oct 18 '22 12:10

tck