"how to init mysql database in docker compose" Code Answer

3

for loading your sql files only on the first run:

you can use the below compose file

version: '2.1'
services:

  usermanagement-service:
    build: ./usermanagementservice
    restart: on-failure
    ports:
      - "7778:7778"
    depends_on:
      mysqldb:
        condition: service_healthy

  mysqldb:
    image: mysql
    volumes:
      - ./mysql-data:/var/lib/mysql
      - ./mysql-init-files:/docker-entrypoint-initdb.d
    restart: always
    environment:
      mysql_root_password: root
      mysql_database: userdb
      mysql_user: testuser
      mysql_password: testuser
    ports:
      - "3600:3306"
    healthcheck:
      test: ["cmd", "mysqladmin" ,"ping", "-h", "localhost"]
      timeout: 20s
      retries: 10

you have to place your data.sql and schema.sql files under ./docker-entrypoint-initdb.d directory using volumes for more info.

sql files in this folder will be loaded only if the db's data directory is empty (the very first run of db service). (i.e) in your case ./mysql-data folder should be empty

for your second problem:

instead of using wait-for-it.sh, you can use healthcheck and service_healthy. here usermanagement-service will be started once mysqldb successfully executes ["cmd", "mysqladmin" ,"ping", "-h", "localhost"] in the specified interval. for more details on healthcheck and depends_on, refer here.

got test command from here.

By Ramy Kfoury on February 5 2022

Answers related to “how to init mysql database in docker compose”

Only authorized users can answer the Search term. Please sign in first, or register a free account.