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.
4 Answers
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.
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.
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.
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.

Ofelia is another reasonable scheduler for this setup, especially if you want it to trigger commands in other containers.