Fibonacci with an interconnected network of Docker containers

On monday, I posted a tutorial on how to compute fibonacci numbers with a recursive algorithm that spawns Docker containers inside docker containers.

But can we do rather spawn a network of interconnected docked?

Yes. Here’s the project to do that: Fiboweb

this version of Fibonacci uses Docker to spawn web servers that communicate one with the others.

Each web server knows the value of the Nth Fibonacci number.
To know this value, it has to connect to the web server that knows N-2 and the web server that knows N-1.

Our script startNetwork.sh takes N as a parameter and spawns N docker daemons. Each docker container
except #0 and #1 is linked to two other docker containers so that it can query them on their port 8000 with wget.

The last docker container maps its 8000 port to the host so that it can be queried.

Here’s the docker file:

FROM google/debian:wheezy
MAINTAINER David Gageot david@gageot.net

ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -qq
RUN apt-get install -yqq python wget

EXPOSE 8000
ENTRYPOINT ["./fiboweb.sh"]
ADD fiboweb.sh /

The script that is run from every container:

(My markdown plugins insists on escaping >. Please unescape in your head…)

#!/bin/bash

if [ $1 -le 0 ]; then
    echo "0" > index.html
    python -m SimpleHTTPServer
    exit 1
fi

if [ $1 -le 1 ]; then
    echo "1" > index.html
    python -m SimpleHTTPServer
    exit 1
fi

N2=$(wget -q -O - --retry-connrefused http://fibo$[$1-2]:8000/)
N1=$(wget -q -O - --retry-connrefused http://fibo$[$1-1]:8000/)
echo "$[$N1+$N2]" > index.html
python -m SimpleHTTPServer

The startup script:

#!/bin/bash

N=$1

./cleanup.sh ${N}

for i in $(seq 0 ${N}); do
    LINK=""
    PORT=""

    if [ ${i} -ge 2 ]; then
        LINK="--link fibo$[$i-2]:fibo$[$i-2] --link fibo$[$i-1]:fibo$[$i-1]"
    fi
    if [ ${i} -ge ${N} ]; then
        PORT="-p 8000:8000"
    fi

    docker run --name fibo${i} ${LINK} ${PORT} -d dgageot/fiboweb ${i}
done

Have fun