Created
March 22, 2017 16:54
-
-
Save Shawyeok/690d79ca87656b3dbb4c9e0d0fd3c88a to your computer and use it in GitHub Desktop.
Expose docker container port to specific IP addresses only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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