underw0rld
Members
-
Joined
-
Last visited
Solutions
-
underw0rld's post in wireguard on a container, but with local docker network access was marked as the answerFor anyone who also wants to achieve this, I found a solution that is much easier (imo).
Create a wireguard connection to your vpn, using "VPN Tunneled Access for Docker"
Assign any of your desired containers to this wireguard network
Create a "shared network" that can bridge your normal docker network with your wg network, but does NOT route to WAN (--internal flag):
docker network create --internal [shared-network-name]
Join your VPN'd containers, as well as any you want to be able to access them, to this "shared network" (a container can join multiple docker networks!):
docker network connect [shared-network-name] [container-name]
that is all you need to do! Now any of your regular docker network containers can communicate with your containers that are on the wireguard network
you can create a user script to always join a list of containers to your shared network:
#!/bin/bash
# Define the target network
TARGET_NETWORK="shared-network"
# Define the list of container names to monitor
CONTAINERS=(
"container-name"
"container2-name"
)
# Function to check and connect container
connect_if_needed() {
local CONTAINER=$1
# Check if container exists
if ! docker inspect "$CONTAINER" &>/dev/null; then
echo "$(date): Container '$CONTAINER' does not exist, skipping..."
return
fi
# Get the networks the container is connected to
NETWORKS=$(docker inspect "$CONTAINER" -f '{{range $key, $value := .NetworkSettings.Networks}}{{$key}} {{end}}')
# Check if container is already connected to the target network
if echo "$NETWORKS" | grep -q "$TARGET_NETWORK"; then
echo "$(date): Container '$CONTAINER' already connected to '$TARGET_NETWORK'"
else
echo "$(date): Connecting '$CONTAINER' to '$TARGET_NETWORK'..."
docker network connect "$TARGET_NETWORK" "$CONTAINER"
if [ $? -eq 0 ]; then
echo "$(date): Successfully connected '$CONTAINER' to '$TARGET_NETWORK'"
else
echo "$(date): Failed to connect '$CONTAINER' to '$TARGET_NETWORK'"
fi
fi
}
# Check if target network exists
if ! docker network inspect "$TARGET_NETWORK" &>/dev/null; then
echo "Error: Network '$TARGET_NETWORK' does not exist"
exit 1
fi
echo "$(date): Starting Docker event monitor for container updates..."
# Monitor docker events for container creates AND starts
docker events --filter 'type=container' --filter 'event=create' --filter 'event=start' --format '{{.Actor.Attributes.name}}' | while read CONTAINER_NAME
do
# Check if this container is in our list
for TARGET_CONTAINER in "${CONTAINERS[@]}"; do
if [ "$CONTAINER_NAME" = "$TARGET_CONTAINER" ]; then
echo "$(date): Detected event for '$CONTAINER_NAME'"
# Small delay to ensure container is fully ready
sleep 2
connect_if_needed "$CONTAINER_NAME"
break
fi
done
done