Change default route in docker container

前端 未结 3 1349
旧巷少年郎
旧巷少年郎 2020-12-24 02:36

I have a docker container that is connected to two networks, the default bridge and a custom bridge. Via the default, it is linked to another container only in the default n

3条回答
  •  遥遥无期
    2020-12-24 02:50

    @Silicium14

    Thanks a lot for your 2nd solution. Took me quite long to find a way to set routes upon container start. I changed your lines a bit according to my needs as I need to provide a container name from docker events to the script

    First I start the listener for my events.

    docker events --filter 'container=box1' --filter 'container=box2' --filter 'event=start' --filter 'event=stop' --format '{{.Actor.Attributes.name}}'|awk '{ system("/work/route_setting.sh " $1) }'
    

    I use more filters as I need the events for two containers of type start or stop Using --format one can control the output very nicely. So only the container name is piped to awk. Which then fires my routing script with the correct containername.

    #!/bin/bash
    
    # exit if no container name provided as $1
    [ "x$1" = 'x' ] && exit 1
    # holds pid of the docker container
    pid=''
    # read the pid for container
    pid=$(docker inspect -f '{{.State.Pid}}' "${1}" 2>/dev/null)
    # if for whatevery reason we get pid 0 avoid setting routes
    [ "x$pid" = 'x0' ] && pid=''
    if [ "x$pid" != 'x' ] ; then
      # let the routing happen 
      mkdir -p /var/run/netns
      ln -s /proc/$pid/ns/net /var/run/netns/$pid
      ip netns exec $pid ip route add 10.0.0.0/8 via 10.66.101.1
      ip netns exec $pid ip route add 192.168.0.0/16 via 10.66.101.1
    fi
    # clean up broken symlinks which occur when a container is stopped
    # verify that your find supports -xtype l
    find /var/run/netns -xtype l -exec rm -f '{}' \;
    

提交回复
热议问题