Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Add a firewall NAT rule to expose a port open in a docker container, on a host.
- #
- # This is only really useful if the container is already running, and you don't
- # want to/can't shut it down, but need a new incoming port open.
- #
- # Requires `jq` for parsing docker container information.
- #
- # 2019 @leonjza
- ACTION=$1
- CONTAINER_NAME=$2
- CONTAINER_PORT=$3
- if ! [[ "$ACTION" =~ ^(-A|-C|-D)$ ]] || [ -z "$CONTAINER_NAME" ] || [ -z "$CONTAINER_PORT" ]; then
- echo "Usage: $0 [action] [container name] [port]"
- echo " Actions can be -A (add rules); -C (check rules); -D (delete rules)"
- exit
- fi
- CONTAINER_IP=$(docker inspect nc-container | jq -r ".[0].NetworkSettings.IPAddress")
- DOCKER_INTERFACE=docker0 # not sure if this is standard, but ok
- echo "Will $ACTION rules for $CONTAINER_PORT to $CONTAINER_IP for container $CONTAINER_NAME..."
- iptables -t nat $ACTION POSTROUTING --source $CONTAINER_IP --destination $CONTAINER_IP -p tcp --dport $CONTAINER_PORT -j MASQUERADE
- iptables -t nat $ACTION DOCKER ! -i $DOCKER_INTERFACE -p tcp --dport $CONTAINER_PORT -j DNAT --to-destination $CONTAINER_IP:$CONTAINER_PORT
- iptables $ACTION DOCKER ! -i $DOCKER_INTERFACE -o $DOCKER_INTERFACE --source 0.0.0.0/0 --destination $CONTAINER_IP -p tcp --dport $CONTAINER_PORT -j ACCEPT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement