centos上的keepalived开机自启动脚本如何编写如何配置
时间: 2024-12-08 10:23:45 浏览: 20
在CentOS上设置Keepalived服务开机自启动,你需要编写一个init.d脚本来管理服务,并配置相应的服务文件以便系统启动时自动运行Keepalived。以下是基本步骤:
1. **创建或编辑init.d脚本**:
- 首先,打开文本编辑器(如`vim`, `nano`或`emacs`),创建一个新的bash脚本文件,例如 `/etc/init.d/keepalived`:
```
sudo nano /etc/init.d/keepalived
```
- 在脚本中添加基本的启动、停止、重启命令以及状态检查函数,参考 Keepalived 的官方文档。
```bash
#!/bin/bash
# ... (添加相应函数,比如 start, stop, restart 和 status)
# 以root权限运行,然后执行命令
if [ "$1" = "start" ]; then
service keepalived start
elif [ "$1" = "stop" ]; then
service keepalived stop
elif [ "$1" = "restart" ]; then
service keepalived restart
elif [ "$1" = "status" ]; then
service keepalived status
else
echo $"Usage: $0 {start|stop|restart|status}"
exit 1
fi
exit 0
```
2. **给脚本增加执行权限**:
```
chmod +x /etc/init.d/keepalived
```
3. **更新运行级别脚本**:
将Keepalived添加到系统默认运行级别脚本中,通常是在 `/etc/rc.d/rc.local` 或 `/etc/rc.d/rcX.d/S99keepalived`,其中 X 表示你的系统运行级别。添加类似下面的内容:
```bash
# chkconfig: - 2345 99
# description: Keepalived HA cluster setup
/etc/init.d/keepalived start || true
```
4. **启用开机自启动**:
使用 `chkconfig` 工具将Keepalived服务设置为开机自启动,例如:
```
chkconfig keepalived on
```
5. **配置Keepalived**: 你需要在 `/etc/keepalived/keepalived.conf` 文件中编写VRRP(Virtual Router Redundancy Protocol)配置。这包括主备节点的选择、监控网络接口、虚拟IP地址等。
完成以上步骤后,你可以通过 `service keepalived start` 启动服务,`chkconfig keepalived status` 查看状态,`service keepalived restart` 重启服务等。
阅读全文