动态监控U盘重启容器

需求背景

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

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

配置动态监控脚本和服务

编写脚本

复制代码
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
相关推荐
江公望1 小时前
Ubuntu htop命令,10分钟讲清楚
linux·服务器
哎呦,帅小伙哦1 小时前
Linux 时间:从原子钟到 clock_gettime 的每一面
linux·运维·服务器
张小姐的猫1 小时前
【Linux】多线程 —— 线程互斥
linux·运维·服务器·c++
YuanDaima20482 小时前
Linux 进阶运维与 AI 环境实战:进程管理、网络排错与 GPU 监控
linux·运维·服务器·网络·人工智能
lolo大魔王3 小时前
Linux 数据文件处理实战:排序、搜索、压缩、归档一站式详解
linux·运维·服务器
starvapour4 小时前
Ubuntu切换到Fcitx5中文输入法
linux·运维·ubuntu
lolo大魔王4 小时前
Linux的监测程序
linux·运维·github
.YYY4 小时前
RHCE--Linux循环执行的例行性任务:crontab从入门到精通
linux·运维·服务器
木欣欣粉皮4 小时前
解决Ubuntu 26.04的挂起状态唤醒问题
linux·运维·ubuntu
ambition202424 小时前
UNIX消息队列:从理论模型到工程实现的演进
linux·服务器·unix