Skip to content

Instantly share code, notes, and snippets.

@FredyRosero
Created August 12, 2023 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FredyRosero/a04030f5eb7e15c6ad033ca628086154 to your computer and use it in GitHub Desktop.
Save FredyRosero/a04030f5eb7e15c6ad033ca628086154 to your computer and use it in GitHub Desktop.
Give internet access to a docker container network

If you docker container has no internet connection maybe you docker network neither have it.

  1. Get virtual container bridge name:
network_name=$(docker inspect --format '{{ range $key, $value := .NetworkSettings.Networks }}{{ $key }}{{ end }}' $container)
etwork_id=$(docker network inspect -f {{.Id}} $network_name)
bridge_name="br-${network_id:0:12}"
  1. Obtain IP network address of the virtual bridge:
IP=$(ip addr show $bridge_name | grep 'inet ' | awk '{print $2}')	
  1. Masquerade all outgoing traffic from the $IP subnet:
sudo iptables -t nat -A POSTROUTING ! -o $bridge_name -s $IP -j MASQUERADE
  1. Check it:
user@host:~$ docker exec -u 0 -it $container /bin/bash 
root@772bc683889a:/var/www/html# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=12.1 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=9.50 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=118 time=4.98 ms
^C
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 4.979/8.850/12.070/2.931 m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment