-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun_docker.sh
More file actions
85 lines (73 loc) · 2.17 KB
/
run_docker.sh
File metadata and controls
85 lines (73 loc) · 2.17 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/bash
# running target
DOCKER_IMAGE=$1
DOCKER_NAME=$2
# available port range
P1=10000
P2=20000
# target port: we will use port range [TP, TP+N-1]
# if target_port == -1, the target port will be the same as source port
TP=-1
# number of ports to use
N=20
# port availablity
is_ports_available() {
# Check if all n consecutive ports are available
for (( i=0; i<$N; i++ )); do
PORT=$(( $1 + i ))
nc -z localhost $PORT
if [ $? -eq 0 ]; then
# Port is in use, return failure
return 1
fi
done
# All ports are available
return 0
}
# Find a consecutive range of N available ports within the range [P1, P2]
available_ports=()
for (( port=$P1; port<=$P2; port++ )); do
# Check if the next N consecutive ports are available
if is_ports_available $port; then
available_ports=()
for (( i=0; i<$N; i++ )); do
available_ports+=($(( $port + i )))
done
break
fi
done
# Check if we found N available ports
if [ ${#available_ports[@]} -lt $N ]; then
echo "Not enough available ports in the range [$P1, $P2]"
exit 1
fi
# Select the first available range of N consecutive ports
START_HOST_PORT=${available_ports[0]} # The first available port
END_HOST_PORT=$((START_HOST_PORT + N - 1)) # Last available port
# Define the container port range starting from target port
# if TP < 0, use same port as host (source port)
if [ $TP -lt 0 ]; then
START_CONTAINER_PORT=$START_HOST_PORT
END_CONTAINER_PORT=$END_HOST_PORT
else
START_CONTAINER_PORT=$TP
END_CONTAINER_PORT=$((TP + N - 1))
fi
# Construct the docker run -p option with port ranges
HOST_PORT_RANGE="${START_HOST_PORT}-${END_HOST_PORT}"
CONTAINER_PORT_RANGE="${START_CONTAINER_PORT}-${END_CONTAINER_PORT}"
# Run the docker container with dynamic port ranges
echo "Running container with the following port mappings:"
echo "docker run -p $HOST_PORT_RANGE:$CONTAINER_PORT_RANGE ..."
echo "Docker Image: $DOCKER_IMAGE"
echo "Docker Name: $DOCKER_NAME"
docker run \
-it \
--gpus all \
--ipc=host \
--name=$DOCKER_NAME \
--privileged \
-v=/data1:/data1 \
-w=$HOME \
-p $HOST_PORT_RANGE:$CONTAINER_PORT_RANGE \
$DOCKER_IMAGE bash