title: How to dump DB via cron inside container?
body: <p>I use <code>docker-compose</code> which ups a stack.</p>
  
  <p><strong>Relative code:</strong></p>
  
  <pre><code>db:
    build: ./dockerfiles/postgres
    container_name: postgres-container
    volumes:
      - ./dockerfiles/postgres/pgdata:/var/lib/postgresql/data
      - ./dockerfiles/postgres/backups:/pg_backups
  </code></pre>
  
  <p><strong>Dockerfile for Postgres:</strong></p>
  
  <pre><code>FROM postgres:latest
  
  RUN mkdir /pg_backups &amp;&amp; &gt; /etc/cron.d/pg_backup-cron &amp;&amp; echo "00 22 * * * /backup.sh" &gt;&gt; /etc/cron.d/pg_backup-cron
  ADD ./backup.sh /
  RUN chmod +x /backup.sh
  </code></pre>
  
  <p><strong>backup.sh</strong></p>
  
  <pre><code>#!/bin/sh
  # Dump DBs
  
  now=$(date +"%d-%m-%Y_%H-%M")
  pg_dump -h db -U postgres -d postgres &gt; "/pg_backups/db_dump_$now.sql"
  
  # remove all files (type f) modified longer than 30 days ago under /pg_backups
  find /pg_backups -name "*.sql" -type f -mtime +30 -delete
  
  exit 0
  </code></pre>
  
  <p>Cron simply does not launch the script. How to fix that?</p>
  
  <hr>
  
  <p><strong>FINAL VERSION</strong></p>
  
  <p>Based on @Farhad Farahi answer, below is the final result:</p>
  
  <p>On host I made a script:</p>
  
  <pre><code>#!/bin/bash
  # Creates Cron Job which backups DB in Docker everyday at 22:00 host time
  croncmd_backup="docker exec -it postgres-container bash -c '/pg_backups/backup.sh'"
  cronjob_backup="00 22 * * * $croncmd_backup"
  
  if [[ $# -eq 0 ]] ; then
      echo -e 'Please provide one of the arguments (example: ./run_after_install.sh add-cron-db-backup):
      1) add-cron-db-backup
      2) remove-cron-db-backup'
  
  # In order to avoid task duplications in cron, the script checks, if there is already back-up job in cron
  elif [[ $1 == add-cron-db-backup ]]; then
      ( crontab -l | grep -v -F "$croncmd_backup" ; echo "$cronjob_backup" ) | crontab -
      echo "==&gt;&gt;&gt; Backup task added to Cron"
  
  # Remove back-up job from cron
  elif [[ $1 == remove-cron-db-backup ]]; then
      ( crontab -l | grep -v -F "$croncmd_backup" ) | crontab -
      echo "==&gt;&gt;&gt; Backup task removed from Cron"
  
  fi
  </code></pre>
  
  <p>This script adds cron task to host, which launches the script <code>backup.sh</code> (see above) in a container.</p>
  
  <p>For this implementation there is no need to use <code>Dockerfile</code> for <code>Postgres</code>, so relevant part of <code>docker-compose.yml</code> should look like:</p>
  
  <pre><code>version: '2'
  services:
    db:
      image: postgres:latest
      container_name: postgres-container
      volumes:
        - ./dockerfiles/postgres/pgdata:/var/lib/postgresql/data
        - ./dockerfiles/postgres/backups:/pg_backups
  </code></pre>