How to run an init script for Docker MariaDB
The official Docker mariadb image will run all *.sh
and *.sql
scripts in its /docker-entrypoint-initdb.d
directory automatically when it starts.
Table of contents:
- 1. Create an init.sql
- 2. Run an init script for Docker MariaDB
- 3. Access the MariaDB running container
- 4. References
Technologies used:
- Docker 24.0.5
- Official Docker
mariadb
image (latest tag)
1. Create an init.sql
Creates an init.sql
with the following content:
CREATE DATABASE IF NOT EXISTS fruitdb;
USE fruitdb;
CREATE TABLE IF NOT EXISTS fruits (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
quantity INT NOT NULL
);
INSERT INTO fruits (name, quantity) VALUES
('Apple', 10),
('Banana', 20),
('Cherry', 30);
2. Run an init script for Docker MariaDB
When the MariaDB container starts, it automatically runs *.sh
and *.sql
scripts in its /docker-entrypoint-initdb.d
directory. We can mount the local init.sql
to the container’s /docker-entrypoint-initdb.d/init.sql
to run the init script for the Docker MariaDB container.
The below command runs the init.sql
and starts the MariaDB container.
docker run --name some-mariadb -v /Users/yongmookkim/projects/docker/init.sql:/docker-entrypoint-initdb.d/init.sql -e MARIADB_ROOT_PASSWORD=password -d mariadb
The command -v /path/to/init.sql:/docker-entrypoint-initdb.d/init.sql
mounts the local /path/to/init.sql
file to the container’s /docker-entrypoint-initdb.d/init.sql
.
Further Reading
Docker – Running MariaDB as a container
3. Access the MariaDB running container
Access the running MariaDB container and display the data inserted by init.sql
.
docker exec -it some-mariadb mariadb -uroot -p
$ docker exec -it some-mariadb mariadb -uroot -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 11.1.2-MariaDB-1:11.1.2+maria~ubu2204 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)]> use fruitdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [fruitdb]> select * from fruits;
+----+--------+----------+
| id | name | quantity |
+----+--------+----------+
| 1 | Apple | 10 |
| 2 | Banana | 20 |
| 3 | Cherry | 30 |
+----+--------+----------+
3 rows in set (0.001 sec)
MariaDB [fruitdb]> exit
Bye