[Answered ]-Seeding a MySQL DB for a Dockerized Django App

2👍

MySQL (and variants like Percona Server) provide a facility for seeding a database on first container start described in the “Initializing a fresh instance” section in the docker hub page.

When a container is started for the first time, a new database with
the specified name will be created and initialized with the provided
configuration variables. Furthermore, it will execute files with
extensions .sh, .sql and .sql.gz that are found in
/docker-entrypoint-initdb.d. Files will be executed in alphabetical
order. You can easily populate your mysql services by mounting a SQL
dump into that directory and provide custom images with contributed
data. SQL files will be imported by default to the database specified
by the MYSQL_DATABASE variable.

A Dockerfile using this technique will look like

FROM mysql:8
COPY seed-data.sql /docker-entrypoint-initdb.d/

Note: the directory trailing slash is important.

When you docker run this image, docker will create the container, the docker-entrypoint.sh will execute the sql script, and then the container will be ready to serve data.

Data will persist through container restarts – the seed data and subsequent modifications.

You can reuse the container for faster startup times – subsequent container starts will not need to initialize the database or seed the data.
When you need pristine data, delete the container and docker run the image again.

When you delete the container, remember to delete the docker volume containing the db data: docker rm -v $CONTAINER_NAME.

I use this method to provide standard data for language / framework POCs as well as CI/CD. Initializing a new database and seeding large amounts of data can take a couple of minutes so you will want some logic to pause automated operations until you can successfully make a db connection.

Hope this helps you on your way.

Leave a comment