在 docker-compose 启动时创建数据库
我想使用 docker-compose.yml 文件中的环境变量创建一个 MySQL 数据库,但它不起作用.我有以下代码:
# 数据库数据库:图像:mysql:5.7卷:- 数据库数据:/var/lib/mysql重启:总是环境:MYSQL_ROOT_PASSWORD:秘密MYSQL_DATABASE:宅基地MYSQL_USER:rootMYSQL_PASSWORD:秘密端口:- 33061:3306"
谁能解释一下这个变量的作用?
解决方案还有一个选项可以为 mysql
容器提供一个初始化文件,该文件将在每次创建容器时应用.
>
数据库:图像:mysql:5.7端口:- 33061:3306"命令:--init-file/data/application/init.sql卷:- ./init.sql:/data/application/init.sql环境:MYSQL_ROOT_USER:rootMYSQL_ROOT_PASSWORD:秘密MYSQL_DATABASE:宅基地MYSQL_USER:rootMYSQL_PASSWORD:秘密
此类文件 (init.sql
) 可以包含您的初始数据库结构和数据 - 例如:
CREATE DATABASE IF NOT EXISTS dev;如果不存在则创建数据库测试;使用开发;如果不存在则创建表 (...);
I would like to create a MySQL database using environment variables in docker-compose.yml file, but it is not working. I have the following code:
# The Database
database:
image: mysql:5.7
volumes:
- dbdata:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: homestead
MYSQL_USER: root
MYSQL_PASSWORD: secret
ports:
- "33061:3306"
Could someone explain the function of this vars?
解决方案There is also an option to provide an init file for mysql
container which will be applied each time a container is created.
database:
image: mysql:5.7
ports:
- "33061:3306"
command: --init-file /data/application/init.sql
volumes:
- ./init.sql:/data/application/init.sql
environment:
MYSQL_ROOT_USER: root
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: homestead
MYSQL_USER: root
MYSQL_PASSWORD: secret
Such file (init.sql
) could contain your initial database structure and data - for example:
CREATE DATABASE IF NOT EXISTS dev;
CREATE DATABASE IF NOT EXISTS test;
USE dev;
CREATE TABLE IF NOT EXISTS (...);
相关文章