Ubuntu에 MySQL 설치 및 구성

현승빈·2023년 8월 1일

개요

사용하고 있는 OS 는 Ubuntu 20.04 버전입니다.

Ubuntu OS에 MySQL 을 설치 및 구성해보도록하겠습니다.

MySQL 설치

먼저 apt 를 업데이트 합니다.
sudo apt update
sudo apt upgrade

MySQL server를 설치합니다.
sudo apt install mysql-server

~$ sudo apt install mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libcgi-fast-perl libcgi-pm-perl libencode-locale-perl libevent-core-2.1-7 libevent-pthreads-2.1-7 libfcgi-perl libhtml-parser-perl libhtml-tagset-perl libhtml-template-perl
  libhttp-date-perl libhttp-message-perl libio-html-perl liblwp-mediatypes-perl libmecab2 libtimedate-perl liburi-perl mecab-ipadic mecab-ipadic-utf8 mecab-utils mysql-client-8.0
  mysql-client-core-8.0 mysql-common mysql-server-8.0 mysql-server-core-8.0
Suggested packages:
  libdata-dump-perl libipc-sharedcache-perl libwww-perl mailx tinyca
The following NEW packages will be installed:
  libcgi-fast-perl libcgi-pm-perl libencode-locale-perl libevent-core-2.1-7 libevent-pthreads-2.1-7 libfcgi-perl libhtml-parser-perl libhtml-tagset-perl libhtml-template-perl
  libhttp-date-perl libhttp-message-perl libio-html-perl liblwp-mediatypes-perl libmecab2 libtimedate-perl liburi-perl mecab-ipadic mecab-ipadic-utf8 mecab-utils mysql-client-8.0
  mysql-client-core-8.0 mysql-common mysql-server mysql-server-8.0 mysql-server-core-8.0
0 upgraded, 25 newly installed, 0 to remove and 0 not upgraded.
Need to get 36.8 MB of archives.
After this operation, 319 MB of additional disk space will be used.
Do you want to continue? [Y/n]

MySQL 보안 스크립트 실행

설치가 완료되면 MySQL에서 제공하는 보안 스크립트를 실행하여 설치를 보다 안전하게 해야 합니다.

sudo mysql_secure_installation

$ sudo mysql_secure_installation

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

Press y|Y for Yes, any other key for No: Y

관리자 비밀번호 구성요소 확인


LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:

기본구성 사용자 삭제확인

Skipping password set for root as authentication with auth_socket is used by default.
If you would like to use password authentication instead, this can be done with the "ALTER_USER" command.
See https://dev.mysql.com/doc/refman/8.0/en/alter-user.html#alter-user-password-management for more information.

By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL 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? (Press y|Y for Yes, any other key for No) : 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? (Press y|Y for Yes, any other key for No) : Y
Success.

테스트 데이터베이스 삭제 확인

By default, MySQL 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? (Press y|Y for Yes, any other key for No) : 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? (Press y|Y for Yes, any other key for No) : Y
Success.

All done

MySQL 방화벽 허용

외부에서 해당 서버에 MySQL 서비스를 접근할 수 있도록 방화벽을 허용합니다.
sudo ufw allow mysql


MySQL 서비스 시작

sudo systemctl start mysql
sudo systemctl enable mysql

MySQL 접속

sudo /usr/bin/mysql -u root -p

## 현재 MySQL root 유저에 비밀번호를 지정하지 않았기때문에 엔터로 접속합니다.
$ sudo /usr/bin/mysql -u root -p

Enter password:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.33-0ubuntu0.20.04.4 (Ubuntu)

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

데이터베이스 및 테이블 생성

데이터베이스 생성
CREATE DATABASE ; 을 통하여 데이터베이스를 생성할 수 있습니다.
CREATE DATABASE <databasename>;

SHOW DATABASES을 통하여 생성 및 기본 데이터베이스를 조회 할 수있습니다.
SHOW DATABASES;

USE mydatabase; 를 사용하여 생성한 테이블을 사용하도록 명령할 수 있습니다.
USE mydatabase;

SELECT DATABASE(); 를 사용하여 지금 현재 사용중인 데이터베이스를 조회 할 수 있습니다.
SELECT DATABASE();

mysql> CREATE DATABASE hyuntestdb;
Query OK, 1 row affected (0.01 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| hyuntestdb         |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
  
mysql> USE hyuntestdb;
Database changed

## 현재 사용중인 데이터베이스 조회 SELECT DATABASE()에 ()를 넣어주셔야합니다.
## 아니면 밑에 예제처럼 오류가 발생합니다.
mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| hyuntestdb |
+------------+
1 row in set (0.00 sec)

mysql> SELECT DATABASE;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

테이블 생성
CREATE TABLE table_name()을 통하여 현재 사용중인 데이터베이스에 테이블을 생성할 수 있습니다.

  CREATE TABLE table_name (
    column1 datatype1 constraints,
    column2 datatype2 constraints,
    ...
); 
## 이 예에서 "id" 열은 기본 키 역할을 하는 자동 증가 값이 있는 정수로 정의됩니다
## "name" 열은 최대 길이가 255자인 가변 길이 문자열입니다.
mysql> CREATE TABLE users (
  ->     id INT AUTO_INCREMENT PRIMARY KEY,
  ->     name VARCHAR(255)
  -> );
Query OK, 0 rows affected (0.08 sec)

테이블 조회
DESCRIBE tablename;을 통하여 현재 데이터베이스에 테이블을 조회 할 수 있습니다.

  mysql> DESCRIBE users;

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int          | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

테이블 데이터 입력
INSERT 문을 통하여 생성된 테이블에 데이터를 입력할 수 있습니다.
INSERT INTO users (id, name) VALUES (1, 'user_name');

mysql> INSERT INTO users (id, name) VALUES (1, 'hyun');
Query OK, 1 row affected (0.01 sec)

id를 자동으로 증가하도록 설정한 테이블이니 'id'입력을 안해도 자동으로 부여됩니다.
또한 INSERT INTO users (name) VALUES('Hyun'),('Been'); 처럼 여러개의 데이터를 한꺼번에 입력할 수 있습니다.

mysql> INSERT INTO users (name) VALUES('Hyun'),('Been');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM users;
+----+------+
| id | name |
+----+------+
|  1 | hyun |
|  2 | been |
|  3 | Hyun |
|  4 | Been |
+----+------+
4 rows in set (0.00 sec)

사용자 생성 및 확인

사용자 정보 확인
MySQL 서버 내부에서 Select User 쿼리를 문을 통해 사용자 정보를 불러옵니다.
쿼리를 마무리 할때는 (;) 따옴표로 마무리해주셔야 쿼리가 입력됩니다.

SELECT User, Host, authentication_string FROM mysql.user;

mysql> SELECT User, Host, authentication_string FROM mysql.user;
+------------------+-----------+------------------------------------------------------------------------+
| User             | Host      | authentication_string                                                  |
+------------------+-----------+------------------------------------------------------------------------+
| debian-sys-maint | localhost | $A$005$?QM"N&2

                                                  Q1(dQAGZQcWuhe4sHF3IYzWjJiLs8Mbyi6BRNbII.tAsJ1Cr/ |
| mysql.infoschema | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.session    | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.sys        | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| root             | localhost |                                                                        |
+------------------+-----------+------------------------------------------------------------------------+
5 rows in set (0.00 sec)

mysql>

사용자 생성
'new_user' 에 사용할 사용자명을 입력하고 'password'에 비밀번호를 입력합니다.
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'password';

mysql> CREATE USER 'hyun'@'localhost' IDENTIFIED BY 'testhyun123';
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT User, Host, authentication_string FROM mysql.user;
+------------------+-----------+------------------------------------------------------------------------+
| User             | Host      | authentication_string                                                  |
+------------------+-----------+------------------------------------------------------------------------+
| debian-sys-maint | localhost | $A$005$?QM"N&2

                                                  Q1(dQAGZQcWuhe4sHF3IYzWjJiLs8Mbyi6BRNbII.tAsJ1Cr/ |
| hyun             | localhost | $A$005$-0Xs~eOB~!\R^{RjIzpwxR.jrFl7Ck5f9NMo8b6rGvfB/zsNkzuezTr37NA |
| mysql.infoschema | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.session    | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.sys        | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| root             | localhost |                                                                        |
+------------------+-----------+------------------------------------------------------------------------+
6 rows in set (0.00 sec)

사용자 권한 부여

GRANT 로 사용자들에 권한을 부여할 수 있습니다.
GRANT ALL을 모든(*), 특정 데이터베이스(database_name)에 모든 측면을 관리할수 있는 권한입니다.

GRANT ALL PRIVILEGES ON database_name.* TO 'new_user'@'localhost';

GRANT SELECT, INSERT, UPDATE ON 을 통하여 Select, Insert, Update 세가지 측면을 나눠서 부여할 수 있습니다.
GRANT SELECT, INSERT, UPDATE ON database_name.table_name TO 'new_user'@'localhost';

SHOW GRANTS FOR 'username'@'hostname'; 을 통하여 또한 권한부여된 사용자를 확인할 수 있습니다.

mysql> GRANT ALL PRIVILEGES ON hyuntestdb.* TO 'hyun'@'localhost';
Query OK, 0 rows affected (0.02 sec)
  
mysql> SHOW GRANTS FOR 'hyun'@'localhost';
+--------------------------------------------------------------+
| Grants for hyun@localhost                                    |
+--------------------------------------------------------------+
| GRANT USAGE ON *.* TO `hyun`@`localhost`                     |
| GRANT ALL PRIVILEGES ON `hyuntestdb`.* TO `hyun`@`localhost` |
+--------------------------------------------------------------+
2 rows in set (0.00 sec)

변경사항 적용
MySQL에서 FLUSH는 데이터베이스의 상태를 초기화하거나 변경하는 명령입니다.

FLUSH PRIVILEGES 을 통하여 권한을 부여한 후 변경 사항이 즉시 적용되도록 권한을 플러시하는 것이 중요합니다.

FLUSH PRIVILEGES;

  mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)
profile
클라우드 엔지니어

0개의 댓글