Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save x-yuri/21f2553004e7124cff1df59fc6cba878 to your computer and use it in GitHub Desktop.

Connect 2 docker containers using SSH (ssh-keyscan)

docker-compose.yml:

services:
  a:
    build: .
    command: ./e.sh b
    init: true
  b:
    build: .
    command: ./e.sh a
    init: true

Dockerfile:

FROM alpine:3.15
RUN apk add --no-cache openssh wait4ports pwgen \
    && echo "root:`pwgen -1`" | chpasswd \
    && ssh-keygen -A
COPY id_rsa .
COPY id_rsa.pub .
RUN mkdir ~/.ssh \
    && cp /id_rsa ~/.ssh \
    && cp /id_rsa.pub ~/.ssh/authorized_keys \
    && chown -R root: ~/.ssh \
    && chmod 0700 ~/.ssh \
    && chmod 0600 ~/.ssh/*
COPY e.sh .

e.sh:

#!/bin/sh -eux
# /usr/sbin/sshd -d
/usr/sbin/sshd

wait4ports tcp://"$1":22
if ! ssh-keygen -F "$1"; then
    ssh-keyscan "$1" > ~/.ssh/known_hosts
fi

exec sleep infinity

gen-key.sh:

#!/bin/sh -eu
if [ -e id_rsa ] \
|| [ -e id_rsa.pub ]; then
    t=`date +%Y%m%d-%H%M%S`
    mkdir .bak-$t
    if [ -e id_rsa ]; then
        mv id_rsa .bak-$t
    fi
    if [ -e id_rsa.pub ]; then
        mv id_rsa.pub .bak-$t
    fi
fi
docker run --rm alpine:3.15 sh -euc '
    (apk add openssh
    ssh-keygen -A
    yes "" | ssh-keygen -N ""
    cd ~/.ssh
    tar czf keys.tar.gz id_rsa*) >/dev/null
    cat ~/.ssh/keys.tar.gz
' > keys.tar.gz
tar xf keys.tar.gz
rm keys.tar.gz
$ ./gen-keys.sh
$ docker-compose build
$ docker-compose up
$ docker-compose exec a ssh root@b hostname
$ docker-compose exec b ssh root@a hostname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment