Docker - Setting MariaDB



MariaDB is an open-source database with powerful performance, and scalable enterprise-grade security features, commonly used in RDBMS. It is popular in developing web applications and in handling warehousing applications.

Running MariaDB inside a Docker container provides several advantages: it ensures consistent environments, makes deployment easy, and is isolated from other services. Dockerizing MariaDB makes setups easy enabling developers to easily manage and scale database environments.

Prerequisites for Dockerizing MariaDB

Before we start Dockerizing MariaDB, we ensure that the following requirements are met −

  • Basic Docker Knowledge − Understand the basic concepts of Docker, images, containers, and basic Docker commands.
  • Installation of Docker on the Local Machine − Ensure that Docker is installed on your local machine. It can be downloaded and installed from https://www.docker.com.
  • MariaDB Knowledge − A little knowledge about MariaDB and how to configure and use MariaDB can accompany you in setting up the database and working with the same.
  • Text Editor or IDE − You'll need a text editor or integrated development environment (IDE) such as VS Code or Sublime Text.
  • CLI Access − Command-line or terminal access that will allow you to execute Docker commands.

Setting up a MariaDB Project

The first step is to create a project structure with all the files related to our MariaDB instance. This includes Dockerfile, configuration files, and any other resources needed for our project.

Step 1: Create the Project Directory

Lets create a new directory that will serve as the root for all your project files.

$ mkdir docker-mariadb
$ cd docker-mariadb
Setting up a MariaDB Project

Step 2: Initialize the Project

You can also initialize the project with a version control system like Git that can help track changes and collaborate with others.

$ git init

Step 3: Create a MariaDB Configuration File

We can customize MariaDB instances through configuration files. This includes customizations like setting specific user permissions, database options, or network settings.

Create a Configuration File

$ touch my-mariadb.cnf

Edit the Configuration File

Open this file in your text editor and add the following configuration settings. For example −

[mysqld]
bind-address = 0.0.0.0
port = 3306

Later, we will mount this configuration file into the Docker container, which will allow MariaDB to read these settings.

Step 4: Prepare SQL Scripts

Lets create an SQL script to initialize our database with a specific schema and data. This script will be executed when the MariaDB container is started.

Create a Directory for SQL Scripts

$ mkdir init-scripts

Create and Add an SQL Script

Now, lets create a file called init-db.sql inside the init-scripts directory and paste the following SQL script:

-- Create a new database

CREATE DATABASE IF NOT EXISTS my_database;

-- Switch to the new database

USE my_database;

-- Create a new table
CREATE TABLE users (

   id INT AUTO_INCREMENT PRIMARY KEY,

   name VARCHAR(100) NOT NULL,

   email VARCHAR(100) NOT NULL UNIQUE,

   created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

-- Insert some sample data into the table

INSERT INTO users (name, email) VALUES

('Alice Smith', 'alice@example.com'),

('Bob Johnson', 'bob@example.com'),

('Charlie Brown', 'charlie@example.com');	

This script automatically creates a database called my_database, then creates a users table with some basic fields, and inserts a few rows of sample data.

Step 5: Review Project Structure

Our project directory should look something like this −

docker-mariadb/

 init-scripts/

    init-db.sql

 my-mariadb.cnf

Running MariaDB Locally

Before we create a Docker container for our MariaDB application, lets try to run it locally on our machine. This will ensure that our setup works as expected. With this step, we can verify our MariaDB configuration and database initialization scripts.

Step 1: Install MariaDB Locally

Lets first install MariaDB on our local machine by following these steps −

On Ubuntu / Debian:

sudo apt update
sudo apt install mariadb-server mariadb-client

On CentOS / RHEL:

sudo yum install mariadb-server mariadb

On macOS (using Homebrew):

brew install mariadb
Install MariaDB Locally

After we have installed it, we can start the MariaDB service −

sudo systemctl start mariadb

For macOS:

brew services start mariadb

Step 2: Secure MariaDB Installation

MariaDB also provides a security script that lets you enhance the default installation by removing anonymous users, disabling root login remotely, and other secure settings. You can run the below command to secure your MariaDB installation −

$ sudo mysql_secure_installation

You can follow the prompts in your terminal to configure the security settings as per your requirements.

Secure MariaDB Installation

Step 3: Create and Test the Database

Now, lets manually execute the SQL script that we have prepared earlier to create the database, table, and insert data.

Access the MariaDB Shell

$ sudo mysql -u root -p
Access the MariaDB Shell

Execute the SQL Script

Now that we are inside the MariaDB shell, we can execute our script by running −

SOURCE /path/to/init-scripts/init-db.sql;

We need to replace /path/to/ with the actual path to your init-db.sql file.

Execute the SQL Script

Verify the Database and Data

Now we can verify that the database and table are actually created, and the data is inserted correctly −

USE my_database;
SELECT * FROM users;
Verify the Database and Data

Step 4: Stop MariaDB

Now that we have verified that our database setup is working fine locally, we can stop the MariaDB service −

$ sudo systemctl stop mariadb

For macOS:

$ brew services stop mariadb

Creating the Dockerfile

The Dockerfile contains all the instructions for creating a Docker image which will contain the MariaDB instance. Create a file called Dockerfile in the projects root directory. Here's an example Dockerfile for our MariaDB project −

# Use the official MariaDB image as the base image

FROM mariadb:latest

# Set environment variables for MariaDB root password and database name

ENV MARIADB_ROOT_PASSWORD=root_password

ENV MARIADB_DATABASE=my_database

# Copy the custom MariaDB configuration file into the container

COPY my-mariadb.cnf /etc/mysql/conf.d/

# Copy initialization SQL scripts into the Docker container

COPY init-scripts/ /docker-entrypoint-initdb.d/

# Expose the default MariaDB port

EXPOSE 3306

# Run the MariaDB server

CMD ["mysqld"]

Explanation of the Dockerfile Instructions

  • FROM mariadb:latest − This instruction mentions the base image for the Docker container that will be created using the Docker image. We will use the mariadb:latest image, which is an official MariaDB image provided by Docker Hub.
  • ENV MARIADB_ROOT_PASSWORD=root_password − This is used to set an environment variable MARIADB_ROOT_PASSWORD, which will be used by the MariaDB image to configure the root user's password.
  • ENV MARIADB_DATABASE=my_database − Next, we will set another environment variable MARIADB_DATABASE that ill create a new database automatically when the container is initialized.
  • COPY my-mariadb.cnf /etc/mysql/conf.d/ − The COPY instruction will copy the custom MariaDB configuration file (my-mariadb.cnf) from our local project directory to the appropriate configuration directory inside the Docker container (/etc/mysql/conf.d/).
  • COPY init-scripts/ /docker-entrypoint-initdb.d/ − Another COPY instruction will copy our SQL script from the init-scripts directory to the /docker-entrypoint-initdb.d/ directory inside the container. MariaDB will automatically execute these scripts during the container's initial startup.
  • EXPOSE 3306 − We can use the EXPOSE instruction to expose port 3306, which is the default port that MariaDB listens on. This will allow us to connect to the MariaDB server running in the container from outside the container.
  • CMD ["mysqld"] − Finally, this defines the command to start the MariaDB server when the container is launched.

Building the MariaDB Image

Now that our Dockerfile is created, the next step is to build the Docker image.

Step 1: Build the Docker Image

Lets navigate to the root of our project directory, where our Dockerfile is present, and run the following command −

$ docker build -t my-mariadb-image .

This will create our mariadb image from the Dockerfile and tag it as my-mariadb-image. The dot at the end specifies the build context which the the directory where the Dockerfile is located.

Build the Docker Image

Step 2: Verify the Image

Lets verify whether the image was created or not by listing all the images in our machine.

$ docker images

You can see that our my-mariadb-image listed.

Verify the Image

Running the MariaDB Docker Container

Now that our image is built, lets create the Docker container associated to this image.

Step 1: Run the Container

To start the container from our Docker image, we can use the following command −

$ docker run -d --name my-mariadb-container -p 3306:3306 my-mariadb-image
Run the Container

This will spin up a container in detached mode (-d flag), will map the exposed port 3306 from the container to the port 3306 of our local machine (-p flag), use the my-mariadb-image mentioned at the end to create a container named my-mariadb-container (--name).

Step 2: Connect to the MariaDB Container

You can use a MySQL client to connect to the MariaDB server inside the Docker container. For example, to connect using the MySQL client from your terminal, run −

mysql -h 127.0.0.1 -P 3306 -u root -p
USE my_database;
SELECT * FROM users;
Connect to the MariaDB Container

You can see that the database, table, and rows are already present that was created with the automated execution of the script that we created.

Conclusion

Dockerizing MariaDB is a really powerful and flexible way to manage a database environment, enabling great capabilities like portability, deploying easily, and environment isolation.

In this chapter, we explained how to configure a project in MariaDB; in particular, we went through setting up a Dockerfile, creating a custom Docker image, and configuring a MariaDB container. This not only streamlines the development process but will also ensure the ability to replicate environments, making easy the scaling, collaboration, and subsequent maintenance of database solutions.

FAQs on Setting MariaDB in Docker

There are some very Frequently Asked Questions(FAQ) about setting MariaDB in docker, this section tries to answer them briefly.

1. How do I connect a Node.js application to a Dockerized MariaDB database?

Connect your Node.js application to your Dockerized MariaDB database by using any of the available Node.js drivers for MariaDB. Mention the correct hostname in your connection string - it's usually mariadb - and a port. Make sure the Node.js application and the MariaDB container are connected to the same network.

2. How do I handle data persistence for MariaDB in a Docker container?

Persist the MariaDB data by using a data volume. This volume maps a directory on your host machine to one inside the container. All the data written to the MariaDB database is stored on the host volume and will not be lost once the container stops.

3. How do I secure a Dockerized MariaDB database?

Establish strong passwords for the MariaDB root identity and other identities. Limit access to the MariaDB container from the network. Regularly update the image and apply security patches. Consider turning on SSL/TLS encryption of communication. Put in place access control and management of users in MariaDB.

Advertisements