0

I have created a MySQL docker container with

sudo docker run -d --name db-mysql -e MYSQL_ROOT_PASSWORD=mypassword -e MYSQL_DATABASE=DB mysql

I have schema.sql to create the schema

DROP DATABASE IF EXISTS `DB`;
CREATE DATABASE `DB`;
USE `DB`;

DROP TABLE IF EXISTS `Occurrences`;
CREATE TABLE `Occurrences` (
  `IdOccurrence` int NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) NOT NULL,
  `Min_probability` double NOT NULL,
  PRIMARY KEY (`IdOccurrence`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
INSERT INTO `Occurrences` VALUES (1,'Frequent',20),(2,'Probable',10),(5,'Possible',1),(6,'Rare',0.1),(7,'Remote',0);

And try to import it (in Ubuntu 18.04) with

sudo docker exec db-mysql mysql -uroot -pmypassword DB < schema.sql

However, I get this warning

mysql: [Warning] Using a password on the command line interface can be insecure.

But the database DB remains empty.

Where is my error?

7
  • 2
    Just to give another idea: Most programming languages have some sort of library to execute database migrations. If this mysql docker is part of another application, you may consider moving the migration one level up. Commented Mar 10, 2020 at 11:34
  • @maio290 Do you know where can I find how to migrate with mysql.connector in Python? Commented Mar 10, 2020 at 11:44
  • I am mostly on the Java and php side of development, so unfortunately, no. Commented Mar 10, 2020 at 11:45
  • Does it work without the first 3 lines in schema.sql? Commented Mar 10, 2020 at 11:48
  • 1
    You might need -h 127.0.0.1 -p 3306 for host and port if they're different to default Commented Mar 10, 2020 at 12:45

1 Answer 1

2

As stated in the documentation for the docker image you can initialize a container with a sql script:

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.

So if you start your container with the following it should startup with your schema:

sudo docker run -d --name db-mysql -e MYSQL_ROOT_PASSWORD=mypassword -e MYSQL_DATABASE=DB -v $PWD/schema.sql:/docker-entrypoint-initdb.d/schema.sql mysql
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.