How to init MySql Database in Docker Compose How to init MySql Database in Docker Compose docker docker

How to init MySql Database in Docker Compose


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.