Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Add a firewall NAT rule to expose a port open in a docker container, on a host.
  4. #
  5. # This is only really useful if the container is already running, and you don't
  6. # want to/can't shut it down, but need a new incoming port open.
  7. #
  8. # Requires `jq` for parsing docker container information.
  9. #
  10. # 2019 @leonjza
  11.  
  12. ACTION=$1
  13. CONTAINER_NAME=$2
  14. CONTAINER_PORT=$3
  15.  
  16. if ! [[ "$ACTION" =~ ^(-A|-C|-D)$ ]] || [ -z "$CONTAINER_NAME" ] || [ -z "$CONTAINER_PORT" ]; then
  17. echo "Usage: $0 [action] [container name] [port]"
  18. echo " Actions can be -A (add rules); -C (check rules); -D (delete rules)"
  19. exit
  20. fi
  21.  
  22. CONTAINER_IP=$(docker inspect nc-container | jq -r ".[0].NetworkSettings.IPAddress")
  23. DOCKER_INTERFACE=docker0 # not sure if this is standard, but ok
  24.  
  25. echo "Will $ACTION rules for $CONTAINER_PORT to $CONTAINER_IP for container $CONTAINER_NAME..."
  26.  
  27. iptables -t nat $ACTION POSTROUTING --source $CONTAINER_IP --destination $CONTAINER_IP -p tcp --dport $CONTAINER_PORT -j MASQUERADE
  28. iptables -t nat $ACTION DOCKER ! -i $DOCKER_INTERFACE -p tcp --dport $CONTAINER_PORT -j DNAT --to-destination $CONTAINER_IP:$CONTAINER_PORT
  29. 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