# MongoServerError：副本集成员 127.0.0.1:27017 解析为 192.168.1.1:27017，但 replSetInitiate 期望主机名为 'localhost'

- **ID:** `database/mongodb-replica-set-hostname-mismatch`
- **领域:** database
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

副本集初始化期间使用的主机名与 MongoDB 内部解析的主机名不匹配，通常由于 DNS 或 /etc/hosts 配置错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MongoDB 5.0.x | active | — | — |
| MongoDB 6.0.x | active | — | — |
| MongoDB 7.0.x | active | — | — |

## 解决方案

1. ```
   确保所有副本集成员使用与 DNS 或 /etc/hosts 匹配的 FQDN：编辑 /etc/hosts 添加 '127.0.0.1 localhost hostname.domain.com'，并在 rs.initiate() 中使用 hostname.domain.com。
   ```
2. ```
   通过以下方式重新配置副本集：cfg = rs.conf(); cfg.members[0].host = 'correctHostname:27017'; rs.reconfig(cfg);
   ```

## 无效尝试

- **Changing the hostname in /etc/hostname without updating /etc/hosts** — MongoDB uses both hostname resolution and network interfaces; only updating one file leaves inconsistency. (70% 失败率)
- **Using IP addresses in replSetInitiate configuration** — IP addresses can change after reboot or network reconfiguration, causing replica set to fail on restart. (80% 失败率)
