How to restart container when usb recconecting

Hello. I need help with one problem.
We have a container that works with a usb port.
It happens that the device reconnects itself, maybe someone reconnects it, but when the device is reconnected, it does not take the ttyACM0 port that it needs to work, but takes ttyACM1 (because ttyACM0 is occupied by a running container) and the container does not work out the functions assigned to it.
So maybe there is a way to restart the container when usbACM0 goes down and restart the container until it sees the connected ACM0 usb port.

I have three ideas, but I haven’t tried to use USB device in a container yet.

  1. Depending on what you want to do with the device, try to mount the device into a folder on your host and mount that folder into your container.
  2. Try to use udev to give a persistent name to your USB device. Again, I haven’t tried, so this is just an idea:
    Persistent names for USB-serial devices in Linux (/dev/ttyUSBx -> /dev/custom-name) | by Islam Negm (Mr.Bit) | Medium
  3. With udev you can also handle events, like when you plug a usb device in or when you disconnect it. That way you could recreate your container when someone reconnects the usb device:
    Detecting a USB Plug/Unplug Efficiently – Yet Another Technical Blog

Good day. Im not sure that it is will resolve this. We need to restart container every time, when USB is disconnecting.

Then I don’t understand the problem since I just wrote this:

If you can recreate it, then you can also restart it. It is up to you. Sometimes restarting is not enough and there is only a little difference between restarting and recreating, since the process inside the container will be restarted in both cases, but you need to recreate a container if for some reasons the device gets a different name.

1 Like

I tried to do it this way, but something went wrong. Here is command to stop and restart container.

Maybe i do something wrong?
Not sure, that my syntax is right.

Here is log output

Problem resolved, i made some changes in rule syntax and its works, thanks!

Do you mind sharing your solution, so the next one having the same problem will not just find a discussion, but will also find your solution :slight_smile:

1 Like

Im just create file with rules in /etc/udev/rules.d/
SUBSYSTEM==“tty”, KERNEL==“ttyACM*” SYMLINK+=“arduino”
SUBSYSTEM==“tty”, KERNEL==“ttyACM*”, RUN+=“/bin/sh /home/username/”
So any device, that have name ttyACM* will named “arduino”. We need this because it needs to have 1 stable port. In this case it always will be “arduino”
Another step just restarting container when arduino connecting/disconnecting. docker restart container_name

1 Like

Thank you for sharing your solution!