Skip to content

Instantly share code, notes, and snippets.

@maxwellimpact
Last active March 3, 2022 04:55
Show Gist options
  • Save maxwellimpact/dc688346ccca2adb0ba79e9d4652f1bc to your computer and use it in GitHub Desktop.
Save maxwellimpact/dc688346ccca2adb0ba79e9d4652f1bc to your computer and use it in GitHub Desktop.
A simple how to guide on using local domains with Docker for Mac beta

Using local development domains with Docker for Mac Beta

Caveats

This technique is only suitable for Docker for Mac Beta. This requires the use of pfctl to add ip/port forwarding and the /etc/hosts file to setup the domain, and both of which require sudo to run. This technique is required due to the fact that Docker only makes the containers accessible locally through the use of localhost and a random port. There reasoning beyond this has to do with Apple application sandboxing, but obviously is not ideal for most developers. Lastly, this will likely not work after a reboot so you will need to rerun the pfctl command. If you have several domains to worry about I'd suggest you setup a startup script in ruby or python to rerun the commands each time.

Please proceed with caution I'm not an expert on pfctl, though I don't foresee any major issues here. If anyone has a better way of doing this please share it and I'll update this document.

How To

Below are a set of steps required to forward an ip with port 80 to the standard Docker localhost ip and port. As noted below you will need swap some of the ip's and ports for what is relevant for you. Lastly, you can use multiple domains as long as you increment the ip. 127.0.0.1 is reserved as the main localhost however 2-255 are available for use, as well as others.

  • Run a pfctl command to add the ip/port forwarding.
  • echo "rdr pass proto tcp from any to 127.0.0.2 port 80 -> 127.0.0.1 port 32768" | sudo pfctl -Ef -
  • Swap 127.0.0.2 with an incrementing localhost ip. If this is your first entry use the one I already have.
  • Swap 32768 with the port of the container. This should be visible in docker ps or Kitematic.
  • If you need multiple forwards then add each one on a new line within the echo "..."
  • Add the ip and domain to /etc/hosts
  • 127.0.0.2 testdomain.dev
  • Be sure you use whatever ip from above and obviously your own domain.
  • Access your domain from the browser

Multiple Entry Example for pfctl

echo "
rdr pass proto tcp from any to 127.0.0.2 port 80 -> 127.0.0.1 port 32768
rdr pass proto tcp from any to 127.0.0.3 port 80 -> 127.0.0.1 port 32770
rdr pass proto tcp from any to 127.0.0.4 port 80 -> 127.0.0.1 port 32775
" | sudo pfctl -Ef -

Feedback

Look forward to see others ideas or feedback on this technique. I would love to refine this idea in to a script that could handle some of the automation and persist after a reboot.

Credit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment