Nixwill
Nixwill

Reputation: 491

Connect to docker-compose network using docker run

Let say I have running orchestration with docker-compose with docker-compose.yml looking like this:

version: '2.2'

services:

  service1:
    # ...
    networks:
      - compose_network

  service2:
    # ...
    networks:
      - compose_network

networks:
  compose_network:

I aim to run and connect temporarily one container to compose_network_1. I tried using

$ docker run --net=compose_network <image for the job>

but I could not connect. I am also aware that docker-compose names the networks as [projectname]_default, so I also tried that variant, but with same result.

Is there a way I can accomplish that?

Upvotes: 33

Views: 17554

Answers (3)

SHAHBAZ AHMAD
SHAHBAZ AHMAD

Reputation: 1

version: '3.8'
services:
  service1:
    networks:
      - virtual-network

  service2:
    networks:
      - virtual-network

  service3:
    networks:
      - virtual-network
networks:
  virtual-network: 

use this command

docker-compose up -d

Upvotes: -1

scipilot
scipilot

Reputation: 7447

I'm not sure if the --net option ever existed but it's now --network.

From docker run --help:

      --network string   Connect a container to a network (default "default")

As @maxm notes you can find the network name, with the DIR prefix of the compose project directory, then simply run it as you were trying:

$ docker run --network=DIR_compose_network <image for the job>

I wanted to connect on run as my container is transient (running tests) so I can't use a second docker network command in time before it quits.

e.g. for my docker composition in a "dev" folder with no network name specified so uses the docker-compose "default" name, therefore I get the name dev_default.

docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
2c660d9ed0ba        bridge              bridge              local
b81db348e773        dev_default         bridge              local
ecb0eb6e93a5        host                host                local

docker run -it --network dev_default myimage

This connects the new docker container to the existing docker-compose network.

Upvotes: 28

maxm
maxm

Reputation: 3667

The network name is going to be something like name-of-directory_compose_network. Find the name with docker network ls

I had success with:

docker-compose up # within directory ./demo
docker run -itd -p "8000:8000" --hostname=hello "crccheck/hello-world"
# outputs: 1e502f65070c9e2da7615c5175d5fc00c49ebdcb18962ea83a0b24ee0440da2b
docker network connect --alias hello demo_compose_network 1e502f65070c

I could then curl hello:8000 from inside my docker compose containers. Should be the exact same functionality as your commands, just with an added alias.

Upvotes: 7

Related Questions