Develop/DevOps

GCP MySQL(MariaDB) DB 외부연결 | GCP MySQL (MariaDB) DB External Connection

GCP compute engine에 mysql을 연결하기 위해 삽질하면서 정리한 내용.1. compute engine에 mysql 설치sudo apt-get updatesudo apt-get install mysql-serversudo mysql_secure_installation // mysql 설정mysql_secure_installation에서 설정한 패스워드로 입력해서 접속한다.접속 방법 : root 유저로 접속하고, 패스워드를 입력하겠음sudo mysql -u root -p 2. 외부 ip 접근에 대한 포트 방화벽 열기VPC network > filewallrules 메뉴에 들어가기traffic : ingress protocols and port : 33063306 포트가 방화벽에 연결된다.소스..

GCP MySQL(MariaDB) DB 외부연결 | GCP MySQL (MariaDB) DB External Connection

728x90

GCP compute engine에 mysql을 연결하기 위해 삽질하면서 정리한 내용.

1. compute engine에 mysql 설치

sudo apt-get update
sudo apt-get install mysql-server
sudo mysql_secure_installation // mysql 설정

mysql_secure_installation에서 설정한 패스워드로 입력해서 접속한다.

접속 방법 : root 유저로 접속하고, 패스워드를 입력하겠음

sudo mysql -u root -p

 

2. 외부 ip 접근에 대한 포트 방화벽 열기

VPC network > filewallrules 메뉴에 들어가기

traffic : ingress

protocols and port : 3306

3306 포트가 방화벽에 연결된다.

소스 필터나 대상은 커스텀하게 사용하자. 난 범용적 사용을 위해 모든 인스턴스로 지정해둠

 

3. demon addresss 변경하기

ip 통해서 mysql에 접근 가능하도록 할 때 mysql 데몬이 0.0.0.0으로 떠 있어야 한다 (기본값 127.0.0.1)
이를 위해서 compute engine의 shell에서 conf 파일 수정이 필요하다.

cd /ect/mysql/mariadb.conf.d
sudo vi 50-server.cnf

해당 경로에 설정파일이 존재한다. 이곳으로 들어가서 bind-address를 변경해준다.

# bind-address = 127.0.0.1
bind-address = 0.0.0.0

이렇게 해준 후에 데몬을 재시작해주어야 한다.

service restart를 해주어도 되지만, vm에 안 깔려 있길래 다른 방법을 사용하였다.

sudo /etc/init.d/mysql restart

 

4. 접속 유저 권한 부여

위에서 sudo 권한을 이용해 db에 접속했었다. 따라서 외부 접속 전용 사용자를 추가하고, 해당 사용자에 권한을 부여 해주자

User 목록 확인

SELECT user, host FROM mysql.user;

 

사용자 계정 추가

CREATE USER 'jyami'@'%' IDENTIFIED BY 'password';
  • 사용자 명 : jyami
  • 접근 : % - 외부에서의 접근을 허용함
  • 비밀번호 : password

사용자 접근 권한

localhost local에서만의 접근을 허용함
% 모든 IP에서의 접근을 허용함
xxx.xxx.xxx.xxx 지정한 IP에서만 접근을 허용함
xxx.xxx.% 특정 IP 대역에서의 접근을 허용함

DB 권한 부여

GRANT ALL PRIVILEGES ON *.* TO 'jyami'@'%' WITH GRANT OPTION;

모든곳에서 접속하는 사용자 jyami에게 모든 권한을 부여한다.

*.* 모든 것을 할 수 잇는 권한
[database_name].* 특정 DB를 관리할 수 있는 권한
[database_name].[tablename] 특정 DB의 특정 Table을 관리할 수 잇는 권한

부여된 권한 보기

SHOW GRANTS FOR jyami@%

 

5. springboot 접속

GCE로 접근했을 때 분명 위 명령어대로 mysql을 깔았는데 직접 Mysql에 접속해보니 MariaDB [DB]> 로 떴었다. 이때 mysql connection은 안됐는데, mariaDB connection은 됐다.

[DB가 MariaDB 인 경우]

# build.gradle
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client:2.1.2'
# application.yml

spring:
  datasource:
    driver-class-name: org.mariadb.jdbc.Driver
    url: jdbc:mariadb://[GCE public IP]:3306/[DB명]?useSSL=false&serverTimezone=UTC
    username: [유저이름]
    password: [비밀번호]

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

  logging:
    level:
      org:
        hibernate:
          SQL: DEBUG
          type:
            trace

 

[DB가 MySQL 인 경우]

# build.gradle
runtimeOnly 'mysql:mysql-connector-java'
# application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://[GCE public IP]:3306/[DB명]?useSSL=false&serverTimezone=UTC
    username: [유저이름]
    password: [비밀번호]

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

  logging:
    level:
      org:
        hibernate:
          SQL: DEBUG
          type:
            trace

 

6. 추가 DB 관련 명령어

database 목록 확인

SHOW DATABASES;

사용할 database 지정

USE [database 이름];

database 생성

CREATE DATABASE [데이터베이스 이름];

 

이외 외부 접속 관련 참고 사이트

https://m.blog.naver.com/PostView.nhn?blogId=varkiry05&logNo=198610727&proxyReferer=https:%2F%2Fwww.google.com%2F

Notes from my struggles trying to connect MySQL to a GCP compute engine.

1. Installing MySQL on Compute Engine

sudo apt-get update
sudo apt-get install mysql-server
sudo mysql_secure_installation // mysql 설정

Log in using the password you set during mysql_secure_installation.

How to connect: Log in as the root user with a password

sudo mysql -u root -p

 

2. Opening Firewall Ports for External IP Access

Go to VPC network > firewall rules menu

traffic : ingress

protocols and port : 3306

Port 3306 will be opened in the firewall.

Customize the source filters and targets as you need. I set it to all instances for general-purpose use.

 

3. Changing the Daemon Address

To allow MySQL access via IP, the MySQL daemon needs to be listening on 0.0.0.0 (the default is 127.0.0.1)
To do this, you need to modify the conf file in the compute engine's shell.

cd /ect/mysql/mariadb.conf.d
sudo vi 50-server.cnf

The config file is located at this path. Go in and change the bind-address.

# bind-address = 127.0.0.1
bind-address = 0.0.0.0

After making this change, you need to restart the daemon.

You could use service restart, but since it wasn't installed on the VM, I used a different method.

sudo /etc/init.d/mysql restart

 

4. Granting User Permissions

Earlier, we connected to the DB using sudo privileges. So let's add a dedicated user for external access and grant permissions to that user.

Check User List

SELECT user, host FROM mysql.user;

 

Add a User Account

CREATE USER 'jyami'@'%' IDENTIFIED BY 'password';
  • Username: jyami
  • Access: % - allows access from external sources
  • Password: password

User Access Scope

localhost Allows access only from local
% Allows access from all IPs
xxx.xxx.xxx.xxx Allows access only from a specific IP
xxx.xxx.% Allows access from a specific IP range

Grant DB Privileges

GRANT ALL PRIVILEGES ON *.* TO 'jyami'@'%' WITH GRANT OPTION;

This grants all privileges to the user jyami connecting from anywhere.

*.* Privileges to do everything
[database_name].* Privileges to manage a specific DB
[database_name].[tablename] Privileges to manage a specific table in a specific DB

View Granted Privileges

SHOW GRANTS FOR jyami@%

 

5. Connecting from Spring Boot

When I accessed the GCE, I definitely installed MySQL following the commands above, but when I actually connected to MySQL, it showed MariaDB [DB]>. In this case, the MySQL connection didn't work, but the MariaDB connection did.

[If the DB is MariaDB]

# build.gradle
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client:2.1.2'
# application.yml

spring:
  datasource:
    driver-class-name: org.mariadb.jdbc.Driver
    url: jdbc:mariadb://[GCE public IP]:3306/[DB명]?useSSL=false&serverTimezone=UTC
    username: [유저이름]
    password: [비밀번호]

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

  logging:
    level:
      org:
        hibernate:
          SQL: DEBUG
          type:
            trace

 

[If the DB is MySQL]

# build.gradle
runtimeOnly 'mysql:mysql-connector-java'
# application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://[GCE public IP]:3306/[DB명]?useSSL=false&serverTimezone=UTC
    username: [유저이름]
    password: [비밀번호]

  jpa:
    show-sql: true
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

  logging:
    level:
      org:
        hibernate:
          SQL: DEBUG
          type:
            trace

 

6. Additional DB-Related Commands

Check Database List

SHOW DATABASES;

Select a Database to Use

USE [database 이름];

Create a Database

CREATE DATABASE [데이터베이스 이름];

 

Additional reference site for external access

https://m.blog.naver.com/PostView.nhn?blogId=varkiry05&logNo=198610727&proxyReferer=https:%2F%2Fwww.google.com%2F

댓글

Comments