As per the documentation from docker, there are certain limitation in Mac OS environment where we cannot expose ports from docker container to host machine, as it is running on a virtual machine.
If you do not want to communicate outside docker but if you want to connect to different images inside a same docker container or different docker container you can use network-mode to host.
network_mode: "host"
But what if we need to expose outside docker to the host machine where the docker is running?
As a workaround we may need to create a loopback IP address in Mac OS host machine. To do this,
- create a file in your current directory named loopback-alias.plist and place below content. Here I’ve used 10.200.10.1 as a loopback IP address. But you can modify it if you want.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist>
<plist version="1.0">
<dict>
<key>Label</key>
<string>loopback-alias</string>
<key>ProgramArguments</key>
<array>
<string>/sbin/ifconfig</string>
<string>lo0</string>
<string>alias</string>
<string>10.200.10.1</string>
<string>netmask</string>
<string>255.255.255.0</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>2. And then run below commands in order to make it available when startup
sudo cp loopback-alias.plist /Library/LaunchDaemons/loopback-alias.plist sudo launchctl load -w /Library/LaunchDaemons/loopback-alias.plist
3. In order to take this effect either you can restart your system or simply restart the network as follows
networksetup -setairportpower en0 off && networksetup -setairportpower en0 on
Changes at docker-compose.yml
redis: image: redis expose: - '6379' ports: - '10.200.10.1:6379:6379' extra_hosts: - 'localhost:10.200.10.1'
This means, we are using hosts loopback IP where we are exposing the port. And you can access it from your host machine as follows,
http://10.200.10.1:6379
Similarly we can add same configuration to any images to access it from host machine.
You may need to add the following to your bashrc/zshrc for MacOS
export DOCKER_HOST=unix:///var/run/docker.sock