Ubuntu 및 CentOS에서 MariaDB를 설치 및 구성하는 방법

널리 사용되는 오픈 소스 관계형 데이터베이스 관리 시스템(RDBMS)인 MariaDB를 설치하고 설정하는 과정을 자세히 알아보겠습니다.

커뮤니티에서 개발되었으며 상업적 지원도 제공됩니다. MariaDB는 MySQL과의 높은 호환성을 목표로 하며, 일부 차이점은 있지만 대부분 호환됩니다.

본 글에서는 Ubuntu 20.x 및 CentOS 7.x/8.x 환경에서 MariaDB 설치 및 설정을 다루고, 마지막으로 성능 향상 및 보호를 위한 몇 가지 주요 모범 사례를 소개합니다.

Ubuntu 환경의 MariaDB

Ubuntu 20.x에서는 MariaDB를 기본 저장소에서 바로 이용할 수 있습니다. 우리는 이 과정을 위해 apt 패키지 관리자를 사용할 것입니다.

먼저, 다음 명령을 실행하여 apt 저장소 데이터를 최신 상태로 업데이트합니다.

$ sudo apt update

저장소 데이터가 업데이트되면, 다음 명령을 사용하여 MariaDB 서버를 설치합니다.

$ sudo apt install mariadb-server

이 명령은 MariaDB와 필요한 종속 패키지를 설치합니다. 설치 진행 중 나타나는 프롬프트에 ‘Y’를 입력하여 설치를 진행하십시오.

Do you want to continue? [Y/n] Y

CentOS 7.x 환경의 MariaDB

CentOS 7.x의 기본 CentOS 저장소에서 제공되는 MariaDB 버전은 5.x입니다. 여기서는 사용 가능한 최신 버전의 MariaDB를 설치하겠습니다.

이를 위해 먼저 추가 yum 저장소를 구성해야 합니다. MariaDB는 mariadb_repo_setup 스크립트를 사용하여 간단하게 설정할 수 있도록 지원합니다. 저장소 설정을 가져오려면 CentOS 7.x 시스템에서 다음 명령들을 실행하십시오.

$ sudo yum install wget
$ wget https://downloads.mariadb.com/MariaDB/mariadb_repo_setup
$ chmod +x mariadb_repo_setup
$ sudo ./mariadb_repo_setup

이 스크립트는 MariaDB의 최신 버전을 자동으로 설치하는 데 필요한 yum 저장소를 설정합니다. 작성 시점에서 최신 버전은 10.x 버전입니다.

또는 수동으로 저장소를 설정하려면, 다음 명령으로 새로운 repo 파일을 생성하여 수동으로 yum 저장소를 구성할 수도 있습니다.

$ sudo vi /etc/yum.repos.d/MariaDB.repo

그런 다음, repo 파일에 다음 정보를 추가하고 저장합니다.

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.5/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

이제 MariaDB를 설치하려면 다음 명령을 실행합니다.

$ sudo yum install MariaDB-server

설치 중 나타나는 모든 프롬프트에 ‘y’를 입력하여 확인합니다.

Is this ok [y/d/N]: y

이것으로 MariaDB 서버 및 종속 패키지 설치가 완료됩니다.

CentOS 8.x 환경의 MariaDB

CentOS 8.x의 경우, 기본 저장소에서 10.3 이상의 버전을 이용할 수 있습니다. 따라서 dnf 명령을 사용하여 MariaDB를 직접 설치할 수 있습니다.

sudo dnf install mariadb-server

또는 사용 가능한 최신 버전을 원한다면 CentOS 7.x에 대한 이전 섹션에 제공된 수동 방법을 따르십시오.

MariaDB 서비스 시작

Ubuntu 시스템에서는 설치 직후 MariaDB 서비스가 자동으로 실행되지만, CentOS에서는 관련 서비스를 수동으로 활성화하고 시작해야 합니다.

Ubuntu 및 CentOS 모두에서 다음 명령을 실행하여 MariaDB 서비스를 시작하고, 부팅 시 자동 시작되도록 설정하고, 서비스 상태를 확인하십시오.

$ sudo systemctl start mariadb.service
$ sudo systemctl enable mariadb.service
$ sudo systemctl status mariadb.service

출력 결과:

$ sudo systemctl start mariadb.service
$ sudo systemctl enable mariadb.service
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
$ sudo systemctl status mariadb.service
● mariadb.service - MariaDB 10.5.8 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf
   Active: active (running) since Thu 2020-12-31 13:20:04 IST; 13s ago
     Docs: man:mariadbd(8)
           https://mariadb.com/kb/en/library/systemd/
 Main PID: 13521 (mariadbd)
   Status: "Taking your SQL requests now..."
   CGroup: /system.slice/mariadb.service
           └─13521 /usr/sbin/mariadbd

Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] InnoDB: 10.5.8 started; log sequence number 45118; transaction id 20
Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] Plugin 'FEEDBACK' is disabled.
Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] InnoDB: Buffer pool(s) load completed at 201231 13:20:04
Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] Server socket created on IP: '::'.
Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] Reading of all Master_info entries succeeded
Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] Added new Master_info '' to hash table
Dec 31 13:20:04 centos7vm mariadbd[13521]: 2020-12-31 13:20:04 0 [Note] /usr/sbin/mariadbd: ready for connections.
Dec 31 13:20:04 centos7vm mariadbd[13521]: Version: '10.5.8-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server
Dec 31 13:20:04 centos7vm systemd[1]: Started MariaDB 10.5.8 database server.
$

MariaDB 보안 강화

MariaDB 설치 후 첫 번째 단계로, 루트 비밀번호를 설정하고, 원격 루트 로그인을 비활성화하고, 테스트 데이터베이스 및 익명 사용자를 제거하고, 마지막으로 권한을 다시 로드하여 배포 환경을 보호해야 합니다.

다음 명령을 실행하여 MariaDB를 강화하십시오.

$ sudo mysql_secure_installation

특정 요구 사항이 없다면, 제시되는 안내에 따라 기본 설정을 적용할 수 있습니다.

출력 결과:

$ sudo mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] n
 ... skipping.

You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] n
 ... skipping.

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!
$

여기서는 시스템 인증을 사용하므로 MariaDB는 이미 보호되어 있으므로 별도의 루트 암호를 설정하지 않았습니다. 필요에 따라 별도의 루트 암호를 설정할 수도 있습니다.

설정 확인

MariaDB 설정을 확인하려면, 다음 명령을 실행하십시오 (mysql_secure_installation을 실행하는 동안 설정한 암호를 지정하거나, 건너뛴 경우 시스템의 루트 자격 증명을 사용).

$ sudo mysqladmin -u root -p version
Enter password:
mysqladmin  Ver 9.1 Distrib 10.5.8-MariaDB, for Linux on x86_64
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Server version          10.5.8-MariaDB
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 53 min 17 sec

Threads: 2  Questions: 77  Slow queries: 0  Opens: 20  Open tables: 14  Queries per second avg: 0.024
$

다음과 같이 루트 계정 대신 새로운 관리자 계정을 설정할 수 있습니다 (관리자 계정에 설정하려는 비밀번호 값을 적절히 변경하십시오).

$ sudo mariadb
Welcome to the MariaDB monitor.  Commands end with ; or g.
Your MariaDB connection id is 44
Server version: 10.5.8-MariaDB MariaDB Server

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)]> GRANT ALL ON *.* TO 'admin'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
Query OK, 0 rows affected (0.003 sec)

MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> exit
Bye
$

다음과 같이 새로운 관리자 계정으로 접속을 확인합니다 (이전 단계에서 설정한 비밀번호를 입력하십시오).

$ mysqladmin -u admin -p version
Enter password:
mysqladmin  Ver 9.1 Distrib 10.5.8-MariaDB, for Linux on x86_64
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Server version          10.5.8-MariaDB
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 56 min 59 sec

Threads: 2  Questions: 83  Slow queries: 0  Opens: 20  Open tables: 14  Queries per second avg: 0.024
$

운영체제 (OS) 최적화

MariaDB를 설치하고 보안 설정을 마친 후, 최적의 성능을 위해 운영체제와 데이터베이스를 조정하는 추가 단계를 고려해야 합니다. 이러한 조정은 시스템 구성, 사용량 패턴, 사용자 수 및 다양한 다른 요소에 따라 달라질 수 있습니다.

운영체제 관점에서, 다음은 MariaDB를 위해 조정할 수 있는 일부 시스템 매개변수입니다.

Linux 커널 설정 – IO 스케줄러

MariaDB에 권장되는 IO 스케줄러는 noop 및 Deadline입니다. 현재 사용 중인 IO 스케줄러를 확인하려면 다음 명령을 사용하십시오.

$ sudo cat /sys/block/sda/queue/scheduler
[mq-deadline] kyber bfq none
$

다음 명령을 실행하여 임시로 스케줄러를 변경할 수 있으며, 이는 시스템 성능에 즉시 적용됩니다.

$ sudo echo noop > /sys/block/sda/queue/scheduler

영구적으로 설정하려면, GRUB 구성 파일 (/etc/default/grub)에서 해당 설정을 수정하고 GRUB를 재빌드하고 시스템을 재부팅해야 합니다.

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash elevator=noop"

리소스 제한 – 열린 파일 제한

Linux는 일반적으로 각 프로세스가 열 수 있는 파일 디스크립터의 수를 제한합니다. 활발하게 사용되는 데이터베이스 시스템의 경우, 이 제한을 쉽게 초과하거나 성능에 영향을 줄 수 있습니다. 많은 Linux 시스템에서 기본 제한은 1024입니다. 또한, soft 및 hard 제한 옵션이 있습니다.

제한을 늘리려면 /etc/security/limits.conf 파일에 다음 줄을 추가하면 됩니다.

mysql soft nofile 65535
mysql hard nofile 65535

mysql 사용자가 새로운 제한을 인식하고 사용할 수 있도록 시스템을 재부팅해야 합니다. 다음 명령으로 확인할 수 있습니다.

$ ulimit -Sn
65535
$ ulimit -Hn
65535

리소스 제한 – 코어 파일 크기

Linux는 코어 파일의 크기를 제한합니다. 여기에도 soft 및 hard 제한이 있으며, 기본적으로 soft 제한은 코어 파일 생성을 효과적으로 비활성화하는 0으로 설정됩니다. 코어 파일 생성을 허용하려면, 코어 덤프 생성에 필요한 추가 설정을 참고하여 /etc/security/limits.conf에서 값을 다음과 같이 늘릴 수 있습니다.

mysql soft core unlimited
mysql hard core unlimited

시스템 재부팅 후, mysql 사용자는 ulimit 명령을 사용하여 새로운 값을 확인할 수 있습니다.

$ ulimit -Sc
unlimited
$ ulimit -Hc
unlimited

스왑 (Swap) 설정

Linux의 Swappiness 값은 시스템이 메모리에서 구성된 스왑 공간으로 페이지를 스왑할 가능성을 결정합니다. 일반적으로 기본값은 60이며, 다음 명령으로 확인할 수 있습니다.

sysctl vm.swappiness

값의 범위는 0에서 100까지이며, 값이 낮을수록 스왑 사용 가능성이 낮아집니다. MariaDB만 실행하는 데이터베이스 서버에서 스왑 사용을 가능한 한 줄이려면 이 값을 0으로 설정하는 것이 바람직할 수 있습니다. 여기서 swappiness 값을 0으로 설정하는 것은 다른 시스템 설계 요소를 고려하여 신중하게 접근해야 합니다. 메모리 사용량이 높거나 I/O 부하가 큰 경우, 커널에 의해 메모리 부족 (OOM) 프로세스가 종료될 수 있기 때문입니다.

데이터베이스 워크로드 및 MariaDB 환경에 낮은 swappiness 설정이 권장되므로 swappiness 값을 1로 설정하는 것이 좋습니다. /etc/sysctl.conf 파일에 다음 줄을 추가하여 이 변경 사항을 영구적으로 만들 수 있습니다.

vm.swappiness = 1

sysctl 명령을 사용하여 즉시 변경할 수 있지만, 변경 사항은 시스템을 재부팅한 후에 적용됩니다.

sysctl -w vm.swappiness=1

파일 시스템 최적화

MariaDB에 적합한 Linux 파일 시스템은 일반적으로 ext4, XFS 및 Btrfs로 간주됩니다. 이들은 기본 Linux 커널에 포함되어 있으며, 널리 지원됩니다. 이러한 파일 시스템은 대부분의 Linux 배포판에서 사용할 수 있습니다. 각 파일 시스템에는 고유한 속성과 기능이 있으므로, 적절히 검토한 후 요구 사항에 따라 선택할 수 있습니다.

또한 데이터베이스 서버에서는 파일 접근 시간을 기록할 필요성이 거의 없습니다. 성능을 높이기 위해 이 기능을 비활성화할 수 있습니다. 관련 파일 시스템을 noatime 옵션으로 마운트하거나 /etc/fstab 파일의 마운트 옵션에 추가하여 영구적으로 설정할 수 있습니다.

데이터베이스 (DB) 최적화

MariaDB 내부에는 요구 사항에 따라 맞춤 설정할 수 있는 여러 조정 가능한 요소들이 있습니다. 여기서는 그 중 몇 가지를 논의합니다.

MariaDB는 대부분 my.cnf 파일을 통해 구성됩니다.

Ubuntu에서 my.cnf 파일은 다음 경로에서 찾을 수 있습니다.

/etc/mysql/my.cnf

CentOS에서는 다음 경로에 있습니다.

/etc/my.cnf

구성 파일에서 조정 가능한 변수에 대한 자세한 내용은 다음 링크에서 확인할 수 있습니다: 여기.

또한 MariaDB에서 사용되는 엔진 유형, 즉 MyISAM, InnoDB 또는 XtraDB에 따라 달라집니다. 둘 다 고유한 장단점이 있으며, 선택은 데이터베이스 및 애플리케이션 요구 사항에 따라 달라집니다.

innodb_buffer_pool_size는 사용 가능한 메모리의 약 80%로 설정해야 합니다. 이렇게 하면 작업 데이터 세트의 80%가 메모리에 보관되어 성능을 향상시킬 수 있습니다.

기타 중요한 조정 가능한 매개변수는 다음과 같습니다.

innodb_log_file_size
innodb_flush_method
innodb_thread_sleep_delay
innodb_adaptive_max_sleep_delay
innodb_buffer_pool_instances
innodb_buffer_pool_size
innodb_max_dirty_pages_pct_lwm
innodb_read_ahead_threshold
innodb_thread_concurrency

InnoDB 또는 XtraDB 변수 조정에 대한 자세한 내용은 다음 링크에서 확인할 수 있습니다: 여기. MariaDB에서 사용 가능한 모든 조정 옵션에 대한 가이드를 참조하십시오.

관심이 있다면 다음 자료를 참고하여 SQL 및 NoSQL에 대해 더 자세히 알아보십시오.

결론

MariaDB는 관계형 DBMS에서 널리 사용되는 선택 중 하나입니다. 다양한 커뮤니티의 지원을 받는 오픈 소스라는 점 또한 장점입니다.

자세한 내용을 알아보려면 다음 링크에서 공식 문서를 참조하십시오. 여기에는 기본 SQL, 마이그레이션, MariaDB 관리, 고가용성, 성능 튜닝, 스토리지 엔진, 프로그래밍 및 사용자 지정과 같은 주제가 포함됩니다. 클러스터를 사용하지 않는 경우, 바이너리 로깅을 비활성화할 수도 있습니다.