动态监控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
相关推荐
C_心欲无痕1 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
冰西瓜6002 小时前
国科大2025操作系统高级教程期末回忆版
linux
HIT_Weston3 小时前
93、【Ubuntu】【Hugo】搭建私人博客:面包屑(一)
linux·运维·ubuntu
cuijiecheng20183 小时前
Linux下Beyond Compare过期
linux·运维·服务器
HIT_Weston3 小时前
92、【Ubuntu】【Hugo】搭建私人博客:侧边导航栏(六)
linux·运维·ubuntu
CodeAllen嵌入式3 小时前
Windows 11 本地安装 WSL 支持 Ubuntu 24.04 完整指南
linux·运维·ubuntu
码农小韩5 小时前
基于Linux的C++学习——指针
linux·开发语言·c++·学习·算法
wdfk_prog5 小时前
[Linux]学习笔记系列 -- [fs]seq_file
linux·笔记·学习
Jay Chou why did6 小时前
wsl安装完无法进入wsl
linux
石头5306 小时前
Rocky Linux 9.6 docker k8s v1.23.17 kubeadm 高可用部署文档
linux