Skip to content

Instantly share code, notes, and snippets.

@Shawyeok
Created March 22, 2017 16:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Shawyeok/690d79ca87656b3dbb4c9e0d0fd3c88a to your computer and use it in GitHub Desktop.
Save Shawyeok/690d79ca87656b3dbb4c9e0d0fd3c88a to your computer and use it in GitHub Desktop.
Expose docker container port to specific IP addresses only
# For example, I have a redis container, I want it only serve for specific IP addresses: 172.31.101.37, 172.31.101.38
$ docker run -d -p 6379:6379 redis:2.8
# After start redis container, the iptables looks like this:
$ iptables -t filter -nL
Chain DOCKER (1 references)
target prot opt source destination
ACCEPT tcp -- 0.0.0.0/0 172.17.0.2 tcp dpt:6379
# Get the IP address of redis container
$ docker inspect --format='{{.NetworkSettings.Networks.IPAddress}}' redis
172.17.0.2
# Create custom chain:
$ iptables -N CUSTOM_REDIS
$ iptables -A CUSTOM_REDIS -p tcp --dport 6379 --source 172.31.101.37 --destination 172.17.0.2 -j ACCEPT
$ iptables -A CUSTOM_REDIS -p tcp --dport 6379 --source 172.31.101.38 --destination 172.17.0.2 -j ACCEPT
$ iptables -A CUSTOM_REDIS -p tcp --dport 6379 --source 0.0.0.0/0 --destination 172.17.0.2 -j DROP
# Replace the original rule with custom chain:
$ iptables -R DOCKER 1 -p tcp --source 0.0.0.0/0 --destination 172.17.0.2 --dport 6379 -j CUSTOM_REDIS
# Now my redis can only access by IP addresses: 172.31.101.37 and 172.31.101.38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment