본문 바로가기
Data/ELK

[2022.04.27] How to install MySQL on ubuntu20.04? (+ Mount & mysql external connect)

by injekim97 2022. 4. 27.
반응형

[2022.04.27]  How to install MySQL on ubuntu20.04? (+ Mount & mysql external connect)

 

 

MySQL 설치      (PASS)

wget dev.mysql.com/get/mysql-apt-config_0.8.20-1_all.deb
sudo dpkg -i mysql-apt-config_0.8.20-1_all.deb 
sudo apt-get update
sudo apt-get install mysql-server




sudo apt-get update 실행 시 발생하는 에러 1

Err:1 http://repo.mysql.com/apt/ubuntu focal InRelease                                              
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 467B942D3A79BD29

 

[Solved]

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 467B942D3A79BD29

 



sudo apt-get update 실행 시 발생하는 에러 2

vmadmin@vmadmin-virtual-machine:~/Desktop$ sudo apt-get update
Err:1 http://kr.archive.ubuntu.com/ubuntu focal InRelease                                                  
  Temporary failure resolving 'kr.archive.ubuntu.com'
Err:2 http://repo.mysql.com/apt/ubuntu focal InRelease                                                     
  Temporary failure resolving 'repo.mysql.com'
Err:3 http://security.ubuntu.com/ubuntu focal-security InRelease                                           
  Temporary failure resolving 'security.ubuntu.com'
Hit:4 http://kr.archive.ubuntu.com/ubuntu focal-updates InRelease                               
Hit:5 http://kr.archive.ubuntu.com/ubuntu focal-backports InRelease
Reading package lists... Done
W: Failed to fetch http://kr.archive.ubuntu.com/ubuntu/dists/focal/InRelease  Temporary failure resolving 'kr.archive.ubuntu.com'
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/focal-security/InRelease  Temporary failure resolving 'security.ubuntu.com'
W: Failed to fetch http://repo.mysql.com/apt/ubuntu/dists/focal/InRelease  Temporary failure resolving 'repo.mysql.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.


[Solved]

sudo apt-get update

 

 




How to Allow Remote Connections to MySQL? 

sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
bind-address            = 0.0.0.0

=> save  &  sudo systemctl restart mysql    


MySQL connection

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


Check the status of MySQL

systemctl status mysql



MySQL start & stop

sudo systemctl start mysql 
sudo systemctl stop mysql


 


WorkBench    (PASS)
* root 계정으로는 외부 접속 X
* mysql.confd 에서 bind-address 추가


# 계정 생성 및 권한 부여 

mysql>  CREATE USER 'admin'@'%'identified by 'admin'; 
Query OK, 0 rows affected (0.01 sec)

mysql> grant all privileges on *.* to 'admin'@'%'; 
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)




# 계정 권한 확인 

mysql> 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
mysql> select host,user from user;
+-----------+------------------+
| host      | user             |
+-----------+------------------+
| %         | admin            |
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
5 rows in set (0.00 sec)

 

 

 


jdbc plugin install (PASS)

wget https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java_8.0.29-1ubuntu20.04_all.deb
sudo dpkg -i mysql-connector-java_8.0.29-1ubuntu20.04_all.deb

path 
    - usr/share/java/mysql-connector-java-8.0.29.jar
 

 


Liunx 에서 Mount   (PASS)
* 내부망 IP 폴더로 접근 하여 파일을 가져오거나 내보내기 가능

sudo mkdir /tmp/qanas
sudo su -
mount -t cifs -o username=injekim97,password='*********' //외부망ip주소 /Mount할Path




많은 데이터 한방에 넣기 
2-1. 아래와 같은 에러가 발생할 시, MySQL에서 LOAD DATA 상태를 확인해줘야 한다.

ERROR 3948 (42000): Loading local data is disabled; this must be enabled on both the client and server sides
ERROR 3948 (42000): Loading local data is disabled; this must be enabled on both the client and server sides




loading local 상태 확인 (기존에는 OFF로 되어있을 것이다)

show global variables like 'local_infile';

mysql>  show global variables like 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | OFF   |
+---------------+-------+
1 row in set (0.00 sec)


loading local OFF -> ON으로 변경방법 

set global local_infile=true;
exit

 

 


 
MySql 접속할 때,(csv 파일을 mysql에 업로드)

mysql --local-infile=1 -u root -p

위와 같은 방법으로 접속 안할시 아래와 같은 에러 발생

ERROR 2068 (HY000): LOAD DATA LOCAL INFILE file request rejected due to restrictions on access.
ERROR 2068 (HY000): LOAD DATA LOCAL INFILE file request rejected due to restrictions on access.


  

자 이제 처음부터 끝까지 대용량 데이터를 넣기 위해 진행과정을 정리하였다. 

ubuntu@ip-172-31-9-174:~$ mysql --local-infile=1 -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 70
Server version: 8.0.25 MySQL Community Server - GPL

 

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| DATA               |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

 

mysql> use DATA;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

 

여기서 중요
window workbench를 이용하여, CSV를 이용하여, 조금만 데이터를 넣어준다 (그럼 자동으로 컬럼을 알아서 만들어 줌)
-> 그런 다음에 workbench를 일부로 종료하여,
-> 밑에 테이블 과 속성을 남겨두고 모든 데이터를 지우기 위해 TRUNCATE 사용하여 삭제
----> 이 방법을 통해 손으로 작업할 필요 없이 많은 칼럼과 테이블을 만들어 줄 필요가 없다.  위의 방법을 사용하면 자동으로 만들어 주니까. workbench를 응용한 것이다.
 

아래의 명령어는 테이블과 컬럼(속성)을 지우지 않고, 안에 모든 데이터를 지우는 명령어

mysql> truncate table eyesight;
Query OK, 0 rows affected (0.04 sec)

 

 

해당 명령어는 대용량의 CSV파일을 넣어주는 방법이다. (단 CSV 칼럼 속성 구조와 DB구조가 같을 때만 사용이 가능하므로, workbench를 통해 CSV 구조와 DB구조를 꼭 맞춰준다)

mysql> LOAD DATA LOCAL INFILE "/home/ubuntu/data/국가건강검진_시력데이터.csv"
    -> INTO TABLE DATA.eyesight FIELDS TERMINATED BY ",";

-> 위의 방법을 통해 6초 만에 100001 데이터를 MySQL에 업로드하였다.

 

 

 


---------------------------------------------------------------------------------------------------------------------------
즉, 위의 과정을 다하고, 할 때마다 하려면 이것을 보면 됨

ubuntu@ip-172-31-9-174:~$ mysql --local-infile=1 -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 98
Server version: 8.0.25 MySQL Community Server - GPL

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

 

mysql> LOAD DATA LOCAL INFILE "/home/ubuntu/data/국가건강검진_혈압혈당데이터.csv" INTO TABLE DATA.blood_pressure_sugar FIELDS TERMINATED BY "," IGNORE 1 LINES;
Query OK, 1000000 rows affected, 65535 warnings (6.25 sec)
Records: 1000000  Deleted: 0  Skipped: 0  Warnings: 1000000

mysql> LOAD DATA LOCAL INFILE "/home/ubuntu/data/국가건강검진_시력데이터.csv" INTO TABLE DATA.eyesight FIELDS TERMINATED BY ","  IGNORE 1 LINES;
Query OK, 1000000 rows affected (5.40 sec)
Records: 1000000  Deleted: 0  Skipped: 0  Warnings: 0

 

 

CSV file > logstash.conf  

input {
    file {
        path => "C:/python_file/*.csv" 
        start_position => "beginning"
    }
}

output {
    stdout { codec => rubydebug }

    # elasticsearch 연동
    elasticsearch {
        hosts => "52.188.20.167:9200"
        index => "instgram_csv" # ★★★★★ 아까 앞에서 geoip를 만들었던 index이름 그대로 사용. ★★★★★
    }         
}

 

logstash 실행 방법 

./logstash -f 000.conf --path.settings /etc/logstash/



logstash 실행 시 에러 1

Reason: Path "/var/lib/logstash" must be a writable directory. It is not writable.
Reason: Path "/usr/share/logstash/data" must be a writable directory. It is not writable.

[solved]

sudo chown -R vmadmin:vmadmin /var/lib/logstash
sudo chown -R vmadmin:vmadmin /usr/share/logstash/data



logstash 실행 시 에러 2

[2022-04-27T13:30:32,629][INFO ][logstash.config.source.local.configpathloader] No config files found in path {:path=>"/usr/share/logstash/test.conf"}
[2022-04-27T13:30:32,639][ERROR][logstash.config.sourceloader] No configuration found in the configured sources.

[solved]

sudo chown -R vmadmin:vmadmin /usr/share/logstash/data

 



백그라운드로 실행하는 방법
1. Linux 서버 시간 설정 

sudo timedatectl set-timezone Asia/Seoul

-> 해당 명령어를 사용하면, 리눅스 서버 시간을 UTC -> KST(한국 시간)으로 변경할 수 있다. 



2. elastcsearch 백그라운드(데몬) 실행

# /usr/share/elasticsearch 이동 후 명령어 입력 bin/elasticsearch -d
ubuntu@ip-172-31-9-174:/usr/share/elasticsearch$ bin/elasticsearch -d


3. kibana 백그라운드(데몬) 실행

sudo chown -R ubuntu:ubuntu /home/ubuntu/

ubuntu@ip-172-31-9-174:~$ nohup /usr/share/kibana/bin/kibana &
[1] 62242

-> 권한을 꼭 부여해줘야 실행이 가능함.



 

DB > logstash.conf 

input {
    jdbc {
        jdbc_driver_library => "/usr/share/java/mysql-connector-java-8.0.25.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        #jdbc_connection_string => "jdbc:mysql://localhost:3306/DATA?allowPublicKeyRetrieval=true&useSSL=false&user=root&password=root"
        jdbc_connection_string => "jdbc:mysql://localhost:3306/DATA?useSSL=false&user=root&password=root"
        jdbc_user => "root"
        jdbc_password => "root"
        schedule => "* * * * *"
        statement => "select * from waist"
        type => "waist"
        tracking_column => "table_1"
        use_column_value => true
        }
}

output {
    if[type] == "waist"  {
        elasticsearch {
            hosts => "localhost:9200"
            index => "final_waist"
            user => "elastic"
            password => "d2L79ArdVSJqbxqATuKj"
            document_id => "%{index}"           #★★★★★★★★ 이것은 중복데이터값 제거하는것, index는 해당 db테이블에 uniqe한 컬럼을 넣어줘야 함 ★★★★★★

            }
    }
    stdout {
        #codec => dots {}
        codec => rubydebug
    }
}


 

반응형

댓글