title: How can I redirect a single port in a docker container to the container's host?
body: <p>To make development easier for a project, I've put a couple of services it depends on in docker containers.  This makes 'localhost' in the project's config mean something different when it is passed to one of the containers.</p>
  
  <p><em>edit</em></p>
  
  <p>To be clear, I'm trying to forward one of the <strong>container's</strong> ports <strong>to the host</strong> so when a process running in the container tries to access localhost:5432, it connects to the <strong>host's</strong> port 5432.</p>
  
  <p><em>endedit</em></p>
  
  <p>I'm currently using</p>
  
  <pre><code>HOST_IP=`ip route | grep default | awk '{ printf "%s",$3 }'`
  cat /etc/hosts | sed "s/127.0.0.1/$HOST_IP/" &gt; /tmp/etc_hosts
  cp /tmp/etc_hosts /etc/hosts
  </code></pre>
  
  <p>to redirect anything targeting 'localhost' to the container's host.  It works in this situation, but I'd prefer to find a way to do this only for the needed port as I expect it won't work in other situations.</p>
  
  <p>Here's what I came up with to do that, but it's not working; when a connection in the container is to localhost:5432, it tries to connect to the container's 5432 instead of the host's:</p>
  
  <pre><code># --- These are the things that should make redirecting port 5432 to the host machine
  #     work, provided the container is run in privileged mode.
  sysctl -w net.ipv4.ip_forward=1
  sysctl -w net.ipv4.conf.all.route_localnet=1
  iptables -t nat -A PREROUTING -p tcp --dport 5432 -j DNAT --to 172.19.0.1:5432
  iptables -A FORWARD -d 172.19.0.1 -p tcp --dport 5432 -j ACCEPT
  iptables -t nat -A POSTROUTING -j MASQUERADE
  </code></pre>