Can I start a new Docker container, from the command line, in the same network of an already running container?
The original container was not run with a defined network (no --network
parameter).
Here is an example of what I would like to happen:
# Start a 1st container named host1.
$ docker run --name host1 -dit alpine ash
…
# Start a 2nd container and open a shell.
$ docker run -it --rm alpine
# Try to ping the 1st container from inside the 2nd container.
/ ~ ping host1
ping: bad address 'host1'
How could the second command be changed so that the second container sees host1
?
3
Answers
Yes. if you don’t specify a network the default network is used. So starting a new container without specifying a network will put it on the default.
Yes. Actually, in your example, you’re probably already doing just that: you created both containers in the default
bridge
network – even though you didn’t specify--network
, Docker created them in this default network.You can’t use
host1
hostname to reach your first container from your second container because DNS resolution in the defaultbridge
network won’t resolve container’s hostname in this default network. (it would work in a non-default network specified with--network
because DNS resolution is different)However you can reach it directly via it’s IP, for example:
It looks like that what you really want is to contact container by their hostname in default
bridge
network. Your question may be reformulated asCan I start a container in the default
bridge
network and resolve its hostname from another container in the same network?You can specify
host1
IP with--add-host
such as:Which will pass
host1
s IP as available hostname to new containerThat being said, you’ll probably be better of using a custom network, for example:
It is possible. You have to add host resolution to
/etc/hosts
in each container: