Skip to content

Instantly share code, notes, and snippets.

@jpralves
Created May 18, 2020 21:59
Show Gist options
  • Save jpralves/841efb02bd0f768a7ba45de3a19bfbdb to your computer and use it in GitHub Desktop.
Save jpralves/841efb02bd0f768a7ba45de3a19bfbdb to your computer and use it in GitHub Desktop.
DockerTWINs - Self Replicating docker containers
version: '2.0'
services:
twin:
build:
context: .
volumes:
- /var/run/docker.sock:/var/run/docker.sock
image: twin:latest
command: ["10"]
FROM alpine:3.11.6
MAINTAINER [email protected]
### Build with:
# docker build . --tag twin:latest
### Run with:
# docker run -ti -v /var/run/docker.sock:/var/run/docker.sock twin:latest [number of twin copies]
# Get docker static executable:
ARG DOCKER_VERSION=19.03.8
RUN wget https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz -O - \
| tar xzf - --strip-components 1 -C /tmp docker/docker && \
mv /tmp/docker /bin/
# Copy Scripts:
COPY *.sh /
# Make Scripts executable:
RUN chmod 755 /*.sh
# Define EntryPoint:
ENTRYPOINT ["/entrypoint.sh"]

Docker TWINs

This is a simple example on how to use docker along docker.

In this particular example the image self-replicates itself running multiple images.

To build:

docker build . --tag twin:latest

To run:

docker run -ti -v /var/run/docker.sock:/var/run/docker.sock twin:latest [number of twin copies]

Example:

$ docker run -ti -v /var/run/docker.sock:/var/run/docker.sock twin:latest 5
Twin docker container running with id=41bdabc1db11af51150c347a1e64e5789257cb826e8c5508d4a152521573e0f7 (Iteration=1)
Twin docker container running with id=ee0aa9c45d36df4f076c79ba69bfe2e685279a5e2cbac2118fd6c3896d35fd88 (Iteration=2)
Twin docker container running with id=bfb390da9aa64c73ef738ae6a99edfe6cdea219fc3ea3e358a16d8e581d0a3ba (Iteration=3)
Twin docker container running with id=5da0748c7f03348800196b4a8b8a329924ee34429b0b77df0b475c43134316d0 (Iteration=4)
Twin docker container running with id=03f45e1d597a11d2a895762519596328973b7128fb243f4b185f59532928ab57 (Iteration=5)

The scripts are self-explanatory.

#!/bin/sh
IT=${1:-1}
# Obtain Instance ID:
INSTANCE_ID=$(cut -c9- </proc/1/cpuset)
if [ -e /var/run/docker.sock ] ; then
# Get Image ID:
IMAGE_ID=$(docker inspect --format='{{.Config.Image}}' "${INSTANCE_ID}")
[ "${IT}" -le 1 ] || docker run -it -v /var/run/docker.sock:/var/run/docker.sock "${IMAGE_ID}" $(( IT - 1 ))
fi
echo "Twin docker container running with id=${INSTANCE_ID} (Iteration=${IT})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment