[Linux]MariaDB 설치 및 기본 사용법
MySQL이 Oracle의 제품이 되면서, 오픈 소스 커뮤니티와 일부 사용자들은 MySQL의 개발 방향에 대한 불확실성을 표현하기 시작했습니다. 이러한 상황에서 Michael “Monty” Widenius와 그의 팀은 MySQL과 호환되는 오픈 소스 데이터베이스 소프트웨어를 개발하기로 결정했습니다. 그 결과 MariaDB는 MySQL 코드베이스를 기반으로 하며, MySQL과 호환되면서도 개발자 및 사용자 커뮤니티 중심의 프로젝트로 성장하였습니다. MariaDB는 현재 많은 리눅스 배포판과 다양한 애플리케이션에서 기본 데이터베이스로 사용되고 있습니다.
MariaDB 설치 및 보안 설정하기
- MariaDB 설치하고 서비스 시작하기
[root@centos8 ~]# dnf -y install mariadb-server----- MORE ----- Installed: mariadb-3:10.3.28-1.module_el8.3.0+757+d382997d.x86_64 mariadb-backup-3:10.3.28-1.module_el8.3.0+757+d382997d.x86_64 mariadb-common-3:10.3.28-1.module_el8.3.0+757+d382997d.x86_64 mariadb-connector-c-3.1.11-2.el8_3.x86_64 mariadb-connector-c-config-3.1.11-2.el8_3.noarch mariadb-errmsg-3:10.3.28-1.module_el8.3.0+757+d382997d.x86_64 mariadb-gssapi-server-3:10.3.28-1.module_el8.3.0+757+d382997d.x86_64 mariadb-server-3:10.3.28-1.module_el8.3.0+757+d382997d.x86_64 mariadb-server-utils-3:10.3.28-1.module_el8.3.0+757+d382997d.x86_64 perl-DBD-MySQL-4.046-3.module_el8+353+7103df35.x86_64 Complete![root@centos8 ~]# systemctl enable --now mariadb.serviceCreated symlink /etc/systemd/system/mysql.service → /usr/lib/systemd/system/mariadb.service. Created symlink /etc/systemd/system/mysqld.service → /usr/lib/systemd/system/mariadb.service. Created symlink /etc/systemd/system/multi-user.target.wants/mariadb.service → /usr/lib/systemd/system/mariadb.service.
- MariaDB 보안 설정하기
- root 사용자 비밀번호 설정
- anonymous users 삭제
- root 사용자의 원격 접속 금지
- 테스트 데이터베이스 삭제
- 권한 관리 테이블 Reload
[root@centos8 ~]# mysql_secure_installationNOTE: 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): Press "Enter key" 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] Y New password: Enter "new password" Re-enter new password: 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] 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 연결하기
[root@centos8 ~]# mysql -u root -pEnter password: Enter "password" Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 18 Server version: 10.3.28-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)]>
- 데이터베이스 목록 확인하기
MariaDB [(none)]> SHOW databases;+--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | +--------------------+ 3 rows in set (0.011 sec)
- 데이터베이스 생성 및 삭제하기
- 데이터베이스 생성 : CREATE DATABASE 데이터베이스명;
- 데이터베이스 삭제 : DROP DATABASE 데이터베이스명
MariaDB [(none)]> CREATE DATABASE testdb;MariaDB [(none)]> SHOW databases;+--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | testdb | +--------------------+ 4 rows in set (0.001 sec) - 데이터베이스 선택하기
MariaDB [(none)]> USE mysql;Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed MariaDB [mysql]>
- 테이블 목록 확인하기
MariaDB [mysql]> SHOW tables;+---------------------------+ | Tables_in_mysql | +---------------------------+ | column_stats | | columns_priv | | db | | event | | func | | general_log | | gtid_slave_pos | | help_category | | help_keyword | | help_relation | | help_topic | | host | | index_stats | | innodb_index_stats | | innodb_table_stats | | plugin | | proc | | procs_priv | | proxies_priv | | roles_mapping | | servers | | slow_log | | table_stats | | tables_priv | | time_zone | | time_zone_leap_second | | time_zone_name | | time_zone_transition | | time_zone_transition_type | | transaction_registry | | user | +---------------------------+ 31 rows in set (0.001 sec)
- 데이블 구조 확인하기
MariaDB [mysql]> DESC user;+------------------------+-----------------------------------+------+-----+----------+-------+ | Field | Type | Null | Key | Default | Extra | +------------------------+-----------------------------------+------+-----+----------+-------+ | Host | char(60) | NO | PRI | | | | User | char(80) | NO | PRI | | | | Password | char(41) | NO | | | | | Select_priv | enum('N','Y') | NO | | N | | | Insert_priv | enum('N','Y') | NO | | N | | | Update_priv | enum('N','Y') | NO | | N | | | Delete_priv | enum('N','Y') | NO | | N | | | Create_priv | enum('N','Y') | NO | | N | | | Drop_priv | enum('N','Y') | NO | | N | | | Reload_priv | enum('N','Y') | NO | | N | | | Shutdown_priv | enum('N','Y') | NO | | N | | | Process_priv | enum('N','Y') | NO | | N | | | File_priv | enum('N','Y') | NO | | N | | | Grant_priv | enum('N','Y') | NO | | N | | | References_priv | enum('N','Y') | NO | | N | | | Index_priv | enum('N','Y') | NO | | N | | | Alter_priv | enum('N','Y') | NO | | N | | | Show_db_priv | enum('N','Y') | NO | | N | | | Super_priv | enum('N','Y') | NO | | N | | | Create_tmp_table_priv | enum('N','Y') | NO | | N | | | Lock_tables_priv | enum('N','Y') | NO | | N | | | Execute_priv | enum('N','Y') | NO | | N | | | Repl_slave_priv | enum('N','Y') | NO | | N | | | Repl_client_priv | enum('N','Y') | NO | | N | | | Create_view_priv | enum('N','Y') | NO | | N | | | Show_view_priv | enum('N','Y') | NO | | N | | | Create_routine_priv | enum('N','Y') | NO | | N | | | Alter_routine_priv | enum('N','Y') | NO | | N | | | Create_user_priv | enum('N','Y') | NO | | N | | | Event_priv | enum('N','Y') | NO | | N | | | Trigger_priv | enum('N','Y') | NO | | N | | | Create_tablespace_priv | enum('N','Y') | NO | | N | | | Delete_history_priv | enum('N','Y') | NO | | N | | | ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | | | ssl_cipher | blob | NO | | NULL | | | x509_issuer | blob | NO | | NULL | | | x509_subject | blob | NO | | NULL | | | max_questions | int(11) unsigned | NO | | 0 | | | max_updates | int(11) unsigned | NO | | 0 | | | max_connections | int(11) unsigned | NO | | 0 | | | max_user_connections | int(11) | NO | | 0 | | | plugin | char(64) | NO | | | | | authentication_string | text | NO | | NULL | | | password_expired | enum('N','Y') | NO | | N | | | is_role | enum('N','Y') | NO | | N | | | default_role | char(80) | NO | | | | | max_statement_time | decimal(12,6) | NO | | 0.000000 | | +------------------------+-----------------------------------+------+-----+----------+-------+ 47 rows in set (0.002 sec)
- 테이블 레코드 조회하기
MariaDB [mysql]> SELECT host, user, password FROM user;+-----------+------+-------------------------------------------+ | host | user | password | +-----------+------+-------------------------------------------+ | localhost | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | | 127.0.0.1 | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | | ::1 | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | +-----------+------+-------------------------------------------+ 3 rows in set (0.000 sec)
- 사용자 생성 및 삭제하기
- 로컬에서만 접근: CREATE USER ‘사용자’@localhost IDENTIFIED BY ‘비밀번호’
- 권한을 부여할 수 있는 권한 부여 : 사용자 생성할 때 [WITH GRANT OPTION] 을 끝에 추가
- 외부에서도 접근: CREATE USER ‘사용자’@’%’ IDENTIFIED BY ‘비밀번호’
- 사용자 삭제: drop user ‘사용자’@’호스트명’
MariaDB [mysql]> CREATE USER 'jeno'@localhost IDENTIFIED BY '1234';Query OK, 0 rows affected (0.001 sec)MariaDB [mysql]> CREATE USER 'archer'@'%' IDENTIFIED BY '1234';Query OK, 0 rows affected (0.000 sec)MariaDB [mysql]> SELECT host, user, password FROM user;+-----------+--------+-------------------------------------------+ | host | user | password | +-----------+--------+-------------------------------------------+ | localhost | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | | 127.0.0.1 | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | | ::1 | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | | localhost | jeno | *A4B6157319038724E3560894F7F932C8886EBFCF | | % | archer | *A4B6157319038724E3560894F7F932C8886EBFCF | +-----------+--------+-------------------------------------------+ 5 rows in set (0.000 sec) - 테이블 생성, 삭제 및 변경하기
- 테이블 생성 : CREATE TABLE 테이블명 ( 컬럼 );
- 테이블 삭제 : DROP TABLE 테이블명;
MariaDB [mysql]> USE testdb;Database changedMariaDB [testdb]>CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), job_title VARCHAR(100), department VARCHAR(50), salary INT(12), hire_date DATE );Query OK, 0 rows affected (0.035 sec)MariaDB [testdb]> DESC employees;+-------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+-------+ | employee_id | int(11) | NO | PRI | NULL | | | first_name | varchar(50) | YES | | NULL | | | last_name | varchar(50) | YES | | NULL | | | job_title | varchar(100) | YES | | NULL | | | department | varchar(50) | YES | | NULL | | | salary | int(12) | YES | | NULL | | | hire_date | date | YES | | NULL | | +-------------+--------------+------+-----+---------+-------+ 7 rows in set (0.001 sec)
- 테이블 변경 : ALTER TABLE 테이블명 변경 사항 지정
-- employees 테이블에 새로운 컬럼인 'phone' 추가 ALTER TABLE employees ADD COLUMN phone VARCHAR(15); -- employees 테이블에서 'phone' 컬럼 삭제 ALTER TABLE employees DROP COLUMN phone; -- employees 테이블에서 'salary' 컬럼의 데이터 타입을 변경 ALTER TABLE employees MODIFY COLUMN salary DECIMAL(10, 2);
- 컬럼 타입의 종류
VARCHAR(size): 가변 길이 문자열, 최대 길이를 지정합니다. CHAR(size): 고정 길이 문자열, 지정된 크기만큼 항상 차지합니다. INT: 정수 타입, 예를 들어 INT 또는 INTEGER로 사용 가능합니다. FLOAT: 부동 소수점 숫자. DOUBLE: 더 큰 부동 소수점 숫자. DECIMAL(size, d): 고정 소수점 숫자, 전체 자릿수와 소수점 이하 자릿수를 지정합니다. DATE: 날짜 값만을 저장하는 타입. TIME: 시간 값만을 저장하는 타입. DATETIME: 날짜와 시간을 함께 저장하는 타입. TIMESTAMP: 날짜와 시간을 저장하며, 시간대 변환이 자동으로 이루어집니다. BOOLEAN 또는 BOOL: 논리값을 저장하는 타입. BLOB(Binary Large Object): 이미지 파일, 첨부문서 등 Binary파일을 저장
- 권한 부여 및 삭제, 확인하기
- 모든 권한 부여 : GRANT all privileges ON 데이터베이스명.* TO 사용자@호스트명
- 사용자 권한 부여 : GRANT 권한 ON 데이터베이스명.테이블명 TO 사용자@호스트명;
- 사용자 권한 삭제 : REVOKE 권한 ON 데이터베이스명.테이블명 FROM 사용자@호스트명;
- 변경된 권한을 반영하기 : FLUSH PRIVILEGES;
- 사용자 권한 조회 : SHOW grants; SHOW grants FOR 사용자@호스트명;
MariaDB [testdb]> GRANT select, insert, update ON employees TO archer@'%';Query OK, 0 rows affected (0.000 sec)MariaDB [testdb]> SHOW grants FOR archer@'%';+-------------------------------------------------------------------------------------------------------+ | Grants for archer@% | +-------------------------------------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO `archer`@`%` IDENTIFIED BY PASSWORD '*A4B6157319038724E3560894F7F932C8886EBFCF' | | GRANT SELECT, INSERT, UPDATE ON `testdb`.`employees` TO `archer`@`%` | +-------------------------------------------------------------------------------------------------------+ 2 rows in set (0.000 sec)MariaDB [testdb]> REVOKE update ON employees FROM archer@'%';Query OK, 0 rows affected (0.000 sec)MariaDB [testdb]> SHOW grants FOR archer@'%';+-------------------------------------------------------------------------------------------------------+ | Grants for archer@% | +-------------------------------------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO `archer`@`%` IDENTIFIED BY PASSWORD '*A4B6157319038724E3560894F7F932C8886EBFCF' | | GRANT SELECT, INSERT ON `testdb`.`employees` TO `archer`@`%` | +-------------------------------------------------------------------------------------------------------+ 2 rows in set (0.000 sec)MariaDB [testdb]> FLUSH PRIVILEGES;Query OK, 0 rows affected (0.000 sec) - 권한의 종류
SELECT: 테이블의 데이터를 조회하는 권한. INSERT: 새로운 데이터를 테이블에 추가하는 권한. UPDATE: 테이블의 기존 데이터를 수정하는 권한. DELETE: 테이블에서 데이터를 삭제하는 권한. CREATE: 새로운 데이터베이스나 테이블을 생성하는 권한. DROP: 데이터베이스나 테이블을 삭제하는 권한. ALTER: 테이블 구조를 변경하는 권한. GRANT OPTION: 다른 사용자에게 권한을 부여하는 권한을 가짐.
- MySQL 백업하기
–mysqldump
명령어를 사용해서 서비스를 중단하지 않고 SQL문 형태로 백업
– 복구하려면 리다이렉트의 방향을 “<”로 변경[root@centos8 ~]# mysqldump --all-databases -u root -p > all_databases.sqlEnter password: Enter "password of root user" - 추가적인 보안 강화 설정
- 디폴트 mysql 관리자 계정인 root의 이름 변경: Brute Force/Dictionary 공격 대응
mysql> update user set user='mariaadm' where user='root'; mysql> flush privileges;
- mysql 계정의 로그인 차단
[root@centos8 ~]# usermod -s /sbin/nologin mysql
- 로컬에 설치된 애플리케이션에 의해서만 접근하도록 원격에서 mysql 데이터베이스 접속 차단(3306/tcp 포트 차단)
[root@centos8 ~]# vi /etc/my.cnf.d/server.cnf[mysqld] .... skip-networking[root@centos8 ~]# systemctl restart mariadb.service
- 디폴트 mysql 관리자 계정인 root의 이름 변경: Brute Force/Dictionary 공격 대응