You have often several docker containers and applications which work together on local development. You need the following communications:
- docker container to localhost
- localhost to docker container
- docker container to docker container
You have a way to connect localhost-to-docker using -p
(port-mapping) docker option.
For instance, you can start PostgreSQL container using -p 0.0.0.0:5432:5432
and then connect like to normal PostgreSQL
You have a way to connect docker-to-localhost using --net=host
docker option.
For instance, you can start Nginx container with this option and nginx would be able to connect with your localhost daemons.
You have a way to connect docker-to-docker using links or docker-compose.
So we have one problem and three solutions. It’s not inspiring, right?
You do not have a way to connect localhost-to-docker and docker-to-localhost at the same time. Frankly speaking, you have this way only for linux.
Docker restricts simultaneous usage of this -p
and --net=host
on OSX.
If you start container with -p
you’re able to connect from localhost to container, but not from container to localhost.
If you start container with --net=host
you’re able to connect from docker container to localhost, but not from localhost to container.
One of the possible solution: use -p
option always and use docker auto-assigned IP-address for connect from local to docker container, but note the Problem #2.
Docker generates IP-address unstably. You will receive a new IP address on every container run. Moreover, the range of addresses is different under Linux and OSX.
One of the possible solutions: to inspect docker container ip-address via docker info
after container start.
The problem is that you have to use this information in your scripts, in contrast to 127.0.0.1 address, which you use it without Docker.
You do not have stable and simple solution to communicate between localhost and docker containers which works identically both under Linux and OSX.
Loopback alias ip-address the simplest way to make OSX and Linux localhost and docker containers communications identical on both platforms.
- Follow the manual for Linux and OSX to create alias to loopback device. I use ip-address 10.200.10.1 for that.
- Always run docker containers with
-p
option (of course, if docker container listens some port) - Use ip address 10.200.10.1 everywhere - in your localhost processes, inside docker containers
As a result, every docker container and localhost process would go to the single communication point. And yes, on OSX and Linux, without difference!
sudo cp loopback-alias.service /etc/systemd/system/loopback-alias.service
sudo systemctl daemon-reload
sudo systemctl enable loopback-alias
sudo systemctl start loopback-alias
sudo cp loopback-alias.plist /Library/LaunchDaemons/loopback-alias.plist
sudo launchctl load -w /Library/LaunchDaemons/loopback-alias.plist