'Network mode container in docker-compose

With plain docker I can use network mode container like this:

docker run -d --name container-b --network container:container-a <image>

Can this be achieved using docker-compose?

services:
  service-b:
    container_name: container-b
    network_mode: "container:container-a"

Leads to:

ERROR: Please provide 'network_mode: "bridge"' or 'network_mode: "host"' in your docker-compose.yaml


Solution 1:[1]

From https://docs.docker.com/compose/compose-file/compose-file-v3/#network_mode

Note

This option is ignored when deploying a stack in swarm mode.

network_mode: "host" cannot be mixed with links.

It won't work if your docker-compose "wrapper" uses docker stack deploy under the hood.

You would have to use something like this:

docker network create some-other-network -d bridge --attachable --scope swarm

... where some-other-network is bound to the target container.

And then:

version: "3.9"

services:
  my-service:
    image: ...
    networks:
      - some-other-network
    
...

networks:
  some-other-network:
    external: true

Solution 2:[2]

I have a docker-compose file with version '2.1', but I am able to do this:

services:
  service-b:
    container_name: container-b
    network_mode: service:container-a

This makes all of my container-b traffic flow through container-a

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 act28
Solution 2 Brian Kustra