Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a mysql db with Docker compose?

Tags:

I'm trying to host on docker an application which uses MySQL db. I'm using docker compose. my yml file looks like this:

version: '2'
volumes:
  data_sql:    
services:  
medical-mysql:
    image: mysql
    hostname: medical-mysql    
    volumes:    
     - data_sql:/dbcreation.sql
    environment:
      MYSQL_DATABASE: Medical
      MYSQL_ROOT_PASSWORD: root
      STARTUP_SQL: data_sql
    ports:
    - "3306:3306"
  medical-main:
    build: .
    ports:
     - "8080:8080"    
    depends_on:
     - medical-mysql

I have a dbcreation.sql which creates the db schema and is kept in the yml folder. When I run the yml file it seems as if the file is not running.

What have I missed?

like image 901
Izhar Lotem Avatar asked Mar 07 '16 13:03

Izhar Lotem


People also ask

Can I use MySQL with Docker?

MySQL is one of the most popular SQL-compatible relational databases. Running MySQL inside a Docker container lets you separate your database from your code. You can also use a container orchestrator like Kubernetes to scale MySQL independently of your API server instance.


2 Answers

Simply just put your .sql file (dbcreation.sql) in a folder (ie. /mysql_init) and add the folder as a volume like this:

volumes:
  - /mysql_init:/docker-entrypoint-initdb.d

The MySQL image will execute all .sql, .sh and .sql.gz files in /docker-entrypoint-initdb.d on startup.

like image 117
StumpDK Avatar answered Sep 30 '22 21:09

StumpDK


1) Create dump file dbcreation.sql

2) Create import.sh file:

#!/usr/bin/env bash
mysql -u root -p$MYSQL_ROOT_PASSWORD < /tmp/dbcreation.sql

3) Create docker-compose.yaml

database:
  image: mysql
  container_name: database.dev
  command: mysqld --user=root --verbose
  volumes:
    - ./dbcreation.sql:/tmp/dbcreation.sql
    - ./import.sh:/tmp/import.sh
  ports:
    - "3306:3306"
  environment:
    MYSQL_DATABASE: "test"
    MYSQL_USER: "test"
    MYSQL_PASSWORD: "test"
    MYSQL_ROOT_PASSWORD: "root"
    MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

"- ./dbcreation.sql:/tmp/dbcreation.sql" - "- local_path:path_inside_container"

4) Run

docker-compose up
docker exec database.dev bash /tmp/import.sh
like image 29
ashatrov Avatar answered Sep 30 '22 22:09

ashatrov