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