5

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!

m1well
  • 716
  • 4
  • 15
  • 28

1 Answers1

18

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.

adam187
  • 3,193
  • 21
  • 15
  • thank you `-v ~/Development/web/myproject/docker/yourstartupscripts:/docker-entrypoint-initdb.d` -> that was it what i searched for :) – m1well Sep 29 '17 at 06:34
  • what is the difference by creating a new user by script or creating it in the docker run command? – m1well Sep 29 '17 at 06:35
  • 2
    @m1well you can check out exactly how user is created here: https://github.com/docker-library/mysql/blob/0590e4efd2b31ec794383f084d419dea9bc752c4/5.7/docker-entrypoint.sh#L166-L174 – adam187 Sep 29 '17 at 07:34
  • ah ok - so it is the same way like i do it in my script. then i prefer my script :) -- thank you! – m1well Sep 29 '17 at 07:53
  • On any subsequent docker startups the scripts will not be executed right ? – MADforFUNandHappy Nov 21 '20 at 17:50