Search code examples
dockerdocker-containerdocker-networkdocker-run

Docker alternative to --network host on macOS and Windows


I have two docker containers:

  • database
  • app that consumes the database

I run my database container like this:

docker run --name my-db -p 127.0.0.1:3306:3306 my-db-image

And my app container like this:

docker run --name my-app --network host -it my-app-image

This works fine on Linux. I can access the DB from both the host system and the app container. Perfect.

However --network host does not work on Mac and Windows:

The host networking driver only works on Linux hosts, and is not supported on Docker for Mac, Docker for Windows, or Docker EE for Windows Server.

(source: https://docs.docker.com/network/host/)

I can still access the database via 127.0.0.1:3306 from the main host, but I cannot access it from the app container.

How can I solve this issue? How can I let the app container connect to the database (and keep accessing also to the DB from the main host using 127.0.0.1:3306)?

I've tried using host.docker.internal and gateway.docker.internal but it doesn't work.

I've also tried to launch both containers using --network my-network after creating my-network with docker network create my-network but it doesn't work.

I can't figure out how to solve this issue.


Solution

  • For multiple services, it can often be easier to create a docker-compose.yml file that will launch all the services and any networks needed to connect them.

    version: '3'
    services:
      my-db:
        image: my-db-image
        ports:
          - "3306:3306"
        networks:
          - mynetwork
    
      my-app:
        image: my-app-image
        ports:
          - "8000:80"
        networks:
          - mynetwork
    
    networks:
      mynetwork:
    

    From the project folder, you run docker-compose up or docker-compose up -d to make the services run in the background.

    In this scenario, the magic of Docker provisions a network with hostname "mynetwork". It should expose default ports to other services on that network. If you want to remap the ports, the pattern is target:source.

    I don't know that you need the 'ports' config here. But I'm trying to map your config to the compose file. Also I'm assuming you need to expose the app on some port; using 8000 as it's pretty common setup.

    What are the parameters here? Docker-compose reference