2019년 1월 13일 일요일

CentOS 7에 MariaDB 10.3 설치하기

 최근 CentOS 7에 Maria DB를 설치할 일이 생겨서 설치하는 김에 여기에 설치 과정을 정리해 보려고 한다.

 환경에 대해서 간단히 설명하자면 Amazon Lightsail 가상 서버에 CentOS 7을 설치하고 Maria DB 10.3 버전을 설치할 것이다. 현재 Maria DB의 최신 버전은 10.3이다.

Maria DB repository 설정


 https://downloads.mariadb.org/mariadb/repositories/ 에 접속하면 리눅스 배포본에 따라 각 repository로 부터 설치할 수 있는 방법을 제시해준다. 여기서 제시하는 방법대로 따라하도록 하자.

 가장 먼저 해야할 것이 yum repository를 설정하는 것이다. 아래 명령으로 /etc/yum.repos.d/ 디렉토리에 MariaDB.repo 라는 파일을 만들고 그 아래 내용을 넣도록 하자.

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

# MariaDB 10.3 CentOS repository list - created 2019-01-13 00:47 UTC
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.3/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

Maria DB 설치


 repository 설정을 했으면 아래 명령으로 YUM을 통해서 Maria DB를 설치할 수 있다.

$ sudo yum install MariaDB-server MariaDB-client

 설치가 진행되면서 몇 번 묻는 질문에는 모두 y를 선택하면 된다. 설치가 완료되고 나면 아무런 설정을 하지 않아도 기본 설정값으로 실행할 수 있다.

Maria DB 서버 시작


 설정 파일을 열어보면 사실 아무것도 설정하고 있는 게 없다. 하지만 그래도 기본값을 가지고 있어서 바로 시작시켜보면 정상적으로 서버가 시작된다. 아래 명령으로 시작 시켜보도록 하자.

# mariadb가 부팅 시 자동 시작되도록 한다.
$ sudo systemctl enable mariadb

# mariadb를 시작시킨다.
$ sudo systemctl start mariadb
# 또는 service 명령으로 시작시킬 수도 있다.
$ sudo service mariadb start

 정상적으로 시작되었는지 아래 명령으로 알아보도록 한다.

$ sudo service mariadb status
Redirecting to /bin/systemctl status mariadb.service
● mariadb.service - MariaDB 10.3.12 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 일 2019-01-13 02:46:47 UTC; 9min ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
  Process: 29208 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 29164 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`/usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION=$VAR || exit 1 (code=exited, status=0/SUCCESS)
  Process: 29162 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
 Main PID: 29176 (mysqld)
   Status: "Taking your SQL requests now..."
   CGroup: /system.slice/mariadb.service
           └─29176 /usr/sbin/mysqld
....
 정상적으로 시작되었으면 active(running) 상태 문구가 보일 것이다.

Maria DB 보안 설정하기


 서버가 정상적으로 시작되었으면 이제 기본적인 보안 설정을 해야한다. 보안 설정이라니 까다로울 것 같지만 사실 스크립트 하나 실행해주면 된다. 초기 mysql 시절에는 매번 수작업으로 했었던 것 같은데 이제는 제공되는 스크립트 하나를 실행해주면 되니 정말 간단해졌다. 아래 명령을 실행해보자.

$ 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
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

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

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

Set root password? [Y/n] 
New password: [root 계정을 위한 비밀번호 설정]
Re-enter new password: [바로 위에서 설정한 값 다시 입력]
Password updated successfully!
Reloading privilege tables..
 ... Success!


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] [Enter]
 ... 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] [Enter]
 ... 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] [Enter]
 - 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] [Enter]
 ... 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!

 최초 설치 후에는 root 계정에 비밀번호가 없으므로 root 비밀번호를 물으면 그냥 Enter 키를 치고 진행하면 된다. 이 후 바로 root 계정 password를 설정할거냐고 묻는데 당연히 설정하는 게 좋을 것이다. 사실 root 비밀번호를 입력하는 것 말고는 모든 질문에 그냥 Enter를 치면 Y가 기본값으로 되어있기 때문에 아무 문제없이 완료된다. 그리고 모두 Y를 선택하는 게 보안상으로도 안전한 선택이다. 그래도 혹시 원하는 바가 다를 수 있으니 한 번쯤 질문을 읽어보고 적절히 답을 하면 된다.

Maria DB 기본 설정


 이제 서버의 기본 설정 상태가 어떤지 한 번 보도록 하자. 아래 명령으로 서버에 접속해서 상태를 출력해보자.

$ mysql -u root -p
Enter password: [기 설정한 root password]
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 16
Server version: 10.3.12-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)]> status
--------------
mysql  Ver 15.1 Distrib 10.3.12-MariaDB, for Linux (x86_64) using readline 5.1

Connection id:  16
Current database: 
Current user:  root@localhost
SSL:   Not in use
Current pager:  stdout
Using outfile:  ''
Using delimiter: ;
Server:   MariaDB
Server version:  10.3.12-MariaDB MariaDB Server
Protocol version: 10
Connection:  Localhost via UNIX socket
Server characterset: latin1
Db     characterset: latin1
Client characterset: utf8
Conn.  characterset: utf8
UNIX socket:  /var/lib/mysql/mysql.sock
Uptime:   25 min 58 sec

 앞에서도 얘기했지만 초기 설정 파일에는 아무 설정값도 정의되어있지 않다. 하지만 그래도 기본 설정값은 있을 것이다. Maria DB 사용자들이 흔히 설정하는 값들의 기본값은 아래와 같다.
  • datadir = /var/lib/mysql/ 
  • socket  = /var/lib/mysql/mysql.sock
  • port = 3306
  • server characterset = latin1
 datadir, socket, port 등은 사실 기본값 그대로 써도 무방하다. 하지만 요즘같은 Global 시대 latin1 characterset은 utf8로 바꿔줘야 할 것 같다. 사실 Client characterset도 latin1으로 되어있을 줄 알았는데 utf8로 되어있다는게 의외였다.

 먼저 간단하게 설정 파일의 위치와 설정값들에 대해서 얘기해 보도록 하겠다.
  • /etc/my.cnf  ==> 주 설정 파일. 파일의 내용은 /etc/my.cnf.d/ 폴더의 파일들을 include하는 것 뿐이다.
  • /etc/my.cnf.d/  ==> 이 폴더 안의 모든 .cnf 파일들이 실제 설정 파일들이며 이 파일들이 my.cnf 파일에서 include 된다.
  • /etc/my.cnf.d/server.cnf  ==> 서버를 위한 실질적인 설정 파일이다. 서버의 characterset 설정을 여기서 해주면 된다.
  • /etc/my.cnf.d/mysql-clients.cnf  ==> mysql, mysqldump 같은 client app들을 위한 설정 파일이다.
 그럼 예상한 대로 server.cnf 파일을 열어서 아래 내용을 추가해 주도록 하자.

...
[mysqld]
character-set-server = utf8
collation-server     = utf8_general_ci
...

 보면 알겠지만 mysqld 옵션 그룹에 characterset 설정만 추가해준 것이다. 이제 서버를 재시작하고 다시 mysql로 접속하여 서버의 상태를 조회해 보도록 하자.

$ sudo service mariadb restart
Redirecting to /bin/systemctl restart mariadb.service
$ mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.3.12-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)]> status
--------------
mysql  Ver 15.1 Distrib 10.3.12-MariaDB, for Linux (x86_64) using readline 5.1

Connection id:  8
Current database: 
Current user:  root@localhost
SSL:   Not in use
Current pager:  stdout
Using outfile:  ''
Using delimiter: ;
Server:   MariaDB
Server version:  10.3.12-MariaDB MariaDB Server
Protocol version: 10
Connection:  Localhost via UNIX socket
Server characterset: utf8
Db     characterset: utf8
Client characterset: utf8
Conn.  characterset: utf8
UNIX socket:  /var/lib/mysql/mysql.sock
Uptime:   24 sec

 이제 서버의 characterset 설정도 utf8로 바뀌었다. 혹시 client의 characterset를 바꾸고 싶다거나 추가적인 설정을 원하면 server.cnf, mysql-clients.cnf 파일을 열어서 적절한 option group에 값을 추가하면 된다. 자세한 설정 사항에 대해서는 구글링으로 해결하도록 하자.

 아주 기본적인 서버의 설치작업은 이제 끝났다. 하지만 실제 사용을 위해서는 추가적인 계정을 추가하고 방화벽 3306 포트를 열어주는 등의 작업이 필요할 것이다. 몇 가지 참고로 알아보도록 하자.

Maria DB 접속 포트 변경하기


 Maria DB의 포트 설정은 server.cnf 의 [mysqld] 옵션 그룹에 port 값을 지정해주면 된다.

...
[mysqld]
port = [포트번호]
...

 설정값을 추가하고 서버를 재시작해보면 아마도 서버 시작이 안될 것이다. CentOS 7에 기본 설정되어있는 SELinux 가 허용되지 않은 포트 access를 막기 때문이다.  물론 SELinux가 꺼진 상태라면 문제없이 시작된다.

 아래 명령으로 SELinux 설정을 수정해준다.

$ sudo semanage port -a -t mysqld_port_t -p tcp [포트번호]

 이제 서버를 다시 시작해보자. 아무 문제 없이 시작될 것이다. 그리고 방화벽에서도 새로 변경한 포트를 열어주는 걸 잊지 말자.

Maria DB 기본 명령어


 최초 설치 후에 간단한 몇 가지 작업을 하려면 매 번 명령어가 생각나지 않아서 인터넷을 검색하곤 한다. 그래서 여기에 몇 가지 자주 사용하는 명령어를 정리해보려고 한다. 아래 명령어들은 모두 mysql로 접속해서 실행할 수 있는 명령어이다.

  • Database 목록 보기
    > show databases;
  • Database 생성하기
    > create database [DB 이름];
  • Database 삭제하기
    > drop database [DB이름];
  • 사용할 Database 선택
    > use [DB이름];
  • 사용자 계정 조회
    > select user, host from mysql.user;
  • 사용자 계정 생성
    > create user 'userid'@'host' identified by 'password';
    • userid와 password는 원하는 값으로 설정.
    • host는 접속 클라이언트의 주소.('%'를 지정하면 anywhere)
  • 사용자 계정 권한 부여
    > grant all privileges on [DB이름].[Table이름] to 'userid'@'host';
    • all은 insert, select, delete, update 등으로 바꿀 수 있다. 여러 개 지정시 콤마로 분리하여 한 꺼번에 지정하면된다.
    • [DB이름].[Table이름]은 wildcard(*)를 사용할 수 있다. (*, *.*, db_name.*, ... )
    • 보안상의 이유로 일반 사용자 계정은 [DB이름].* 이상의 권한을 주지 않도록 한다.
  • 사용자 권한 확인
    >  show grants for 'userid'@'host';
  • 사용자 권한 삭제
    > revoke all on [DB이름].[Table이름] from 'userid'@'host';
  • 사용자 계정 삭제
    > drop user 'userid'@'host';
  • 권한 변경사항 적용
    > flush privileges;

 일단 이 정도로 설치 & 설정 작업을 마치도록 하겠다. 추후에 추가적으로 필요하다고 생각되는 사항이 생기면 글을 계속 업데이트할 예정이다. 많은 이에게 도움이 되길 바란다.

댓글 2개: