Backup MySQL or MariaDB with Ofelia (cron) and Docker.

Tiempo de lectura: 2 minutos

Sure! Here’s the translated content in HTML format without any additional text:
html
Copy code
Reading time: 2 minutes

Hello, today we are going to learn how we can create a backup of MySQL or MariaDB using Ofelia to schedule cron tasks with Docker or Docker Compose.

The first thing we are going to do is to have a Docker Compose environment ready with MySQL installed and loaded tables. You can check out some of the tutorials we have published on how to set up environments with Docker Compose: https://devcodelight.com/category/docker/

Now let’s create the configuration files inside our MySQL container:

miservicio_mysql:
    image: biarms/mysql:5.7
    env_file:
      - ./Dockerfile/mysql.env
    container_name: mysql_container
    command: --max_allowed_packet=67108864
    mem_limit: 2g
    restart: always
    environment:
      MYSQL_DATABASE: "bddd" 
      MYSQL_USER: "user_db" 
      MYSQL_PASSWORD: "user_db_root_pass" 
      MYSQL_ROOT_PASSWORD: "root_pass"
    volumes:
      - ./config/mysql:/var/lib/mysql
      - ./config/backup_sql:/backup
    expose:
      - 3306
    ports:
      - 3306:3306
    networks:
      - docker-network

We have created the volume:

  - ./config/backup_sql:/backup

Where the created backup will be stored, along with the MySQL configuration file containing the passwords.

Now, inside the config/backup directory, let’s create a file named my.cf

[mysqldump]
user=root
password=root_pass

In this file, we configure the database user and its password.

Next, we will create the config.ini file for Ofelia (remember that here I show you how you can use Ofelia in your environment).

[job-exec "job-executed-on-running-container"]
schedule =  @every 5m
container = mysql_container
command =  sh -c \"mysqldump --defaults-file=/backup/my.cf --routines --all-databases  gzip > /backup/copia-$(date +%y%m%d%H%M).sql.gz\"

This command will be executed every 5 minutes and will generate a database backup.

Remember to change the frequency from 5m to your desired value:

schedule = @every 5m

Finally, the command will create a backup of all databases. You can customize the command according to your needs, for example, to select only the database you need for your backup

Leave a Comment