Last active
September 24, 2024 14:55
-
-
Save davidpp/37e8dbeb856b58217dcea4cdd7b4fae8 to your computer and use it in GitHub Desktop.
pg_dump for easypanel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Function to find the container ID of a service's first running task | |
find_container_id() { | |
local service_name=$1 | |
docker service ps --filter "desired-state=running" --format "{{.ID}}" $service_name | head -n 1 | xargs -I {} docker inspect --format "{{.NodeID}} {{.Status.ContainerStatus.ContainerID}}" {} | awk '{print $2}' | |
} | |
# Function to extract the database name from the service name | |
extract_db_name() { | |
local service_name=$1 | |
echo "${service_name%%_*}" | |
} | |
# Get all Docker services containing "db" in their name | |
db_services=$(docker service ls --format "{{.Name}}" | grep db) | |
# Check if any db services were found | |
if [ -z "$db_services" ]; then | |
echo "No Docker services containing 'db' were found." | |
exit 1 | |
fi | |
# Create an array of db services | |
mapfile -t service_array <<< "$db_services" | |
# Display the list of services | |
echo "Available DB services:" | |
for i in "${!service_array[@]}"; do | |
echo "$((i+1)). ${service_array[$i]}" | |
done | |
# Prompt user to select a service | |
while true; do | |
read -p "Enter the number of the source database service (1-${#service_array[@]}): " selection | |
# Validate input | |
if [[ "$selection" =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le "${#service_array[@]}" ]; then | |
source_service="${service_array[$((selection-1))]}" | |
break | |
else | |
echo "Invalid selection. Please enter a number between 1 and ${#service_array[@]}." | |
fi | |
done | |
# Find container ID for source service | |
source_container_id=$(find_container_id $source_service) | |
# Extract database name from service name | |
source_db_name=$(extract_db_name $source_service) | |
# Database user | |
db_user="postgres" | |
# Get current timestamp | |
timestamp=$(date +"%Y%m%d_%H%M%S") | |
# Define the dump file name | |
dump_file="${source_db_name}_${timestamp}.sql" | |
# Perform the data dump | |
if ! docker exec $source_container_id pg_dump -U $db_user -d $source_db_name | cat > "$dump_file"; then | |
echo "Error: Data dump failed." | |
exit 1 | |
fi | |
echo "Data dump completed successfully. File saved as: $dump_file" | |
# Optionally, compress the dump file | |
read -p "Do you want to compress the dump file? (y/n): " compress_choice | |
if [[ $compress_choice == "y" ]]; then | |
gzip "$dump_file" | |
echo "Dump file compressed: ${dump_file}.gz" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment