#!/bin/bash # Show RAM usage for containers # Usage: ./show-ram.sh [compose-file-name] # Without argument: shows all containers and total server RAM # With argument: shows containers for specific node BASEPATH="$(dirname "$0")" COMPOSE_NAME="$1" # Function to calculate and print total from container IDs calc_total() { local container_ids="$1" local total_mib=$(docker stats --no-stream --format "{{.MemUsage}}" $container_ids | \ awk -F'/' '{ val=$1; gsub(/[^0-9.]/,"",val); if($1 ~ /GiB/) val*=1024; sum+=val } END {printf "%.0f", sum}') if [ "$total_mib" -ge 1024 ] 2>/dev/null; then local total_gib=$(echo "scale=2; $total_mib / 1024" | bc) echo "${total_gib} GiB" else echo "${total_mib} MiB" fi } if [ -z "$COMPOSE_NAME" ]; then # No argument: show all containers grouped by compose project echo "RAM usage for all nodes:" echo "========================================" # Get all running containers ALL_CONTAINERS=$(docker ps -q 2>/dev/null) if [ -z "$ALL_CONTAINERS" ]; then echo "No running containers found" exit 0 fi # Show stats for all containers, sorted by memory usage (descending) docker stats --no-stream --format "table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}" $ALL_CONTAINERS | \ head -1 docker stats --no-stream --format "{{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}" $ALL_CONTAINERS | \ sort -t$'\t' -k2 -h -r echo "========================================" # Calculate total echo -n "Total container RAM: " calc_total "$ALL_CONTAINERS" # Show server total RAM total_server_ram=$(free -h | awk '/^Mem:/ {print $2}') used_server_ram=$(free -h | awk '/^Mem:/ {print $3}') echo "Server RAM: ${used_server_ram} / ${total_server_ram}" else # Specific node COMPOSE_FILE="${BASEPATH}/${COMPOSE_NAME}.yml" if [ ! -f "$COMPOSE_FILE" ]; then echo "Error: Compose file not found: $COMPOSE_FILE" exit 1 fi # Get container IDs for this compose project CONTAINER_IDS=$(docker compose -f "$COMPOSE_FILE" ps -q 2>/dev/null) if [ -z "$CONTAINER_IDS" ]; then echo "No running containers found for $COMPOSE_NAME" exit 0 fi echo "RAM usage for $COMPOSE_NAME:" echo "----------------------------------------" # Show stats for each container docker stats --no-stream --format "{{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}" $CONTAINER_IDS echo "----------------------------------------" echo -n "Total: " calc_total "$CONTAINER_IDS" fi