1

I noticed if you try to attach a container to two networks, the following syntax does not cause an error, but effectively attach the container only on the network specified by the last --network:

sudo docker run \
        --network front-end \
        --network back-end \
        --name app1 ${IMAGE}

sudo docker network inspect front-end | jq '.[].Containers[].Name'
# <-- nothing here
sudo docker network inspect back-end | jq '.[].Containers[].Name'
"app1"

How to attach two (or more) networks to a container so they are available when the container starts?

1

Do that:

You cannot attach several networks using the --network option. You have to rely on the docker network connect command. So if you want the multiple network interfaces to be available at container startup, you have to do it in three steps:

  1. create the container,
  2. connect the extra network needed,
  3. and finally run the container.
# create a container, attaching it to one user-defined bridge:
docker create --name app3 \
              --network back-end \
              ${IMAGE}

# connect the other bridge networks:
docker network connect front-end app3

# start the container
docker start app3
docker exec -it app3 ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
465: eth1@if466: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:13:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.19.0.3/16 brd 172.19.255.255 scope global eth1
       valid_lft forever preferred_lft forever
467: eth0@if468: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:14:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.20.0.3/16 brd 172.20.255.255 scope global eth0
       valid_lft forever preferred_lft forever


Dont' do that:

It is tempting to do that instead:

# You probably DON'T want this:
# create a container with the default network settings
docker create --name app3 \
              ${IMAGE}

# connect the user-defined bridge networks:
docker network connect back-end app3
docker network connect front-end app3

# start the container
docker start app3

However, there is a pitfall here: when creating the container without an explicit --network option, Docker attaches it to the default bridge. Then the two network connect commands will add two more networks. And the container end-up bein attached to the front_end and back_end networks as expected. But also to the default bridge, something you probably don't want when using user-defined networks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.