Skip to content

Instantly share code, notes, and snippets.

@muness
Created January 10, 2026 12:34
Show Gist options
  • Select an option

  • Save muness/52379158d4206b161eafab0c948a83c4 to your computer and use it in GitHub Desktop.

Select an option

Save muness/52379158d4206b161eafab0c948a83c4 to your computer and use it in GitHub Desktop.
Recover running Docker containers as Dockge stacks
#!/bin/bash
# Recover running containers as Dockge stacks
STACKS_DIR="${1:-/share/Container/stacks}"
mkdir -p "$STACKS_DIR"
# Get all running containers (excluding dockge itself)
containers=$(docker ps --format '{{.Names}}' | grep -v dockge)
for container in $containers; do
# Extract stack name (remove -1, -2 suffixes from compose)
stack_name=$(echo "$container" | sed 's/-[0-9]*$//' | sed 's/_/-/g')
stack_dir="$STACKS_DIR/$stack_name"
# Skip if we already created this stack
if [ -d "$stack_dir" ]; then
echo "Skipping $container (stack $stack_name already exists)"
continue
fi
echo "Processing: $container -> $stack_name"
mkdir -p "$stack_dir"
# Get container inspect data
inspect=$(docker inspect "$container")
# Extract key values
image=$(echo "$inspect" | jq -r '.[0].Config.Image')
# Get port mappings
ports=$(echo "$inspect" | jq -r '.[0].NetworkSettings.Ports | to_entries | .[] | select(.value != null) | .value[0].HostPort + ":" + .key' | sed 's/\/tcp//' | sed 's/\/udp/:udp/')
# Get volume mounts
mounts=$(echo "$inspect" | jq -r '.[0].Mounts[] | select(.Type == "bind") | .Source + ":" + .Destination')
# Get environment variables (excluding PATH and common defaults)
envs=$(echo "$inspect" | jq -r '.[0].Config.Env[] | select(startswith("PATH=") | not) | select(startswith("HOME=") | not) | select(startswith("HOSTNAME=") | not)')
# Get restart policy
restart=$(echo "$inspect" | jq -r '.[0].HostConfig.RestartPolicy.Name')
[ "$restart" = "no" ] && restart=""
# Build compose file
cat > "$stack_dir/compose.yaml" << EOF
services:
$stack_name:
image: $image
container_name: $container
EOF
# Add restart policy
if [ -n "$restart" ] && [ "$restart" != "null" ]; then
echo " restart: $restart" >> "$stack_dir/compose.yaml"
fi
# Add ports
if [ -n "$ports" ]; then
echo " ports:" >> "$stack_dir/compose.yaml"
echo "$ports" | while read -r port; do
[ -n "$port" ] && echo " - \"$port\"" >> "$stack_dir/compose.yaml"
done
fi
# Add volumes
if [ -n "$mounts" ]; then
echo " volumes:" >> "$stack_dir/compose.yaml"
echo "$mounts" | while read -r mount; do
[ -n "$mount" ] && echo " - $mount" >> "$stack_dir/compose.yaml"
done
fi
# Add environment
if [ -n "$envs" ]; then
echo " environment:" >> "$stack_dir/compose.yaml"
echo "$envs" | while read -r env; do
[ -n "$env" ] && echo " - $env" >> "$stack_dir/compose.yaml"
done
fi
echo " Created: $stack_dir/compose.yaml"
done
echo ""
echo "Done! Restart Dockge to see recovered stacks:"
echo " docker restart dockge"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment