为了在 Hadoop 集群中通过 ntpd(Network Time Protocol Daemon)实现集群时间同步,并使 hd1 作为时间服务器,hd2 和 hd3 与 hd1 实现定时同步时间,按照以下详细步骤进行配置。确保集群中的所有节点都正确同步时间,以便避免由于时间不一致而导致的各种问题(如 HDFS 写入、YARN 调度等)。
步骤概述
配置 hd1 作为 NTP 时间服务器。
配置 hd2 和 hd3 从 hd1 同步时间。
配置定时任务,每隔 10 分钟同步一次时间。
步骤 1: 配置 hd1 作为 NTP 时间服务器
hd1 将作为时间服务器,提供时间同步服务。我们将安装并配置 ntpd 服务,使其能够从互联网时间服务器获取时间并对其他节点提供服务。
a. 安装 ntpd
在 hd1 上安装 ntpd:
sudo yum install -y ntp
b. 配置 ntpd 服务
编辑 NTP 配置文件 /etc/ntp.conf,配置 hd1 作为时间服务器。
sudo vi /etc/ntp.conf
确保文件中存在以下配置:
启用本机作为 NTP 时间服务器
broadcast 192.168.1.255 # 或者将其替换为具体的广播地址,确保局域网内的机器可以接收到时间广播。
指定外部 NTP 时间源
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
允许局域网内的机器访问本机 NTP 服务
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap nopeer
server:指定外部 NTP 服务器,iburst 是为了在首次启动时加快同步速度。
restrict:限制只允许内网(如 192.168.1.0/24 网段)上的机器访问时间服务。
c. 启动 NTP 服务
启动并启用 ntpd 服务,使其开机自启:
sudo systemctl start ntpd
sudo systemctl enable ntpd
d. 验证时间同步
检查 hd1 的时间同步状态:
ntpq -p
该命令将显示连接的时间服务器列表以及同步状态,确认 hd1 已经成功同步时间。
步骤 2: 配置 hd2 和 hd3 从 hd1 同步时间
在 hd2 和 hd3 上,您需要配置 ntpd 使其从 hd1 同步时间。
a. 安装 ntpd
在 hd2 和 hd3 上安装 ntpd 服务:
sudo yum install -y ntp
b. 配置 ntpd 客户端
编辑 /etc/ntp.conf 文件,配置 hd2 和 hd3 从 hd1 同步时间:
sudo vi /etc/ntp.conf
将配置文件中的时间服务器修改为 hd1 的 IP 地址,例如:
server hd1 iburst # 使用 hd1 作为时间服务器
确保没有 restrict 配置禁止本机连接到 NTP 服务器。
c. 启动 NTP 服务
启动并启用 ntpd 服务,使其开机自启:
sudo systemctl start ntpd
sudo systemctl enable ntpd
d. 验证同步状态
检查 hd2 和 hd3 是否成功连接到 hd1 并同步时间:
ntpq -p
步骤 3: 配置定时同步任务(每 10 分钟同步一次)
a. 配置定时任务
在 hd2 和 hd3 上,配置 cron 任务来定期强制同步时间。
打开 crontab 配置:
sudo crontab -e
添加一条每 10 分钟执行一次的定时任务:
*/10 * * * * /usr/sbin/ntpdate -u hd1
这条命令会每 10 分钟执行一次 ntpdate,通过指定 hd1 作为时间服务器强制同步时间。
保存并退出 crontab 配置文件。
b. 配置 hd1 允许外部 NTP 客户端访问
确保 hd1 的防火墙设置允许 hd2 和 hd3 从 hd1 同步时间。如果有防火墙限制,请允许 ntpd 服务的端口(默认端口是 123)通过防火墙。
对于 firewalld(在 CentOS/RHEL 7+):
sudo firewall-cmd --zone=public --add-service=ntp --permanent
sudo firewall-cmd --reload
步骤 4: 验证集群时间同步
在 hd2 和 hd3 上,运行以下命令确认时间同步是否正常:
date
确认时间已经从 hd1 同步过来。
在 hd1 上,您可以查看 ntpd 的状态,确保其正常工作:
ntpq -p
确保 hd2 和 hd3 都列在同步客户端列表中。
总结
通过以上步骤,已成功配置了:
hd1 作为时间服务器:通过 ntpd 服务,hd1 将提供时间同步服务。
hd2 和 hd3 从 hd1 同步时间:通过修改 ntp.conf 配置文件,使 hd2 和 hd3 从 hd1 同步时间。
定时同步时间:通过 cron 配置每 10 分钟执行一次 ntpdate 命令,强制同步时间。