docker
docker-compose
networking
host-network
tutorial

How to combine host network with the default network in docker-compose

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Docker Compose is an instrumental tool that simplifies running multiple containerized applications. It provides a way for combining containers in a network to enable communication. However, combining different network modes, such as the `host` network with the `default` (or `bridge`) network, can be quite challenging. This article will guide you through the process of merging these two network modes using Docker Compose, combining technical explanations with practical examples.

Understanding Docker Networking

Docker supports several networking modes, with `bridge` and `host` being two primary types:

  • Bridge Network: This is Docker's default mode. Containers on the same bridge network can communicate with each other, but they are isolated from other traffic by default. Containers must explicitly expose ports to connect with external services.
  • Host Network: This mode makes the container use the host's network stack. As a result, all the network configurations (e.g., IP addresses) are shared with the host. It is beneficial for scenarios requiring high network performance or when the service needs to be accessible on the host's network interfaces directly.

Combining Network Modes in Docker Compose

Docker Compose does not natively support containers on the same service to use both the `host` and `bridge` networks simultaneously. However, you can achieve a similar effect by strategically configuring multiple services to interconnect across these networks. Below is an example demonstrating how to combine a `host` network with a `bridge` network using Docker Compose.

Approach

  1. Define Services Separately: You must define separate services for Docker Compose to manage the network types. Place one container on the `host` network and another on the `bridge` network.
  2. Manual Bridging Logic: Implement custom logic or tools to facilitate communication between containers across these networks.

Here's a `docker-compose.yml` configuration utilizing both network modes:

  • default_bridge
  • `service_bridge` runs on the `bridge` network. This service remains isolated from the host's network.
  • `service_host` utilizes `network_mode: host`, directly assigning it the host’s network stack.

Course illustration
Course illustration

All Rights Reserved.