Skip to content

Instantly share code, notes, and snippets.

@spinanicky
Created September 22, 2023 08:57
Show Gist options
  • Save spinanicky/d82763292cacf357b26fd2dfcf11836c to your computer and use it in GitHub Desktop.
Save spinanicky/d82763292cacf357b26fd2dfcf11836c to your computer and use it in GitHub Desktop.
Allows you to rapidly identify and kill hung shinyproxy containers
#!/bin/bash
# NOTE: UPDATE PATH TO LOG FILES ON LINE 10
# Prune all stopped containers
echo "Prune all stopped/hung containers:"
docker container prune
# Search the log file for the last occurrence of the specified message
last_failed_bind=$(grep -Eo "Bind for 0.0.0.0:[0-9]+ failed: port is already allocated|listen tcp4 0.0.0.0:[0-9]+: bind: address already in use" /PATHTOLOGS/shinyproxy.log | tail -n 1)
# Extract the port number from the message (if found)
if [[ $last_failed_bind =~ ([0-9]+) ]]; then
suggested_port=$(echo "$last_failed_bind" | grep -oP ':\K\d+')
fi
# Ask the user for the port number
read -p "Enter the port number (or press Enter to use suggested port $suggested_port): " user_port
# Use the suggested port if the user didn't provide one
if [ -z "$user_port" ]; then
port="${suggested_port}"
else
port="${user_port}"
fi
# Use docker ps to find the container using the specified port
container_name=$(docker ps --format "table {{.Names}}\t{{.Ports}}" | grep ":${port}->" | awk '{print $1}')
# Check if a container was found
if [ -n "$container_name" ]; then
echo "Container using port $port: $container_name"
# Prompt the user for confirmation before forcefully removing the container
read -p "Do you want to forcefully remove this container? (y/n): " choice
if [ "$choice" == "y" ]; then
docker rm -f "$container_name"
echo "Container removed."
else
echo "Container not removed."
fi
else
echo "No container found using port $port"
# Try to identify the PID associated with the port
pid=$(sudo lsof -n -i :$port -t)
if [ -n "$pid" ]; then
echo "Process using port $port has PID: $pid"
# Display details of the process
echo "Details of the process:"
ps -p $pid -o pid,ppid,cmd,stat,stime,%cpu,%mem
# Ask the user if they want to kill the process
read -p "Do you want to kill this process? (y/n): " kill_choice
if [ "$kill_choice" == "y" ]; then
sudo kill -9 $pid
echo "Process killed."
else
echo "Process not killed."
fi
else
echo "No process found using port $port"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment