How to Dockerize MariaDB?

You can dockerize MariaDB in either of the following ways:

  1. Using docker-compose.yml;
  2. Using the docker run Command.

In either case, you can use the following command to ensure that your MariaDB container is running:

docker ps -a

This will allow you to check the status of your containers.

#Using docker-compose.yml

You can create a docker-compose.yml file in your project directory and define your MariaDB service within it, for example, like so:

version: '3'

services:
  mariadb:
    image: mariadb:latest
    container_name: my-mariadb
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=my-pwd

This docker-compose.yml file specifies a service named mariadb that uses the latest version of the official MariaDB Docker image. The container is named "my-mariadb", which can be accessed on host's port 3306. This allows external access to the MariaDB service using the root password, which is set as "my-pwd".

After creating your docker-compose.yml file, in the same directory in terminal, you can use the following command to run it:

docker-compose up -d

#Using the docker run Command

The docker run command is a basic Docker command that you can use to run a container from a specific image. For example, you can use the following command to start a MariaDB container, specifying a desired container name, port mapping, and environment variables for configuring the database:

docker run --name my-mariadb -p 3306:3306 -e MYSQL_ROOT_PASSWORD=my-pwd -d mariadb:latest

This command will pull the latest version of the official MariaDB image, and start a new container with the name "my-mariadb". The port 3306 of the container is mapped to port 3306 of the host, allowing you to access the MariaDB service from your local machine, with the root password set as "my-pwd".

As an alternative, you can also create your own Docker image using a Dockerfile, for example, like so:

FROM mariadb:latest

ENV MYSQL_ROOT_PASSWORD=my-pwd

EXPOSE 3306

CMD ["mysqld"]

You can run this Dockerfile using the following command:

docker build -t my-mariadb .

This will build the Docker image and tag it with the name "my-mariadb". The "." at the end of the command specifies the build context as the current directory.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.