backend/test/doc/NETWORK_SETUP.md

144 lines
3.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 網絡配置說明
## 🐳 Docker 容器訪問主機服務
當 API 服務器在主機上運行,而 k6 測試在 Docker 容器內運行時,需要配置網絡讓容器能夠訪問主機上的服務。
## ✅ 已配置的解決方案
本測試架構已經配置為使用**主機網絡模式**`--network host`),容器可以直接訪問主機上的服務。
### 配置說明
1. **Makefile**:所有 `docker run` 命令都添加了 `--network host` 參數
2. **docker-compose.yml**k6 服務使用 `network_mode: host`
### 使用方式
```bash
# 如果 API 在本地主機運行localhost
export BASE_URL=http://localhost:8888
# 或
export BASE_URL=https://localhost:8888
# 運行測試
make smoke-health
```
## 🔧 其他網絡配置選項
### 選項 1: 使用 host.docker.internal僅限 macOS/Windows
在 macOS 和 Windows 上Docker Desktop 提供了 `host.docker.internal` 主機名:
```bash
export BASE_URL=http://host.docker.internal:8888
make smoke-health
```
**注意**:在 Linux 上,`host.docker.internal` 默認不可用,需要額外配置。
### 選項 2: 使用主機 IP 地址
如果知道主機的 IP 地址,可以直接使用:
```bash
# 獲取主機 IP 地址
ip addr show | grep "inet " | grep -v 127.0.0.1
# 使用主機 IP
export BASE_URL=http://192.168.1.100:8888
make smoke-health
```
### 選項 3: 使用 Docker 網絡(如果 API 也在容器中)
如果 API 服務器也在 Docker 容器中運行,可以使用 Docker 網絡:
```yaml
# docker-compose.yml
services:
api:
# ... API 配置
k6:
# ... k6 配置
networks:
- test-network
extra_hosts:
- "host.docker.internal:host-gateway"
```
## 📝 常見問題
### Q: 為什麼使用 `--network host`
A: `--network host` 是最簡單可靠的方式,讓容器直接使用主機網絡,可以訪問 `localhost` 和主機上的所有端口。
### Q: 使用 `--network host` 有什麼限制?
A:
- 容器無法使用端口映射(因為直接使用主機端口)
- 在 macOS/Windows 上,`--network host` 可能不工作(需要使用 `host.docker.internal`
### Q: 如何測試連接?
A: 在容器內測試連接:
```bash
# 進入容器
docker run -it --rm --network host grafana/k6:latest sh
# 在容器內測試連接
curl http://localhost:8888/api/v1/health
```
### Q: HTTPS 證書問題?
A: 如果使用 HTTPS 但沒有有效證書,可以設置:
```bash
export K6_SKIP_TLS_VERIFY=true
make smoke-health
```
或在測試文件中設置:
```javascript
export const options = {
// ...
insecureSkipTLSVerify: true,
};
```
## 🚀 快速測試
### 測試本地 API
```bash
# 1. 確認 API 在本地運行
curl http://localhost:8888/api/v1/health
# 2. 設置 BASE_URL
export BASE_URL=http://localhost:8888
# 3. 運行測試
make smoke-health
```
### 測試遠程 API
```bash
# 1. 設置遠程 API 地址
export BASE_URL=https://api.example.com
# 2. 運行測試
make smoke-health
```
## 📚 參考資源
- [Docker 網絡文檔](https://docs.docker.com/network/)
- [k6 網絡配置](https://k6.io/docs/using-k6/options/#insecureskiptlsverify)