MySQL Container with Preloaded Data

· 194 words · 1 minute read

Ways to include preload the data in mysql container

  1. Using init script: SQL file is executed as part of container start process. This might not be good option when there is large number of sql scripts. Slows down the container start up.
    ADD schema.sql /docker-entrypoint-initdb.d
    
  2. Flyway migration: Provides sophisticated way to manage migration. The amount of time taken depends on number and type of sql scripts.
  3. Including the mysql data directory as part of image: Doesn’t impact on container start up time.
    1. Create a mysql container
      • /var/lib/mysql considered as volume path. So this directory is not included while creating the image
      • When the mysql image creating with data volume and if any database exist already then we cannot specify the username and password as env variable while creating new container from our custom image.
      docker run --name mysql -d -p 3306:3306 \
       -e MYSQL_ROOT_PASSWORD=mysql \
       -v mysql_data_volume:/var/lib/mysql mysql \
       --default-authentication-plugin=mysql_native_password \
       --log_bin_trust_function_creators=1 \
       --datadir=/var/lib/mysql-no-volume
      
    2. Now create the data in database
    3. Create a image from the running container
      docker commit <container_id> mysql:tag
      
    4. docker run -p 3306:3306 <container_id> mysql:tag We should not specify user and password as env variable here.