Main Tutorials

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:

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:

init.sql

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.

Terminal

  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.

3. Access the MariaDB running container

Access the running MariaDB container and display the data inserted by init.sql.

Terminal

  docker exec -it some-mariadb mariadb -uroot -p
Terminal

$ 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

4. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments