I have a MySQL instance hosted in Google Cloud SQL, and I have a container which uses this database, I tried to initialize the database schema from the docker file using the following command:
FROM anapsix/alpine-java
ADD ./mysql/init.sql /docker-entrypoint-initdb.d
init.sql
SET sql_mode = '';
CREATE DATABASE IF NOT EXISTS `locations_schema`;
USE `locations_schema`;
CREATE TABLE `locations` (
`id` int(11) NOT NULL,
`value` varchar(255) NOT NULL,
`label` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
But unfortunately this is not working, is there any way I can achieve the init of a DB?
I think that you are getting confused implementing your solution.
If you have a unique Google Cloud MySQL instance used by your containers why are you trying to initialize the database schema each time a container is created from the new custom image? Isn't better to initialize it just connecting to it once manually?
However docker-entrypoint-initdb.d
is used to initialize local MySQL instances, not an instance running in a different machine. Notice that you will need at least to specify the address of the instance, a user and a password to let the container to connect to it. In order to do so there are different ways and you can find several guide, but I don't think that this is what you need to implement.
However If you are trying to init a MySQL instance running in the Docker container here you can find an awesome explanation how to do it, but I think you have to change the image you are starting from since I don't think that it contains MySQL.
You can use a script to do the initialize the DB without needing to pass the root password, provided MySQL is persisting data outside of the container and you specify a volume on the docker run command. You will need to specify environment variables specific to your environment. The script file needs to be added to the container via a Dockerfile. The Basic MySQL command line:
Set -e
Set -x
Then start the MySQL daemon
Mysql_pid=$!
You can add an echo for “..” to show until the MySQL admin has started, if you want.
mysql -e "GRANT ALL ON *.* TO root@'%' IDENTIFIED BY '' WITH GRANT OPTION"
Then shutdown your MySQL daemon
wait $mysql_pid -- wait for it to stop
The Docker documentation, https://docs.docker.com/samples/library/mysql/ offers more DB start options, including starting from an application in a docker container. You can also combine MySQL and docker commands for other database functions, like create schema, or creating multiple databases.