dockerdocker-composedocker-network

why does docker compose still create an implicit network


services:
  echo:
    image: busybox
    command: echo 7

  server:
    build: .
    command: server 0.0.0.0:8000
    healthcheck:
      test: /app/compose-tinker poke localhost:8000
      interval: 1s
      retries: 10

  client:
    build: .
    command: client server:8000
    tty: true
    stdin_open: true
    depends_on: 
      server:
        condition: service_healthy

networks:
  my_network: {}

here’s my compose file. notice that the toplevel networks declares a my_network network and none of the services is connected to it

$ docker compose -f compose-7.yaml build --no-cache
$ docker compose -f compose-7.yaml up              
[+] Running 4/0
 ✔ Network compose-tinker_default     Created                                                        0.0s 
 ✔ Container compose-tinker-server-1  Created                                                        0.0s 
 ✔ Container compose-tinker-echo-1    Created                                                        0.0s 
 ✔ Container compose-tinker-client-1  Created                                                        0.0s 
$ docker compose -f compose-7.yaml down
[+] Running 4/0
 ✔ Container compose-tinker-client-1  Removed                                                        0.0s 
 ✔ Container compose-tinker-echo-1    Removed                                                        0.0s 
 ✔ Container compose-tinker-server-1  Removed                                                        0.0s 
 ✔ Network compose-tinker_default     Removed

yet docker compose still creates a compose-tinker_default network and puts all services on it; they communicate with each other just fine. what gives? i was expecting all containers to be isolated. but docker creates an implicit default network even though i’ve explicitly defined a custom network and puts all services on it. is this supposed to happen and how do i isolate all containers?


Solution

  • This is supposed to happen. the default docker network is an implicit definition and defining another network does not change or alter the default network in any way. The services that do not declare explicit networks continue to use their implicit network configurations.

    To prevent the implicit network attachments use network_mode

    services:
      hello:
        image: nginx
        network_mode: bridge