# How to use LBaaS for mysql Load Balancing

## Introduction

เอกสารนี้จะแนะนำการตั้งค่า LBaaS  เพื่อทำ Load Balancing สำหรับการอ่านข้อมูลจาก MySQL Replicas (Slaves) โดยมีเป้าหมายเพื่อเพิ่ม performance ในการรองรับการอ่านจำนวนมาก (Read Scaling) และเพิ่มความพร้อมใช้งาน (High Availability) ให้กับระบบฐานข้อมูล โดยจะต้องมีระบบ MySQL ที่ตั้งค่า Master-Slave Replication ไว้เรียบร้อยแล้ว (มี Master 1 ตัว และ Slave อย่างน้อย 1 ตัว)​ ซึ่งต้องติดตั้ง MySQL Health Check สำหรับตรวจสอบสถานะความพร้อมของ MySQL Server (โดยเฉพาะ Slave/Replica) เพื่อให้ LBaaS สามารถตรวจสอบได้ว่า server ไหนพร้อมใช้งาน และตั้งค่า LBaaS บน Nipa Cloud Space เพื่อทำหน้าที่กระจาย request ไปยัง backend group ที่สร้างไว้ ในส่วนของการเชื่อมต่อสำหรับการเขียน (Write) client จะเชื่อมต่อ MySQL Master ผ่าน Listener Port 3306 และสำหรับการอ่าน (Read) client จะเชื่อมต่อ MySQL Replica ผ่าน Listener Port 3307

<figure><img src="/files/DeUwvuVnyUDqnBpllsuW" alt="" width="563"><figcaption><p>Diagram แสดง flow การใช้งาน LBaaS กับ MySQL databases</p></figcaption></figure>

## Prerequisite

* มีการติดตั้ง mysql master-slave&#x20;
* มีการ create และ attach security group port 9200&#x20;

{% hint style="info" %}
สามารถดูวิธีการสร้าง security group ได้ที่ [Create a Security Group](/ncs-documents/networking/security-group/create-a-security-group.md)
{% endhint %}

## Objective

เพื่อให้ mysql มี healthcheck ให้ตรวจสอบได้ว่าพร้อมรับ request จาก loadbalancer จีงจำเป็นต้องมี tool ในการเช็ค โดยจะเลือกใช้การติดตั้งผ่าน docker และ run container mysqlcheck ตรวจสอบสถานะ MySQL Slave ได้อย่างแม่นยำ  สำหรับรัน Healthcheck script เพื่อตรวจสอบว่า replication ยังทำงาน (`Slave_IO_Running` และ `Slave_SQL_Running` เป็น `Yes`) และ slave ไม่ lag จาก master ด้วย port 9200 ใช้เป็น port สำหรับ healthcheck จาก loadbalancer วิธีนี้ช่วยให้มั่นใจว่า client อ่านข้อมูลจาก slave ที่ sync อยู่เสมอ (HTTP respone 200) และยังสามารถทำ self-healing เมื่อมี connection timeout จากที่ตั้งค่าไว้ จะมีการ restart service MySQL แบบ automate ได้อีกด้วย

#### โดย Service mysqlcheck จะมี HTTP Response ดังนี้

| Role   | Status                        | Response |
| ------ | ----------------------------- | -------- |
| slave  | healthy                       | 200      |
| slave  | not healthy (not sync, error) | 503      |
| master | healthy                       | 200      |
| other  | -                             | 200      |

## Instructions

วิธีการติดตั้งให้ดำเนินการ ดังนี้

### 1. Create MySQL user

เพื่อให้ LoadBalancer สามารถ healthcheck ผ่าน command select ได้

```
CREATE USER 'lb_heathcheck'@'%' IDENTIFIED WITH mysql_native_password BY 'your_secure_password';
GRANT SELECT ON performance_schema.* TO 'lb_heathcheck'@'%';
FLUSH PRIVILEGES;
```

### 2. ssh & install docker, docker-compose

ให้ ssh เข้าไปที่ mysql host และ install docker เพื่อจะทำเป็น healthcheck

```
sudo apt update && sudo apt install docker.io docker-compose -y
```

### 3. create docker-compose file

สร้าง directory mysqlcheck แล้วสร้าง docker-compose.yaml file

```
version: "3"
services:
    mysqlcheck:
        container_name: mysqlcheck
        network_mode: host
        restart: unless-stopped
        volumes:
        - /var/run/mysqld/:/var/run/mysqld/
        image: registry.nipa.cloud/nipa-public-services/mysqlcheck:v1
        environment:
          MYSQL_USERNAME: lb_heathcheck        ## mysql healthcheck user 
          MYSQL_PASSWORD: xxxxxx               ## mysql healthcheck password 
          RESTART_ON_TIMEOUT: 'TRUE'           ## enable/disable auto restart mysql
          RESTART_MYSQL_TIMEOUT: '1800         ## timeout for call restart in second 
          CACHE_EXPIRE: '5'                    ## caching timeout second
          HEALTHCHECK_PORT: '9200'             ## binding port for script
```

### 4. docker-compose up

ทำการ docker-compose up เพื่อสร้าง container environment

```
docker-compose up -d --build
```

### 5. verify docker ทำงานถูกต้อง

ตรวจสอบ service ว่าทำงานถูกต้องด้วย command

```
curl 0.0.0.0:9200
```

Slave Node:

&#x20;       expect response: (status code 200)

```
{"message":"[Slave] MySQL Server Master-Slave is synced."}
```

Master Node:

&#x20;       expect response: (status code 200)

```
{"message":"[Master] MySQL Server Master-Slave is available."}
```

### 6. create Loadalance (ต้องสร้างภายใน VPC Networking เดียวกันกับ database)

{% hint style="info" %}
สามารถดูวิธีการติดตั้ง LoadBalancer ได้ที่ [LOAD BALANCING](/ncs-documents/load-balancing/load-balancer.md)
{% endhint %}

### 7. create backend group

* สร้าง backend group สำหรับ role writer แล้วใช้ healthcheck แบบ http โดย check ไปที่ port 9200

<figure><img src="/files/E9j4FYdZAkSTmfcuL5F0" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/iBCch3fVBxiHQZCbVbW3" alt="" width="563"><figcaption></figcaption></figure>

* สร้าง backend group สำหรับ role reader แล้วใช้ healthcheck แบบ http โดย check ไปที่ port 9200 โดย role reader จะมี Algorithm แบบ round robin และเพิ่ม Member List ของ slave host

<figure><img src="/files/pbKBkByk1fAZZbkkulZz" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/c1dwnaJbWtIZ8oyQLGr4" alt="" width="563"><figcaption></figcaption></figure>

เมื่อสร้างทั้งหมดจะได้ทั้ง role-writer และ role-reader

<figure><img src="/files/45wQMmK7uqtMhyNC3FZX" alt=""><figcaption></figcaption></figure>

### 8. create listener

* ให้ไปที่ tab Listener แล้วดำเนินการสร้าง role-writer โดยจะใช้ TCP port 3306

<figure><img src="/files/qIJdS6SamzyYcbTpIPD8" alt=""><figcaption></figcaption></figure>

* จากนั้นสร้าง role-reader โดยใช้ TCP port 3307

<figure><img src="/files/IV8LeyNlXA2ypeF3UgdY" alt=""><figcaption></figcaption></figure>

เมื่อสร้างเสร็จแล้วจะได้ทั้ง role-writer และ role-reader

<figure><img src="/files/6OqrWxcfdejeJo4Ow1q7" alt=""><figcaption></figcaption></figure>

### 9. verify via mysql login

ทดสอบเข้าใช้งานด้วยการใช้ mysql cli

```
mysql -h${LoadBalancer_IP} -P${writer_port} -u${username} -p'${password} -e'select @@hostname'
```

<figure><img src="/files/ymHhdWLWdcrlzKywwQgP" alt=""><figcaption><p>การเข้าใช้งานด้วย LoadBalancer IP และ Port สำหรับ Writer</p></figcaption></figure>

```
mysql -h${LoadBalancer_IP} -P${reader_port} -u${username} -p'${password} -e'select @@hostname'
```

<figure><img src="/files/ZYjDESqkBNMdYHStmLXD" alt=""><figcaption><p>การเข้าใช้งานด้วย LoadBalancer IP และ Port สำหรับ Reader</p></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs-epc.gitbook.io/ncs-documents/tutorial/how-to-use-lbaas-for-mysql-load-balancing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
