Skip to content

Instantly share code, notes, and snippets.

@gentunian
Last active February 13, 2019 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gentunian/1363b57255af3bd04a8000175948be4f to your computer and use it in GitHub Desktop.
Save gentunian/1363b57255af3bd04a8000175948be4f to your computer and use it in GitHub Desktop.
Prove that docker network order is dict based and compose order is not respected
#!/bin/bash
# autogenerate compose file avoiding file name colisions in the current directory
COMPOSE_FILE_NAME=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 10).xml
cat << EOF > ${COMPOSE_FILE_NAME}
version: "3.4"
services:
alpine:
image: alpine
command: sleep 120
networks:
- zw2
- nw0
- hw1
- nw3
networks:
nw0:
hw1:
zw2:
nw3:
EOF
# pull the image
echo "Pulling alpine image" && docker pull alpine > /dev/null
# autogenerate stack name avoiding stack name colision
STACK_NAME=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 3)
# deploy the stack
echo "Deploying stack ${STACK_NAME}" && docker stack deploy -c ${COMPOSE_FILE_NAME} ${STACK_NAME} > /dev/null
# insert a delay
WAIT_FOR_SERVICE=5
echo "Sleeping for ${WAIT_FOR_SERVICE} seconds..." && sleep ${WAIT_FOR_SERVICE}
# gather container name
CONTAINER_NAME=$(docker container ls -f name=${STACK_NAME}* --format '{{ .Names }}')
echo "=== Gathering container ${CONTAINER_NAME} network info ==="
for network in $(docker network ls -f name=${STACK_NAME}* --format '{{ .Name }}'); do
network_cidr=$(docker network inspect -f '{{ (index .IPAM.Config 0).Subnet }}' ${network})
echo "[${network}]"
echo "cidr=${network_cidr}"
docker exec -i ${CONTAINER_NAME} ip a | awk -v subnet=${network_cidr/0\//*\/} '$0 ~ subnet { printf "ip=%s\niface=%s\n", $2, $7}'
echo
order="${order}\n$(docker exec -i ${CONTAINER_NAME} ip a | awk -v subnet=${network_cidr/0\//*\/} '$0 ~ subnet { print $7}') => ${network}"
done
echo "=== Network desired mapping ==="
grep "[ ]\+networks:" -A 4 docker-compose.yml | awk -v stack="${STACK_NAME}" '/-/ { print "eth"a++, "=>", stack"_"$2 }'
echo
echo -n "=== Network actual mapping ==="
echo -e ${order}
echo
docker --version
echo
# remove the stack
echo "Removing stack ${STACK_NAME}" && docker stack rm ${STACK_NAME} > /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment