Search code examples
dockerdocker-composecompatibility

Docker Compose network_mode and port_binding compatibility issue


My docker-compose.yml contains this:

version: '3.2'
services:
  mysql:
    image: mysql:latest
    container_name: mysql
    restart: always
    network_mode: "host"
    hostname: localhost
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
    volumes:
      - $HOME/data/datasql:/var/lib/mysql
    ports:
      - 3306:3306

  user-management-service:
    build: user-management-service/
    container_name: user-management-service
    restart: always
    depends_on:
      - mysql
      - rabbitmq
      - eureka
    network_mode: "host"
    hostname: localhost
    ports:
      - 8089:8089

When I try to do docker-compose up, I get the following error:

"host" network_mode is incompatible with port_bindings

Can anyone help me with the solution?


Solution

  • network_mode: host is almost never necessary. For straightforward servers, like the MySQL server you show or what looks like a normal HTTP application, it's enough to use normal (bridged) Docker networking and ports:, like you show.

    If you do set up host networking, it completely disables Docker's networking stack. You can't call to other containers using their host name, and you can't remap a container's port using ports: (or choose to not publish it at all).

    You should delete the network_mode: lines you show in your docker-compose.yml file. The container_name: and hostname: lines are also unnecessary, and you can delete those too (specific exception: RabbitMQ needs a fixed hostname:).

    I feel like the two places I see host networking are endorsed are either to call back to the host machine (see From inside of a Docker container, how do I connect to the localhost of the machine?), or because the application code has hard-coded localhost as the host name of the database or other components (in which case Docker and a non-Docker development setup fundamentally act differently, and you should configure these locations using environment variable or another mechanism).