March 27Mar 27 I recently setup a wireguard container through which a bunch of other children containers (e.g. qbittorrent, radarr) depend on its network for the VPN capability.One problem I encountered was the sudden loss of network interface within the wireguard container (I figure there must be somekind of reset once in a while). The wireguard container would set itself backup automatically, but the children containers would loose all connection to the network interface created. It turns out this is currently a problem known and unsolved in the docker community (Issue example).I wanted a solution that was simple and that would allow me to scale well with my infinite thirst for MORE CONTAINERS. I decided to write a script that would use CURL to check for a web UI response and if the request fails, it restarts the container. To make it scale with the amount of containers I would create, the script automatically detects containers with an "autorestart-curl" label. The value of the label is the endpoint curl should hit to detect if the web UI is still active. Adding a label is pretty simple in unraid docker so this is very easy to implement.All that was left to do was to schedule the script to run periodically using the User Script plugin.Here is the bash script:#!/bin/bash # Function to check service and restart container if needed check_and_restart() { local container_name="$1" local target_url="$2" # Perform curl request and capture both output and HTTP code local response=$(curl -L -s -w "\n%{http_code}" \ --connect-timeout 5 \ --max-time 5 \ "$target_url" 2>&1) local http_code=$(echo "$response" | tail -n1) local body=$(echo "$response" | sed '$d') # Check for connection errors if echo "$body" | grep -qE "Connection reset|Connection refused|Timeout|Empty reply|Failed to connect"; then echo "[$(date +'%Y-%m-%d %H:%M:%S')] Connection error for $container_name - Restarting..." docker restart "$container_name" return 1 fi # Check if HTTP response is valid (2xx or 3xx) if [[ "$http_code" =~ ^[23][0-9]{2}$ ]]; then echo "[$(date +'%Y-%m-%d %H:%M:%S')] $container_name healthy (HTTP $http_code)" return 0 else echo "[$(date +'%Y-%m-%d %H:%M:%S')] $container_name unhealthy (HTTP $http_code) - Restarting..." docker restart "$container_name" return 1 fi } # Retrieve list of active containers with autorestart-curl label containers=$(docker ps --filter label=autorestart-curl --format $'{{.Names}}\t{{.Label "autorestart-curl"}}') printf '%s\n' "$containers" | while IFS=$'\t' read -r name endpoint; do [ -z "$name" ] && continue check_and_restart "$name" "$endpoint" doneScript was built using LLM, but every line has been verified.Let me know what you think.
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.