Docker: a quick tip to expose RTC ports fast / speed-up docker start/restart process

Mediasoup requires lots of ports. This is normal. However, it takes a long time to expose them via docker. Docker is creating docker-proxy for each port with iptables rules. If you’re using only 5000 ports, with TCP + UDP it requires a lot of bridges running. Combined two protocols, it will be over 10k.

That is using a lot of resources, a restart of the docker container is very slow, etc… there are faster ways to do it.

There are a couple of ways:

  1. (quickest and easy) run your docker with --net=‘host’, that way all of the ports will be exposed on your machine directly
  2. (harder way) If you don’t want to attach to the host directly, then all we need is to have a couple of iptables rules in place.

Here is the script you will need to add to your docker run script:

CIP='172.18.0.18'
PORTBEGIN='50000'
PORTEND='55000'
BRIDGEID='docker0'

iptables -D DOCKER -t nat -p udp -m udp ! -i $BRIDGEID --dport $PORTBEGIN:$PORTEND -j DNAT --to-destination $CIP:$PORTBEGIN-$PORTEND
iptables -D DOCKER -t nat -p tcp -m tcp ! -i $BRIDGEID --dport $PORTBEGIN:$PORTEND -j DNAT --to-destination $CIP:$PORTBEGIN-$PORTEND
iptables -D DOCKER -p udp -m udp -d $CIP/32 ! -i $BRIDGEID -o $BRIDGEID --dport $PORTBEGIN:$PORTEND -j ACCEPT
iptables -D DOCKER -p tcp -m tcp -d $CIP/32 ! -i $BRIDGEID -o $BRIDGEID --dport $PORTBEGIN:$PORTEND -j ACCEPT
iptables -D POSTROUTING -t nat -p udp -m udp -s $CIP/32 -d $CIP/32 --dport $PORTBEGIN:$PORTEND -j MASQUERADE
iptables -D POSTROUTING -t nat -p tcp -m tcp -s $CIP/32 -d $CIP/32 --dport $PORTBEGIN:$PORTEND -j MASQUERADE

iptables -A DOCKER -t nat -p udp -m udp ! -i $BRIDGEID --dport $PORTBEGIN:$PORTEND -j DNAT --to-destination $CIP:$PORTBEGIN-$PORTEND
iptables -A DOCKER -t nat -p tcp -m tcp ! -i $BRIDGEID --dport $PORTBEGIN:$PORTEND -j DNAT --to-destination $CIP:$PORTBEGIN-$PORTEND
iptables -A DOCKER -p udp -m udp -d $CIP/32 ! -i $BRIDGEID -o $BRIDGEID --dport $PORTBEGIN:$PORTEND -j ACCEPT
iptables -A DOCKER -p tcp -m tcp -d $CIP/32 ! -i $BRIDGEID -o $BRIDGEID --dport $PORTBEGIN:$PORTEND -j ACCEPT
iptables -A POSTROUTING -t nat -p udp -m udp -s $CIP/32 -d $CIP/32 --dport $PORTBEGIN:$PORTEND -j MASQUERADE
iptables -A POSTROUTING -t nat -p tcp -m tcp -s $CIP/32 -d $CIP/32 --dport $PORTBEGIN:$PORTEND -j MASQUERADE

Where:
CIP: internal docker IP of the docker that runs mediasoup
PORTBEGIN: rtcMinPort from the config
PORTEND: rtcMaxPort from the config
BRIDGEID: this is where your docker subnet runs, by default it will be docker0. If you run your docker container with --net somename, then it will be a different name. For example: br-f362166a51b9, etc. To verify this, just run:

ip r l

on the Linux box. It will print all of the subnets. Find one that your CIP belongs to and type it there.

Hope that helps someone.

6 Likes