First, write the Dockerfile as follows.
Dockerfile
FROM mariadb:latest
COPY ./init.sql /docker-entrypoint-initdb.d/
VOLUME [ "/var/lib/mysql" ]
Specify the original image of MariaDB with FROM.
Then COPY sends the local file ʻinit.sql to the directory /docker-entrypoint-initdb.d/in the container. The purpose of this is to place the table etc. first when launching theMariaDBcontainer. Finally,VOLUME saves the MariaDBdata in the container locally. The purpose of this is to save the save data locally so that the data will not be lost if you stop theMariaDB` container.
By preparing ʻinit.sql` as shown below, the table will be created when the container is started.
init.sql
CREATE DATABASE test;
USE test;
CREATE TABLE test(name varchar(10));
Here, we first create a database named test.
Then select the database test.
Finally, we are creating a table named test.
Here, the column name is only name, and its type is a variable length string.
After creating the above file, create a Docker ʻImage` file.
Execute the following command in the directory where the above files are located.
$ docker build -t mariadb .
In addition, start the container with the following command.
$ docker run --name mariadb -e MYSQL_ROOT_PASSWORD=password -dp 3306:3306 mariadb
Here, the container name is mariadb.
The database password is password. ** Without this, startup will fail. ** **
The port to open is specified by local port number: container port number. Here, both can be accessed by opening 3306 at localhost: 3306.
You can enter the container with the following command (although you can also enter it from Docker Desktop etc.).
$ docker exec -it mariadb bash
Furthermore, you can execute SQL from the command line by going inside the container and executing the following.
root@4ec9744dff6e:/# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.5-MariaDB-1:10.5.5+maria~focal mariadb.org binary distribution
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Recommended Posts