database Mysql Setting

Mac Mini에서 MySQL 설치와 외부 접속 설정하기: 물뮤(MoolMeow) 프로젝트 구축 가이드 🐬

안녕하세요! 이번 글에서는 물뮤(MoolMeow) 프로젝트를 위해 Mac Mini에 MySQL을 설치하고 쿠버네티스 클러스터에서 접속할 수 있도록 설정하는 방법을 단계별로 알아보겠습니다. 여러 문제 해결 방법도 함께 공유합니다! 🛠️

⚠️ 주의: 이 글에 사용된 데이터베이스 이름, 사용자 이름 및 비밀번호는 모두 예시입니다. 실제 환경에서는 보안을 위해 다른 값을 사용해야 합니다.

1. Homebrew로 MySQL 설치하기 🍺

Mac에서는 Homebrew를 사용하여 MySQL을 쉽게 설치할 수 있습니다.

Homebrew 설치

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# zsh를 사용하는 경우 (기본 macOS 쉘)
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc

MySQL 설치 및 실행

# MySQL 설치
brew install mysql

# MySQL 서비스 시작
brew services start mysql

# 초기 보안 설정
mysql_secure_installation

초기 보안 설정에서는 다음과 같은 질문에 답하게 됩니다:

  • 비밀번호 복잡성 검사 활성화 여부
  • root 비밀번호 설정
  • 익명 사용자 제거 여부
  • root의 원격 로그인 허용 여부
  • 테스트 데이터베이스 제거 여부
  • 권한 테이블 다시 로드 여부

2. 외부 접속을 위한 MySQL 설정 🌐

MySQL 설정 파일 찾기

Mac에서 Homebrew로 설치한 MySQL의 설정 파일은 다음 위치에 있습니다:

# MySQL이 현재 사용 중인 설정 파일 확인
mysql --help | grep "Default options" -A 1

일반적으로 /opt/homebrew/etc/my.cnf 위치에 있습니다.

설정 파일 수정

외부 접속을 허용하기 위해 설정 파일을 수정합니다:

sudo nano /opt/homebrew/etc/my.cnf

다음과 같이 설정 내용을 변경합니다:

# Default Homebrew MySQL server config
[mysqld]
# Allow connections from anywhere
bind-address = 0.0.0.0
mysqlx-bind-address = 0.0.0.0

[client]
socket=/tmp/mysql.sock

bind-address = 0.0.0.0으로 설정하면 모든 네트워크 인터페이스에서 MySQL 접속을 허용합니다. 또한 [client] 섹션에 socket=/tmp/mysql.sock을 추가하여 소켓 연결 문제를 해결합니다.

MySQL 재시작

설정 변경 후 MySQL을 재시작합니다:

brew services restart mysql

3. “Can’t connect to local MySQL server through socket” 오류 해결하기 🔧

MySQL에 접속할 때 다음과 같은 오류가 발생할 수 있습니다:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

이 오류는 다음과 같은 방법으로 해결할 수 있습니다:

방법 1: 소켓 위치 지정하기

mysql -u root -p --socket=/tmp/mysql.sock

방법 2: my.cnf 파일에 소켓 위치 설정하기

my.cnf 파일의 [client] 섹션에 소켓 위치를 지정합니다:

[client]
socket=/tmp/mysql.sock

이렇게 설정하면 mysql -u root -p 명령어만으로도 접속할 수 있습니다.

방법 3: MySQL 로그 확인하기

MySQL 로그를 확인하여 실제 소켓 파일 위치를 확인할 수 있습니다:

# MySQL 프로세스 ID 찾기
ps aux | grep mysqld

# 로그 파일 확인
tail -100 /opt/homebrew/var/mysql/*.err

로그에서 socket: '/tmp/mysql.sock'와 같은 부분을 찾아 실제 소켓 위치를 확인합니다.

4. 데이터베이스 및 사용자 생성 🗄️

MySQL에 접속한 후 물뮤 프로젝트를 위한 데이터베이스와 사용자를 생성합니다:

-- 데이터베이스 생성 (실제 이름은 다르게 사용하세요)
CREATE DATABASE your_database_name;

-- 로컬 접속용 사용자 (실제 이름과 비밀번호는 다르게 사용하세요)
CREATE USER 'your_username'@'localhost' IDENTIFIED BY 'use_strong_password_here';
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'localhost';

-- 쿠버네티스 노드에서 접속용 사용자
CREATE USER 'your_username'@'192.168.100.%' IDENTIFIED BY 'use_strong_password_here';
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'192.168.100.%';

-- 변경사항 적용
FLUSH PRIVILEGES;

여기서 192.168.100.%는 쿠버네티스 클러스터의 IP 범위입니다. 이 설정으로 쿠버네티스 노드에서만 접속을 허용합니다.

5. 통합 데이터베이스 구조 설계 📊

물뮤 프로젝트에서는 물(Mool)과 뮤(Meow) 모두에 적용되는 게시물과 마켓플레이스를 관리하기 위한 통합 데이터베이스 구조를 사용하는 것이 효율적입니다.

-- 포스트(게시물) 테이블 (테이블 이름은 실제 환경에 맞게 변경하세요)
CREATE TABLE posts (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    section ENUM('section1', 'section2') NOT NULL,  -- 구분 필드 (실제 값은 다르게 사용)
    title VARCHAR(255) NOT NULL,
    content TEXT,
    author_id BIGINT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_section (section),
    INDEX idx_author (author_id)
);

-- 마켓플레이스 상품 테이블 (테이블 이름은 실제 환경에 맞게 변경하세요)
CREATE TABLE marketplace_items (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    section ENUM('section1', 'section2') NOT NULL,  -- 구분 필드 (실제 값은 다르게 사용)
    title VARCHAR(255) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL,
    seller_id BIGINT NOT NULL,
    status ENUM('available', 'sold', 'reserved') DEFAULT 'available',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_section (section),
    INDEX idx_seller (seller_id),
    INDEX idx_status (status)
);

이 구조에서는 section 필드를 사용하여 물(mool)과 뮤(meow) 항목을 구분합니다.

6. 외부에서 MySQL 접속 테스트하기 🔄

설정이 완료되었다면, 다른 컴퓨터나 쿠버네티스 노드에서 MySQL에 접속할 수 있는지 테스트합니다:

# 다른 컴퓨터에서
mysql -h [Mac Mini IP 주소] -u your_username -p -P 3306

접속이 성공하면 외부 접속 설정이 올바르게 된 것입니다.

7. MySQL 접근 제어 및 보안 강화 🔒

외부 접속을 허용할 때 보안을 강화하기 위한 몇 가지 추가 설정:

  1. 특정 IP 주소만 허용: 위에서 설정한 대로 192.168.100.% 범위의 IP에서만 접속 가능하도록 사용자를 제한합니다.

  2. SSL/TLS 암호화 적용 (선택 사항):

    ALTER USER 'your_username'@'192.168.100.%' REQUIRE SSL;
    
  3. 리소스 제한 설정 (선택 사항):

    ALTER USER 'your_username'@'192.168.100.%' WITH 
        MAX_QUERIES_PER_HOUR 10000
        MAX_CONNECTIONS_PER_HOUR 1000;
    

결론 🎯

이제 Mac Mini에 MySQL을 설치하고 외부 접속을 위한 설정을 완료했습니다. 이 설정을 통해 쿠버네티스 클러스터에서 MySQL에 안전하게 접속할 수 있으며, 물뮤 프로젝트의 통합 데이터베이스를 효율적으로 관리할 수 있습니다.

다음 글에서는 Redis 설치 및 설정 방법과 함께 k3s 쿠버네티스 클러스터에 기본 인프라를 구축하는 방법에 대해 알아보겠습니다. 🚀

질문이나 의견이 있으시면 댓글로 남겨주세요! 💬

Installing MySQL on Mac Mini with External Access: A Guide for the MoolMeow Project 🐬

Hello there! In this guide, we’ll walk through installing MySQL on a Mac Mini and configuring it for external access from a Kubernetes cluster for the MoolMeow project. I’ll also share common troubleshooting tips that we encountered along the way! 🛠️

⚠️ Warning: All database names, usernames, and passwords used in this guide are examples only. In a real environment, you should use different values for security reasons.

1. Installing MySQL with Homebrew 🍺

On Mac, we can easily install MySQL using Homebrew.

Installing Homebrew

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# For zsh (default macOS shell)
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc

Installing and Starting MySQL

# Install MySQL
brew install mysql

# Start MySQL service
brew services start mysql

# Initial security setup
mysql_secure_installation

During the security setup, you’ll answer questions about:

  • Enabling password complexity validation
  • Setting a root password
  • Removing anonymous users
  • Disallowing root login remotely
  • Removing test database
  • Reloading privilege tables

2. Configuring MySQL for External Access 🌐

Finding MySQL Configuration File

For MySQL installed via Homebrew on Mac, the configuration file is typically located at:

# Check where MySQL is looking for config files
mysql --help | grep "Default options" -A 1

Usually, it’s at /opt/homebrew/etc/my.cnf.

Modifying the Configuration File

Edit the configuration file to allow external connections:

sudo nano /opt/homebrew/etc/my.cnf

Change the configuration content to:

# Default Homebrew MySQL server config
[mysqld]
# Allow connections from anywhere
bind-address = 0.0.0.0
mysqlx-bind-address = 0.0.0.0

[client]
socket=/tmp/mysql.sock

Setting bind-address = 0.0.0.0 allows MySQL connections from all network interfaces. Adding socket=/tmp/mysql.sock in the [client] section resolves socket connection issues.

Restarting MySQL

After changing the configuration, restart MySQL:

brew services restart mysql

3. Resolving “Can’t connect to local MySQL server through socket” Error 🔧

When connecting to MySQL, you might encounter this error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Here’s how to resolve it:

Method 1: Specify Socket Location

mysql -u root -p --socket=/tmp/mysql.sock

Method 2: Configure Socket in my.cnf

Add the socket location to the [client] section of your my.cnf file:

[client]
socket=/tmp/mysql.sock

This allows you to connect simply with mysql -u root -p.

Method 3: Check MySQL Logs

Check the MySQL logs to find the actual socket file location:

# Find MySQL process ID
ps aux | grep mysqld

# Check log file
tail -100 /opt/homebrew/var/mysql/*.err

Look for lines like socket: '/tmp/mysql.sock' to identify the actual socket location.

4. Creating Database and Users 🗄️

After connecting to MySQL, create a database and users for the MoolMeow project:

-- Create database (use a different name in your real environment)
CREATE DATABASE your_database_name;

-- Create user for local access (use different username and password)
CREATE USER 'your_username'@'localhost' IDENTIFIED BY 'use_strong_password_here';
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'localhost';

-- Create user for Kubernetes nodes
CREATE USER 'your_username'@'192.168.100.%' IDENTIFIED BY 'use_strong_password_here';
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'192.168.100.%';

-- Apply changes
FLUSH PRIVILEGES;

Here, 192.168.100.% represents the IP range of your Kubernetes cluster. This setting only allows connections from those IPs.

5. Designing an Integrated Database Structure 📊

For the MoolMeow project, it’s efficient to use an integrated database structure for managing posts and marketplace items that apply to both Mool and Meow sections.

-- Posts table (customize table names for your environment)
CREATE TABLE posts (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    section ENUM('section1', 'section2') NOT NULL,  -- Distinguishing field (use your actual values)
    title VARCHAR(255) NOT NULL,
    content TEXT,
    author_id BIGINT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_section (section),
    INDEX idx_author (author_id)
);

-- Marketplace items table (customize table names for your environment)
CREATE TABLE marketplace_items (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    section ENUM('section1', 'section2') NOT NULL,  -- Distinguishing field (use your actual values)
    title VARCHAR(255) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL,
    seller_id BIGINT NOT NULL,
    status ENUM('available', 'sold', 'reserved') DEFAULT 'available',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_section (section),
    INDEX idx_seller (seller_id),
    INDEX idx_status (status)
);

This structure uses a section field to distinguish between Mool and Meow items.

6. Testing External MySQL Connection 🔄

After completing the setup, test the connection from another computer or Kubernetes node:

# From another computer
mysql -h [Mac Mini IP address] -u your_username -p -P 3306

If the connection succeeds, your external access configuration is working correctly.

7. Strengthening MySQL Access Control and Security 🔒

Some additional settings to enhance security when allowing external access:

  1. Allow only specific IP addresses: As configured above, limit user connections to only the 192.168.100.% IP range.

  2. Apply SSL/TLS encryption (optional):

    ALTER USER 'your_username'@'192.168.100.%' REQUIRE SSL;
    
  3. Set resource limits (optional):

    ALTER USER 'your_username'@'192.168.100.%' WITH 
        MAX_QUERIES_PER_HOUR 10000
        MAX_CONNECTIONS_PER_HOUR 1000;
    

Conclusion 🎯

Now you’ve successfully installed MySQL on your Mac Mini and configured it for external access. With these settings, your Kubernetes cluster can securely connect to MySQL, and you can efficiently manage an integrated database for the MoolMeow project.

In the next guide, we’ll explore how to install and configure Redis, as well as how to set up the basic infrastructure on your k3s Kubernetes cluster. 🚀

Feel free to leave any questions or comments below! 💬

답글 남기기