Add docker-network.sh

This commit is contained in:
2025-07-03 19:17:27 +00:00
parent ee0e055106
commit 79d19d4d4b

63
docker-network.sh Normal file
View File

@@ -0,0 +1,63 @@
#!/bin/bash
set -euo pipefail
# -------------------------------
# Prompt user for subnet base
# -------------------------------
read -rp "Enter the second octet for your Docker network (e.g., 100 for 10.100.0.0/16): " octet
# Validate that it's a number between 1 and 254
if ! [[ "$octet" =~ ^[0-9]{1,3}$ ]] || ((octet < 1 || octet > 254)); then
echo "Invalid input. Must be a number between 1 and 254."
exit 1
fi
# -------------------------------
# Define values
# -------------------------------
DOCKER_CONFIG_FILE="/etc/docker/daemon.json"
ADDRESS_POOL_BASE="10.${octet}.0.0/16"
ADDRESS_POOL_SIZE=24
NETWORK_NAME="bridge_default"
NETWORK_SUBNET="10.${octet}.1.0/24"
# -------------------------------
# Replace daemon.json
# -------------------------------
echo "Writing Docker daemon.json with base $ADDRESS_POOL_BASE..."
mkdir -p /etc/docker
cat > "$DOCKER_CONFIG_FILE" <<EOF
{
"default-address-pools": [
{
"base": "10.${octet}.0.0/16",
"size": 24
}
]
}
EOF
echo "Docker config updated at $DOCKER_CONFIG_FILE"
# -------------------------------
# Delete and recreate network
# -------------------------------
if docker network inspect "$NETWORK_NAME" >/dev/null 2>&1; then
echo "Network '$NETWORK_NAME' exists. Deleting it..."
docker network rm "$NETWORK_NAME"
fi
echo "Creating network '$NETWORK_NAME' with subnet $NETWORK_SUBNET..."
docker network create \
--driver=bridge \
--subnet="$NETWORK_SUBNET" \
"$NETWORK_NAME"
echo "✅ Done. You may need to restart Docker to apply default address pool changes:"
echo " sudo systemctl restart docker"