Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

sql - How to add a startup script to a mysql docker container?

I started a docker container with mysql.
Actually i want to create a new user and a new table - and i have to do it in the MySQL Workbench.

This ist my docker run command:
docker run -p 3306:3306 --name mysql-server -v ~/Development/web/myproject/docker/mysql:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:latest

My Question is:
How can i add a sql startup script (only for the first start of the container) which creates my user and my table?
Which steps do i have to do?

Could some one help me here?
Thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to create user via MYSQL_USER, MYSQL_PASSWORD env vars and use volume /docker-entrypoint-initdb.d to map directory with your startup scripts (.sh, .sql, .sql.gz)

docker run -p 3306:3306 --name mysql-server  
 -v ~/Development/web/myproject/docker/mysql:/var/lib/mysql 
 -v ~/Development/web/myproject/docker/yourstartupscripts:/docker-entrypoint-initdb.d 
 -e MYSQL_ROOT_PASSWORD=root 
 -e MYSQL_USER=youruser 
 -e MYSQL_PASSWORD=youruserpassword 
 -d mysql:latest

Explanation from: https://hub.docker.com/_/mysql/

MYSQL_USER, MYSQL_PASSWORD
These variables are optional, used in conjunction to create a new user and to set that user's password. This user will be granted superuser permissions (see above) for the database specified by the MYSQL_DATABASE variable. Both variables are required for a user to be created.

Initializing a fresh instance
When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...