如何使用 Docker compose 创建 mysql 数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35845144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a mysql db with Docker compose?
提问by Izhar Lotem
I'm trying to host on docker an application which uses MySQL db. I'm using docker compose. my yml file looks like this:
我正在尝试在 docker 上托管一个使用 MySQL db 的应用程序。我正在使用 docker compose。我的 yml 文件如下所示:
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.
我有一个dbcreation.sql
创建 db 模式并保存在 yml 文件夹中的。当我运行 yml 文件时,似乎该文件没有运行。
What have I missed?
我错过了什么?
回答by StumpDK
Simply just put your .sql file (dbcreation.sql) in a folder (ie. /mysql_init) and add the folder as a volume like this:
只需将您的 .sql 文件 (dbcreation.sql) 放在一个文件夹(即 /mysql_init)中,然后将该文件夹添加为一个卷,如下所示:
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.
MySQL 映像将在启动时执行 /docker-entrypoint-initdb.d 中的所有 .sql、.sh 和 .sql.gz 文件。
回答by ashatrov
1) Create dump file dbcreation.sql
1) 创建转储文件dbcreation.sql
2) Create import.shfile:
2)创建import.sh文件:
#!/usr/bin/env bash
mysql -u root -p$MYSQL_ROOT_PASSWORD < /tmp/dbcreation.sql
3) Create docker-compose.yaml
3) 创建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"
“- ./dbcreation.sql:/tmp/dbcreation.sql”-“- local_path:path_inside_container”
4) Run
4)运行
docker-compose up
docker exec database.dev bash /tmp/import.sh