Skip to content

Instantly share code, notes, and snippets.

@th3gundy
Forked from Shawyeok/expose.sh
Created September 20, 2022 14:33
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 th3gundy/0b593c57d9f375b39101eff8daf71dd0 to your computer and use it in GitHub Desktop.
Save th3gundy/0b593c57d9f375b39101eff8daf71dd0 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