动态监控U盘重启容器

需求背景

Ubuntu机器需要动态根据插入的U盘进行导入数据, 路径是约定为U盘内的固定路径.

但是服务是docker服务, 插入U盘并不会直接挂在到容器内部, 需要重启容器才能生效, 每次手动重启很麻烦, 自动检测U盘路径变化来操作容器.

配置动态监控脚本和服务

安装服务

sudo apt-get update
sudo apt-get install inotify-tools

编写脚本

vim monitor_and_restart.sh

脚本内容:

  • MONITOR_DIR: 替换为自己需要监控的路径(当前是插入U盘会在/media/guimu/路径下生成一个CENTOS文件夹, 所以根据实际情况进行修改为自己的路径即可)
  • CONTAINER_NAME: 需要重启的容器名
#!/bin/bash

# 定义要监控的目录和容器名称
MONITOR_DIR="/media/guimu/"
CONTAINER_NAME="das-data-raw-service"

# 监控目录变化,并在变化发生时重启容器
while true; do
    inotifywait -r -e modify,create,delete,move "$MONITOR_DIR"
    echo "Detected changes in $MONITOR_DIR. Restarting container $CONTAINER_NAME..."
    docker restart "$CONTAINER_NAME"
done

添加可执行权限:

chmod +x monitor_and_restart.sh

配置服务

sudo vim /etc/systemd/system/monitor_and_restart.service

编辑内容:

[Unit]
Description=Monitor and Restart das-data-raw-service Container
After=network.target

[Service]
Type=simple
ExecStart=/root/das-docker/monitor_and_restart.sh

[Install]
WantedBy=multi-user.target
  • 替换ExecStart为自己的脚本存放路径
# 开启自启
sudo systemctl enable monitor_and_restart.service
# 开启服务
sudo systemctl start monitor_and_restart.service
# 查看服务状态
sudo systemctl status monitor_and_restart.service
# 停止服务
sudo systemctl stop monitor_and_restart.service

你可能感兴趣的:(linux)