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/624e431e00ffa86efbf07e86d9efadbe to your computer and use it in GitHub Desktop.

Connect 2 docker containers using SSH (w/o 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 pwgen \
    && echo "root:`pwgen -1`" | chpasswd
COPY host-keys/* /etc/ssh
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
awk -v "host=$1" '{print host, $1, $2}' \
    /etc/ssh/ssh_host_ecdsa_key.pub \
    /etc/ssh/ssh_host_ed25519_key.pub \
    /etc/ssh/ssh_host_rsa_key.pub \
    > ~/.ssh/known_hosts

# /usr/sbin/sshd -d
/usr/sbin/sshd

exec sleep infinity

gen-key.sh:

#!/bin/sh -eu
if [ -e id_rsa ] \
|| [ -e id_rsa.pub ] \
|| [ -e host-keys ]; 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
    if [ -e host-keys ]; then
        mv host-keys .bak-$t
    fi
fi
docker run --rm alpine:3.15 sh -euc '
    (apk add openssh
    ssh-keygen -A
    yes "" | ssh-keygen -N ""
    cd ~/.ssh
    mkdir host-keys
    cp /etc/ssh/ssh_host* host-keys
    tar czf keys.tar.gz id_rsa* host-keys) >/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