{{announcement.body}}
{{announcement.title}}

MySQL Container to Preset Database From SQL File

DZone 's Guide to

MySQL Container to Preset Database From SQL File

In this article, take a look at how to start MySQL container with a pre-defined .sql file.

· Database Zone ·
Free Resource

Problem Statement

Start MySQL container with a pre-defined .sql (database, tables, insert, etc.) file.

Solution

MySQL
 




x
24


 
1
CREATE DATABASE TESTDB;
2
COMMIT;
3
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'my-secret-pw';
4
GRANT ALL ON TESTDB.* TO 'testuser'@'localhost';
5
 
          
6
COMMIT;
7
 
          
8
use TESTDB;
9
 
          
10
CREATE  TABLE IF NOT EXISTS TESTTABLE
11
(
12
  id INT NOT NULL AUTO_INCREMENT ,
13
  modifiedOn TIMESTAMP,
14
  createdOn TIMESTAMP,
15
  testname VARCHAR (50),
16
  PRIMARY KEY (id)
17
);
18
 
          
19
INSERT INTO TESTTABLE (testname, createdOn, modifiedOn) VALUES 
20
("name-1", NOW(), NOW()),
21
("name-2", NOW(), NOW()),
22
("name-3", NOW(), NOW()),
23
("name-4", NOW(), NOW());
24
© 2020 GitHub, Inc.



Shell
 




x


 
1
export containerName=mysql
2
export hostAddress=127.0.0.1
3
export hostPort=3306
4
export ROOT_USERNAME=root
5
export ROOT_PASSWORD=my-secret-pw
6
 
          
7
// download latest mysql container from docker hub
8
docker pull ${containerName}:latest
9
 
          
10
// start MySql container service
11
docker run --name ${containerName} -v ${CURRENT_PATH}/scripts:/docker-entrypoint-initdb.d -p ${hostPort}:${hostPort} -e MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD} -e MYSQL_DATABASE=${containerName} -e TZ='America/Los_Angeles' -d ${containerName} --verbose --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci &
12
 
          
13
// wait until container running...
14
sleep 15
15
 
          
16
// tail logs
17
docker logs -f $containerId &
18
 
          



  • Finally, execute the shell script

Issues You May Encounter on Docker Desktop

  • docker bind-address, update Docker Perferences > Settings > Resources with the IP as the below image 

More Information:

Topics:
mysql ,docker ,database ,tutoroal ,mysql scripts ,container ,sql file

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}