back-end/DB

2. DB | DBMS | DB환경구축

림가이드 2023. 3. 30. 17:40

< DB> : 데이터의 저장소

- 데이터 저장? : 수기 -> 메모장 -> 엑셀                     ▶ 문제 : 보안? 여러사람 사용가능? 등

 

- data : 관찰 결과로 나타난 정상적 실제값

- 정보 : data의 의미

- 지식 : 사물/현상에 대한 이해

- 지혜 : 지식 기반 도출되는 창의 아이디어

 

1. 파일시스템 : 컴퓨터에서 파일이나 자료를 쉽게 발견/접근 가능하도록 보관하는 시스템.

- 즉, OS가 저장되어 있는 파일/폴더를 효율적으로 관리하는 방법

ex) FAT, NTFS, APFS 등

1) 단점

- 데이터 중복

- 데이터 종속 : app에 종속적

ex) 구조, 접근방법이 변경되면 프로그램도 같이 변경해야 함. 반대로 프로그램이 변경되면 데이터 파일도 같이 변경해야 함.

2) 장점

- 처리속도

- 구현

- 저비용

 

2. DB

- 실시간 접근성 가능

- 계속적 변화

- 동시(병행) 공유

: DB에 접근하는 프로그램이 여러개 존재

ex) 서울시에서 제공하는 버스운행 실시간 제공 -> 카카오버스 어플, 네이버맵 어플

- 내용에 따른 참조 : DB에 저장된 데이터는 데이터의 물리적 위치가 아닌 데이터값(조건값)에 따라 참조.

사용자가 원하는 data를 얻기 위해 데이터값(조건값)을 사용하여 조건을 제시하면 DB는 이에 해당하는 data를 검색하여 제공

- 데이터 독립성 : app과 db를 독립 데이터의 논리적 구조를 변경시켜도 app은 변경X => 중간매개체 : SQL

 

3. tools

ex) DataGrip, MySQL WorkBench, DBeaver 등등


< DBMS > : DB를 운영하고 관리하는 소프트웨어

: DB를 체계적으로 관리하기 위한 시스템

 

- 유형 : 계층형(조직도), 망형, 관계형, 객체지향형, 객체관계형

 

- 관계형 데이터베이스

: 가장 많이 사용하는 DB로 속성(n개)와 tuple(m개)로 이루어진 행/열 table로 구성

 

1. RDBMS : 관계형 DBMS

ex) 오라클, MySQL, MariaDB

 

- MariaDB 설치 및 설정

brew install mariadb

(my.cnf 파일? : mysql의 설정 파일. 위치찾기: find / -name my.cnf)

brew search mariadb

==> Formulae

mariadb                   mariadb@10.3               mariadb@10.8

 

설치완료시, 체크표시 됨

 

cd /usr/local/Cellar/mariadb/버전/bin
bin % sudo ./mariadb-secure-installation

Password:

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] Y
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] n
 ... skipping.

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] n
 ... skipping.

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!

 

- 실행중?!

brew services info mariadb

- 실행중단

brew services stop mariadb

- 실행시작

brew services restart mariadb

 

 

 

 

- DB 접속하기

서버에 접속하려면 기본적으로 IP, port, 계정, 인스턴스, password의 정보가 있어야 한다.

local에 접속하려면 계정, password만 가지고 있으면 된다.

 ~ % 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.11.2-MariaDB Homebrew

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)]>

- DB 버전확인

MariaDB [(none)]> select version();
+-----------------+
| version()       |
+-----------------+
| 10.11.2-MariaDB |
+-----------------+
1 row in set (0.000 sec)

- DB 보기

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.013 sec)

- 존재하는 DB 중 하나 고르기

MariaDB [(none)]> use 데이터베이스명;

- 고른 DB의 table들 보기

MariaDB [(none)]> show tables;

- 종료

quit

 

- 터미널에서 존재하는 DB 위치?

cd /usr/local/var/mysql 에 들어가면

ls -al로 존재하는 DB들 확인 가능하다.

 

 


< 원격 접속? >

 

대부분의 DB서버는 원격에서 접속한다.

이때, root는 원격으로 접속할 수 없도록 해야한다.

원격접속은 linux(OS)에 설치된 DB를 SSH를 통해 윈도우(다른 OS)에서 접속하는 것을 말한다.

 

- 방법?

: Xshell을 다운 받아 실행하면 이 프로그램 안에 터미널 창이 뜬다.

여기서 ipconfig으로 ip주소를 확인할 수 있고

"ssh setcop@접속하려는 컴퓨터(linux)의 IP주소" 의 명령을 실행하면 프로그램 내에서 linux로 변경.

 

하지만 자기컴퓨터(윈도우)의 터미널에서 외부에 접속하려면, 즉 자기컴퓨터(윈도우)의 터미널 창에서 mysql 명령을 통해 외부DB(linux)에 접속하려면!!!!!

접속하려는 컴퓨터(linux)의 터미널 창에 my.cnf의 위치를 찾아 cd한다. 그리고 관리자권한으로 vi my.cnf로 파일을 수정한다.

맨 아래에

[mysqld]
bind-address=0.0.0.0

을 추가하고

service mariadb restart 의 명령어까지 치면

외부(윈도우)에서 원격으로 접속 가능하다.

(리눅스)에서 netstat -anpt로 local address가 0.0.0.0:3306으로 변경된 것을 확인할 수 있다.

 

엥? 그런데...

외부(윈도우)에서 mysql -h 접속하려는 컴퓨터(linux)의 IP주소 -u root -p을 치면 접속할 수 없다고 뜬다.

why?

 

DB서버(linux)에서 아래의 명령어로 mysql을 실행하면,

% mysql -u root -p

use mysql;로 DB를 설정하고 

> select Host, User, Password from user;

user의 table에서 Host, User, Password를 뽑아내면, root에 접속할 수 있는 권한이 localhost(자기자신컴퓨터 - linux)밖에 설정되어 있지 않다.

그래서 서버(linux)에서 외부에서 접속할 컴퓨터(윈도우)계정을 추가해야한다.

> create user 'root'@'%' identified by '패스워드';

계정이 생성됐고, 이 계정에 권한도 부여해야 한다.

> grant all privileges on root.* to 'root'@'%' identified by '패스워드';
> flush privileges

select문으로 user의 table을 다시 확인해보면 계정이 추가된 것을 확인할 수 있다.

 

 

그래서 외부(윈도우)에서

% mysql -h 접속하려는 컴퓨터(linux)의 IP주소 -u root(=>계정명) -p

을 치면 원격접속 완료한 것이다!

 

 

▶ 정리

1. my.cnf -> bind-address=0.0.0.0 추가함

2. 접속계정(root)에서 %를 통해 외부host에서 접속가능하도록 설정함