-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdocker-port-forward
executable file
·55 lines (40 loc) · 1.14 KB
/
docker-port-forward
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/bash
# If it's stupid but it works, it isn't stupid.
cleanup() {
if [[ ! -z "$socatPid" ]]; then
kill "$socatPid"
wait "$socatPid"
fi
}
trap cleanup EXIT
if [[ -z "$1" ]]; then
echo "$0 container sourcePort:destinationPort [command [options...]]"
echo ""
echo "Forward port from sourcePort on localhost to destinationPort located inside a given container."
echo "Optionally a command might be provided which will be called when tunnel is open. The tunel will be closed"
echo "when command finishes"
exit 1
fi
set -e
if [[ "$1" == "--internal" ]]; then
internal="true"
shift
fi
container="$1"
ports="$2"
shift
shift
sourcePort="$(echo -n "$ports" | cut -d':' -f1)"
destinationPort="$(echo -n "$ports" | cut -d':' -f2)"
if [[ "$internal" == "true" ]]; then
docker run --rm -i --log-driver=none "--net=container:$container" alpine/socat STDIO "TCP4:localhost:$destinationPort"
else
socat TCP4-LISTEN:$sourcePort,reuseaddr,fork SYSTEM:"$0 --internal $container $destinationPort" &
socatPid="$!"
if [[ -z "$1" ]]; then
sleep infinity
else
"$@"
sleep 1 # wait for forked Docker container to finish to prevent socat error
fi
fi