Multiple Databases in Official MySql Container

Hi,
I’m able a create a new single database with Docker run command
$ docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag

Then I bash into the mysql container with exec and create another database in their at the mysql> prompt. Now how do I do that with the docker run command itself.

Cheers!!!
K

The official mysql image has some features in its entrypoint script to help you initialize your database. Check out https://hub.docker.com/_/mysql/ and scroll down to “Initializing a fresh instance”. Basically you can drop in some .sql or .sh scripts into a certain location that can import whatever you want into your database.

Cheers!

1 Like

@programmerq It is wrong suggestion about creating another one Database through /docker-entrypoint-initdb.d
just because mouthed sql files will be imported by default to the database specified by the MYSQL_DATABASE variable. Since you can’t create DB in DB :slight_smile:

Created clear example of docker-compose with multiple databases, just use for your purposes:

Here is an example: https://gist.github.com/MKagesawa/a03892b8c44c015cd991c2c5311f1768
You can pass a shell script creating the dbs

# The official MySQL (https://hub.docker.com/_/mysql/) supports only one MYSQL_DATABASE environment variable.
# By modifying the entrypoint and passing shell script, you can create multiple dbs without having to make a mysql image just for this purpose.
  
version: '3'

services:
  # Some other service connecting to mysql
  
  db:
    image: mysql:5.6
    environment:
      - MYSQL_USER=root
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    entrypoint:
      sh -c "
        echo 'CREATE DATABASE IF NOT EXISTS firstDB; CREATE DATABASE IF NOT EXISTS secondDB;' > /docker-entrypoint-initdb.d/init.sql;
        /usr/local/bin/docker-entrypoint.sh --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
      "
    ports:
      - 3306:3306