What’s the best way to schedule PostgreSQL backups with Docker?
Asked by
bicycle spoke 32
I'm running PostgreSQL in a Docker container and want to create regular automated backups. Should I run cron inside the database container, use docker exec from the host, or handle the schedule with a separate container? I'd also like the backups to be written to persistent storage and to have failures logged clearly.
Answers
The simplest design is usually a one-line scheduled pg_dump command running either on the host or from a small PostgreSQL client container. A separate scheduler is useful when you want everything managed in Docker, but you don’t need to add extra containers just for the sake of it. Whichever method you choose, test restoring a backup periodically—creating dump files alone doesn’t prove they’re usable.
Reply to this answer
You can also run the backup from the host’s cron and start a temporary PostgreSQL client container for each job. For example, run pg_dump from a matching postgres image, connect it to the database network, pipe the compressed output into a file, and mount the backup directory into the temporary container. This avoids putting cron inside the database container.
Reply to this answer
A host cron job that invokes pg_dump through docker exec is perfectly workable for a simple setup. The important parts are to store the resulting files on a persistent host volume, not only in the container filesystem, and to check the command’s exit status so a failed backup doesn’t look successful. Protect the database password rather than embedding it directly in shell history or visible command arguments.
Reply to this answer
A clean Docker-style approach is to use a separate scheduler container rather than installing cron in the PostgreSQL container. Keep the database container focused on PostgreSQL, and let the scheduler run a command such as pg_dump on a schedule. Mount a persistent backup directory into the scheduler and configure its logs to go to the container output. Tools such as Supercronic or Ofelia can handle the scheduling.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Free throw form~: Ofelia is another reasonable scheduler for this setup, especially if you want it to trigger commands in other containers.