Иногда мы хотим установить определенную версию MariaDB, MariaDB ColumnStore или MaxScale в определенной системе, но пакеты недоступны. Или, может быть, мы просто хотим изолировать MariaDB от остальной системы, чтобы быть уверенными, что мы не нанесем никакого ущерба.
Виртуальная машина,безусловно,послужит прицелом.Однако это означает установку системы поверх другой системы.Это требует много ресурсов.
Во многих случаях лучшим решением является использование контейнеров.Docker-это фреймворк,который запускает контейнеры.Контейнер предназначен для запуска определенного демона и программного обеспечения,необходимого для правильной работы этого демона.Docker не виртуализирует всю систему;контейнер включает только те пакеты,которые не входят в базовую систему.
Docker требует очень небольшого количества ресурсов.Он может работать на виртуализированной системе.Он используется как в разработке,так и в производственных средах.Docker-это проект с открытым исходным кодом,выпускаемый под лицензией Apache License,версия 2.
Обратите внимание: хотя в ваших репозиториях пакетов может быть пакет с именем docker , мы, вероятно, говорим не о Docker. Пакет Docker может называться docker.io или docker-engine .
Дополнительные сведения об установке Docker см. В разделе « Получить Docker» в документации Docker.
- Установка докера на вашу систему с помощью универсального скрипта установки
- Использование изображений MariaDB
- Бег и остановка контейнера
- Поиск и устранение неисправностей контейнера
- Доступ к контейнеру
- Подключение к MariaDB снаружи контейнера.
- Конфигурация портов для кластерных контейнеров и репликации
- Bootstrapping a new instance
- Environment Variables (-e
- Umask for running applications
- Do not delete your docker swarm cluster when using docker secrets for your docker based databases 😉
- Install Docker Engine
- Download MariaDB Docker Image
- Search for MariaDB Docker Image
- Download MariaDB Docker Image from Docker Hub
- List Downloaded Docker Images
- Running MariaDB Docker Container
- List Running Containers
- Checking MariaDB Container Logs
- Setting Persisting Data Volume for MariaDB Docker Container
- Stop, Pause, Restart Remove Docker Container
- Reference
- Other Related Tutorials
- Related content
- Using the docker-compose tool
- Conclusion
Установка докера на вашу систему с помощью универсального скрипта установки
С помощью приведенного ниже скрипта будут установлены репозитории Docker,необходимые модули ядра и пакеты на наиболее распространенных дистрибутивах Linux:
В некоторых системах вам, возможно, придется запустить dockerd daemon самостоятельно:
sudo systemctl start docker
sudo gpasswd -a docker
Использование изображений MariaDB
Самый простой способ использования MariaDB на Docker-это выбор изображения MariaDB и создание контейнера.
Вы можете загрузить образ MariaDB для Docker из официального Docker MariaDB или выбрать другой образ, который лучше соответствует вашим потребностям. Вы можете найти образ в Docker Hub (официальный набор репозиториев) с помощью этой команды:
docker mariadb
Например,если вы хотите установить образ MariaDB по умолчанию,вы можете набрать его:
docker pull mariadb:10.4
В результате будет установлена версия 10.4.Версии 10.2,10.3,10.5 также являются допустимыми вариантами.
Вы увидите список необходимых слоев.Для каждого слоя Docker сообщит,есть ли он уже в наличии,или о ходе его загрузки.
Получить список установленных образов:
Образ-это не запущенный процесс,это просто программное обеспечение,которое необходимо запустить.Чтобы запустить его,мы должны сначала создать контейнер.Команду,необходимую для создания контейнера,обычно можно найти в документации к образу.Например,чтобы создать контейнер для официального образа MariaDB:
docker run —name mariadbtest -e MYSQL_ROOT_PASSWORD=mypass -p 3306:3306 -d docker.io/library/mariadb:10.3
mariadbtest — это имя, которое мы хотим присвоить контейнеру. Если мы не укажем имя, идентификатор будет автоматически сгенерирован.
10.2 и 10.5 также являются допустимыми целевыми версиями:
docker run —name mariadbtest -e MYSQL_ROOT_PASSWORD=mypass -p 3306:3306 -d docker.io/library/mariadb:10.2
docker run —name mariadbtest -e MYSQL_ROOT_PASSWORD=mypass -p 3306:3306 -d docker.io/library/mariadb:10.5
При желании после имени образа мы можем указать некоторые параметры для mysqld . Например:
docker run —name mariadbtest -e MYSQL_ROOT_PASSWORD=mypass -p : -d mariadb: —bin —binlog-=MIXED
Докер ответит идентификатором контейнера.Но,чтобы убедиться,что контейнер создан и работает,мы можем получить список работающих контейнеров таким образом:
Мы должны получить выход,похожий на этот:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
819b786a8b48 mariadb «/docker-entrypoint. 4 minutes ago Up 4 minutes 3306/tcp mariadbtest
Бег и остановка контейнера
Докер позволяет перезагрузить контейнер одной командой:
docker restart mariadbtest
Контейнер можно также остановить вот так:
docker mariadbtest
Контейнер не будет уничтожен этой командой.Данные все равно будут жить внутри контейнера,даже если MariaDB не запущен.Чтобы перезапустить контейнер и увидеть наши данные,мы можем выдать:
С docker stop контейнер будет корректно завершен: сигнал SIGTERM будет отправлен процессу mysqld , и Docker будет ждать завершения процесса перед возвратом управления в оболочку. Однако также можно установить тайм-аут, по истечении которого процесс будет немедленно завершен с помощью SIGKILL . Или можно немедленно убить процесс, без тайм-аута.
docker stop —= mariadbtest
docker mariadbtest
В случае,если мы хотим уничтожить контейнер,возможно,потому,что изображение не соответствует нашим потребностям,мы можем остановить его и затем запустить:
Обратите внимание,что вышеприведенная команда не уничтожает том данных,который Docker создал для /var/lib/mysql.Если вы хотите уничтожить и этот том,используйте:
docker -v mariadbtest
Когда мы запускаем контейнер, мы можем использовать параметр —restart , чтобы установить политику автоматического перезапуска. Это полезно в производстве.
Допустимыми значениями являются:
Можно изменить политику перезапуска существующих,возможно,запущенных контейнеров:
docker
# , change the restart policy containers:
docker
Вариант использования для изменения политики перезапуска существующих контейнеров — выполнение обслуживания в производственной среде. Например, перед обновлением версии Docker мы можем захотеть изменить политику перезапуска всех контейнеров на « always , чтобы они перезапустились, как только новая версия будет запущена и запущена. Однако, если некоторые контейнеры остановлены и в данный момент не нужны, мы можем изменить их политику перезапуска на « unless-stopped .
Контейнер также можно заморозить с помощью команды pause . Docker заморозит процесс с помощью групп. MariaDB не будет знать, что он заморожен, и, когда мы unpause его, MariaDB возобновит свою работу, как ожидалось.
И pause и unpause принимают одно или несколько имен контейнеров. Итак, если мы запускаем кластер, мы можем заморозить и возобновить работу всех узлов одновременно:
docker node1 node2 node3
docker unpause node1 node2 node3
Оплата контейнера очень полезна,когда нам нужно временно освободить ресурсы нашей системы.Если контейнер в данный момент не является критичным (например,он выполняет какую-то пакетную работу),мы можем освободить его,чтобы позволить другим программам работать быстрее.
Поиск и устранение неисправностей контейнера
Если контейнер не запускается или работает некорректно,мы можем исследовать это с помощью следующей команды:
docker logs mariadbtest
Эта команда показывает, что демон отправил на стандартный вывод с момента последней попытки запуска — текст, который мы обычно видим, когда вызываем mysqld из командной строки.
В некоторых системах такие команды, как docker stop mariadbtest и docker restart mariadbtest , могут завершаться ошибкой с разрешениями. Это может быть вызвано AppArmor, и даже sudo не позволит вам выполнить команду. В этом случае вам нужно будет выяснить, какой профиль вызывает проблему, и исправить его или отключить. Полное отключение AppArmor не рекомендуется, особенно в производственной среде.
Чтобы узнать, какие операции были предотвращены AppArmor, см. Ошибки AppArmor в документации AppArmor.
Чтобы отключить профиль, создайте символическую ссылку с именем профиля (в данном примере mysqld ) на etc/apparmor.d/disable , а затем перезагрузите профили:
-s /etc/apparmor.d/usr.sbin.mysqld /etc/apparmor.d/disable/
sudo apparmor_parser -R /etc/apparmor.d/usr.sbin.mysqld
Дополнительные сведения см. В разделе « Макет политики» в документации AppArmor.
После отключения профиля может потребоваться запуск:
sudo service docker restart
docker system prune
Перезапуск системы позволит Docker работать нормально.
Доступ к контейнеру
Чтобы получить доступ к контейнеру через Bash,мы можем запустить эту команду:
docker -it mariadbtest bash
Теперь мы можем использовать обычные команды Linux, такие как cd , ls и т. Д. У нас будут права root. Мы даже можем установить наш любимый файловый редактор, например:
apt
apt install vim
В некоторых изображениях репозиторий по умолчанию не настроен,поэтому может потребоваться их добавление.
Подключение к MariaDB снаружи контейнера.
Если мы попытаемся подключиться к серверу MariaDB на localhost , клиент обойдет сеть и попытается подключиться к серверу, используя файл сокета в локальной файловой системе. Однако это не работает, когда MariaDB работает внутри контейнера, потому что файловая система сервера изолирована от хоста. Клиент не может получить доступ к файлу сокета, который находится внутри контейнера, поэтому он не может подключиться.
Поэтому соединения с сервером MariaDB должны осуществляться по TCP,даже если клиент запущен на той же машине,что и контейнер сервера.
После включения сетевых подключений в MariaDB,как описано выше,мы сможем подключиться к серверу снаружи контейнера.
mysql -h . -u root —
Эта простая форма подключения должна работать в большинстве ситуаций.В зависимости от Вашей конфигурации,может также потребоваться указать порт для сервера или форсировать TCP режим:
mysql -h -P
Конфигурация портов для кластерных контейнеров и репликации
Несколько серверов MariaDB,работающих в отдельных контейнерах Docker,могут подключаться друг к другу по TCP.Это полезно для формирования кластера Galera или для репликации.
При запуске кластера или настройке репликации через Docker мы хотим, чтобы контейнеры использовали разные порты. Самый быстрый способ добиться этого — сопоставить порты контейнеров с разными портами в нашей системе. Мы можем сделать это при создании контейнеров ( команда docker run ), используя параметр -p , при необходимости несколько раз. Например, для узлов Galera мы будем использовать сопоставление, подобное этому:
Во-первых,нам нужен образ системы,чтобы работать как демон.Если мы пропустим этот шаг,MariaDB и все базы данных будут потеряны при остановке контейнера.
Чтобы демонизировать изображение,мы должны дать ему команду,которая никогда не закончится.В следующем примере мы создадим демона Debian Jessie,который будет постоянно пинговать специальный адрес 8.8.8.8:
Содержание,воспроизводимое на этом сайте,является собственностью соответствующих владельцев,и это содержание не просматривается заранее компанией MariaDB.Взгляды,информация и мнения,выраженные в этом содержании,не обязательно представляют собой взгляды,информацию и мнения,выраженные MariaDB или любой другой стороной.
is one of the most popular database servers. Made by the original developers of MySQL.
We utilise the docker manifest for multi-platform awareness. More information is available from docker
and our announcement
lscr.io/linuxserver/mariadb:latest should retrieve the correct image for your arch, but you can also pull specific arch images via tags.
The architectures supported by this image are:
Find custom.cnf in /config for config changes (restart container for them to take effect) , the databases in /config/databases and the log in /config/log/myqsl
These settings can be mixed and matched with Docker ENV settings as you require, but the settings in the file will always take precedence.
Bootstrapping a new instance
We support a one time run of custom sql files on init. In order to use this place *.sql
This will have the same effect as setting the REMOTE_SQL environment variable. The sql will only be run on the containers first boot and setup.
# check all databases for errors
# repair all databases
# analyze all databases
# optimize all databases
After running the above commands, you may need to run the upgrade command again.
When this container initializes, if MYSQL_ROOT_PASSWORD is set an upgrade check will run. If an upgrade is required the log will indicate the need stop any services that are accessing databases in this container, and then run the command:
To help you get started creating a container from this image you can either use docker-compose or the docker cli.
Environment Variables (-e
You can set any environment variable from a file by using a special prepend FILE__
Will set the environment variable PASSWORD based on the contents of the /run/secrets/mysecretpassword
Umask for running applications
For all of our images we provide the ability to override the default umask settings for services started within the containers using the optional -e UMASK=022 setting. Keep in mind umask is not chmod it subtracts from permissions based on it’s value it does not add. Please read up
before asking for support.
We publish various
to enable additional functionality within the containers. The list of Mods available for this image (if any) as well as universal mods that can be applied to any one of our images can be accessed via the dynamic badges above.

Do not delete your docker swarm cluster when using docker secrets for your docker based databases 😉
In case you do, you have to reset the passwords in the docker databases.
Change your docker compose file and add the argument —skip-grant-tables which can be done by using command in your docker compose file. If you haven’t used command in your docker compose, just add the line below or just add the argument if you already use command.
After this change restart your docker container and login to it.
The last step is to remove the —skip-grant-tables in your docker compose file and restart the container using docker compose.
Welcome to our basic tutorial on how to install and run MariaDB as a Docker container. According to Docker website, “Docker is an open platform for developing, shipping, and running applications“. A container on the hand “is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings“.
Install Docker Engine
Install and Use Docker CE on CentOS 8
Install Docker CE on Ubuntu 20.04
Download MariaDB Docker Image
Every docker container is based off a specific image. Docker image contains everything that is necessary to run a container and is therefore a series of instructions that defines how an application is run.
You can build your own Docker image or simply utilize the images that the community have created. You can find the images at the Docker Hub.
In this tutorial, we will be utilizing the community available Docker images.
Search for MariaDB Docker Image
First off, you need to identify the name of the specific MariaDB Docker Image. To search for the image on the docker hub, simply run the command below;
docker search mariadb
You will get a ton of MariaDB images that have been created;
Download MariaDB Docker Image from Docker Hub
The command downloads the image to your system, if doesn’t already exist.
By default, when you pull a docker image, the latest version of it is downloaded. If you need to download other versions of MariaDB Docker Images, for example, MariaDB 10.3 Docker Image, simply use the command;
docker pull mariadb:10.3
You can see a wide range of tags you can use on Docker Hub MariaDB page.
List Downloaded Docker Images
You can list locally available images using the docker images command.
REPOSITORY TAG IMAGE ID CREATED SIZE
mariadb latest 8075b7694a2d 8 days ago 407MB
We have the latest MariaDB Docker Image downloaded.
Running MariaDB Docker Container
In our case here, the name of the image is, mariadb (with latest being the tag);
docker run —name mariadbdemo -e MYSQL_ROOT_PASSWORD=password -d mariadb
The command above basically creates and run (in the background, -d) the MariaDB Docker container based on the latest image version available, sets the MariaDB database root password to password (-e MYSQL_ROOT_PASSWORD=password) and the name of the container as mariadbdemo (—name mariadbdemo, random names are usually set for containers if you don’t specify the name).
If you have other versions of MariaDB Docker Images, you can specify the tags to run a container based on that specific image. For example, assuming we had MariaDB 10.4 image and we would like to run a container based on that image, you could specify the tag as, mariadb:10.4.
docker run —name mariadbdemo -d -e MYSQL_ROOT_PASSWORD=password mariadb:10.4
List Running Containers
Once you have run a container, you can list them using the docker ps command.
To list all running and stopped containers, use docker ps -a command.
To get just the running container IDs;
docker ps -q
Checking MariaDB Container Logs
docker logs mariadbdemo
docker logs ce03099cfffa
Your MariaDB docker container is now running in the background. You can access it by:
docker exec -it mariadbdemo bash
This takes you to container interactive bash shell;
You can as well login to your MariaDB container using mysql client on your host.
For this, you need to install MySQL client. For example, on Ubuntu systems, you can install MySQL client by running the command
apt install mysql-client
«SecondaryIPAddresses»: null,
«IPAddress»: «172.17.0.2»,
«IPAddress»: «172.17.0.2»,
In this case, our MariaDB container is assigned an IP address of 172.17.0.2.
To use the MySQL host client to connect to our container;
mysql -u root -p -h 172.17.0.2
The command assumes that the container is listening on a default port, 3306.
You will need to use the password that you specified with the MYSQL_ROOT_PASSWORD variable when running the container above.
NOTE: The IP address assigned to your docker container is dynamic and if you happen to restart the container, it will be assigned a new/different IP address within the docker network.
If you have some external applications that needs to access your database running on MariaDB container, you need to expose the container port for external via the host system. By default, the container is only accessible within the host system
For example, our MariaDB container is listening on the default port 3306.
If you check your listening ports on your host for MariaDB port, you wont find any;
docker run —name mariadbdemoport -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -d mariadb
If you need to use the same names for the container, just stop the existing container and remove it and relaunch new container using the same name.
Let us verify the port exposure
If you check on the PORTS column, you realize for our new container, the container port is exposed on port 3306 on the host and is listening on all interfaces;
Checking the listening ports on the host again;
LISTEN 0 4096 *:3306 *:*
If you need to map the container port to a dynamic host port, use the option;
docker run —name mariadbdemo-dport -p 3306 -e MYSQL_ROOT_PASSWORD=password -d mariadb
As you can see, the container port is exposed on dynamic port 32768.
You can always find what dynamic port the container port is mapped to using the docker port command;
docker port mariadbdemo-dport
Setting Persisting Data Volume for MariaDB Docker Container
When a container is removed, all if its data it had written to its internal volumes are removed as well. To ensure data is persistent across container deletes, you can map MariaDB Docker container internal volume to some host directory.
The default data directory for MariaDB container is /var/lib/mysql.
For example, if I want the container data to be written to my host directory /opt/mariadb/data, the first create the directory and run a container mapping the data directories using the -v option.
mkdir -p /opt/mariadb/data
docker run —name mariadbdemo-volume -v /opt/mariadb/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=password -d mariadb
Therefore, any container data that is written to the container data directory, /var/lib/mysql, will be written to the data directory on host, /opt/mariadb/data at the same time.
Stop, Pause, Restart Remove Docker Container
To stop a running container, use the docker stop command;
docker stop mariadbdemo
You can stop all containers using their ids;
docker stop $(docker ps -q)
Once you are done with a container, you can choose to remove it;
docker rm mariadbdemo
To force removal;
docker rm —force mariadbdemo
To pause the container;
docker pause mariadbdemo
docker restart mariadbdemo
To list docker volumes;
docker volume ls
Find specific docker container volume using docker inspect command.
Remove specific volume;
docker volume rm volume-name
That marks the end of our guide on how to install and run MariaDB as a Docker Container.
Reference
MariaDB – Docker Hub
Other Related Tutorials
Install and Deploy Kubernetes Cluster on Ubuntu 20.04
In this guide we are going to explore how to run Mariadb 10 locally with docker and docker compose. This can be helpful if you want to run Mariadb 10 locally without installing it in your machine or if you want to run multiple versions of Mariadb seamlessly.
Related content
We are going to use the docker run command to achieve our goal. The version of Mariadb that we want is mariadb:10.7 – the latest version of mariadb image.
Create data dir
mkdir -p ~/apps/mariadb/data
Run the container
In the above command:
To check that our container is running as expected, use the docker ps command:
In my case the container is running as my-mariadb the name we gave it. We can login to the container using the docker exec command while executing /bin/bash interactively. Here we are also logging in to posgtres with the credentials we specified above and checking the version.
If you need to clean up the container when not in use, you can stop and remove the container using this command:
❯ docker stop my-mariadb
my-mariadb
➜ docker rm my-mariadb
my-mariadb
Using the docker-compose tool
We can achieve the same functionality with docker-compose. Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services.
Docker Compose allows you to define the service (Mariadb in our case) with properties like the image to use, ports to expose, volumes to mount and environment variables.
Here is how we would use docker-compose to achieve the functionality above. Save this as docker-compose.yaml:
Now bring up the containers:
Verify the container processes using the ps command:
To login to the container and login to Mariadb, use this:
Conclusion
In this guide we managed to run Mariadb 10 as a container in our system, we explored using the docker run command while passing the required arguments an alternative approach of simplifying the process with docker-compose






