Back up a database in a Docker container: MySQL, MariaDB and PostgreSQL
When the database runs in Docker, you dump it with its own tool inside the container through docker exec. The server itself needs no database client.
Find the container
ssh deploy@example.com "docker ps --format '{{.Names}}\t{{.Image}}'"
This lists running containers with their images, such as shop-db mysql:8.4 or crm-db postgres:16. The server user must be in the docker group, or the commands need sudo.
PostgreSQL
In the official postgres image, connecting from inside the container usually needs no password:
ssh deploy@example.com "set -o pipefail; docker exec crm-db pg_dump -U postgres crm | gzip" \
> pgsql-crm-$(date +%F).sql.gz
Use the user from POSTGRES_USER instead of postgres if you set it.
MySQL and MariaDB
The root password is already in the container’s environment, so you don’t have to copy it into the command. Because of the quoting, the command is easier to keep in a script on the server, say ~/dump-shop.sh:
#!/bin/bash
set -euo pipefail
docker exec shop-db sh -c 'exec mysqldump -uroot -p"$MYSQL_ROOT_PASSWORD" \
--single-transaction --routines --triggers --events shop' | gzip
Make it executable (chmod 700 ~/dump-shop.sh) and run it from the Mac:
ssh deploy@example.com ./dump-shop.sh > mysql-shop-$(date +%F).sql.gz
In MariaDB 11 images the tool is called mariadb-dump and the password is in $MARIADB_ROOT_PASSWORD. Keep in mind that a password passed with -p shows up in the server’s process list while the dump runs. If other people use the server, pass it through a temporary options file.
No -t
Don’t add -t to docker exec. With a terminal attached, Docker rewrites line endings and the dump gets corrupted. For the same reason docker compose needs -T:
docker compose exec -T db pg_dump -U postgres crm | gzip > crm.sql.gz
Why not copy the data volume
The folder where a running database keeps its files changes all the time. A copy taken on the fly may not start, or may start with damaged tables. A dump is a consistent snapshot that restores into any compatible version. Files the app keeps in other volumes, such as user uploads, can go into a regular archive, as in "Back up a website to your computer".
Check the result
A MySQL dump ends with -- Dump completed on …, and a PostgreSQL one with -- PostgreSQL database dump complete:
gunzip -c mysql-shop-2026-10-18.sql.gz | tail -n 1
gunzip -c pgsql-crm-2026-10-18.sql.gz | tail -n 8 | grep "dump complete"