Reputation: 6781
Running 2 containers where mycontainer2
must use the same network stack of mycontainer1
. As if the two containers were running in the same machine. Here how I try to do by using docker run
with --network container:xxx
$ docker run -it --rm --name mycontainer1 -p 6666:7777 myregistry/my-container1:latest
$ docker run -it --rm --network container:mycontainer1 --name mycontainer2 myregistry/my-container2:latest
I tried to replicate this behavior using docker-compose
instead. But the networks: definition of docker-compose.yaml
doesn't indicate something equivalent to the --network container:xxx
option of docker run
. Is it possible in docker-compose
to configure two containers to use the same network stack?
Upvotes: 4
Views: 8251
Reputation: 158706
This is a network_mode:
setting.
version: '3.8'
services:
mycontainer1:
image: myregistry/my-container1:latest
ports: ['6666:7777']
mycontainer2:
image: myregistry/my-container2:latest
network_mode: service:mycontainer1 # <---
Since Compose will generally pick its own container names, this service:name
form uses the container matching the named Compose service. (If you override container_name:
then you can also use container:mycontainer1
the same way you did with docker run
.)
Upvotes: 11
Reputation: 395
Creating an external network and use it inside docker-compose YAML manifest might help. Here is how you do it.
version: '3.7'
networks:
default:
external:
name: an-external-network
services:
my-container1:
...
my-container2:
...
Note: use
docker network create
command to createan-external-network
before runningdocker-compose up
command.
Upvotes: 0