Dockerfile

FROM ubuntu:16.04

# package
RUN apt-get update; apt-get -y install ssh
COPY ssh_config /etc/ssh/ssh_config

# ssh
RUN sed -i 's/UsePAM yes/UsePAM no/g' /etc/ssh/sshd_config && sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/g' /etc/ssh/sshd_config
RUN echo "root:root" | chpasswd
RUN echo "root   ALL=(ALL)       ALL" >> /etc/sudoers
RUN ssh-keygen -t rsa -f ~/.ssh/id_rsa -P '' && \
    cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
RUN mkdir /var/run/sshd
EXPOSE 22

CMD [ "sh", "-c", "service ssh start && bash"]

生成镜像

docker build -t sshimage ./

验证ssh互信

  启动第一个docker容器,然后会进入bash,执行hostname -i来获取ip。

# docker run --rm -it sshimage
root@cbdf1f5e7e0f:/# hostname -i
172.17.0.4

  再启动另一个容器,并执行ssh $ip。

# docker run --rm -it sshimage
 * Starting OpenBSD Secure Shell server sshd                             [ OK ] 
root@ecaa455762df:/# ssh 172.17.0.4
Warning: Permanently added '172.17.0.4' (ECDSA) to the list of known hosts.
root@cbdf1f5e7e0f:~# hostname -i
172.17.0.4

  可以看到,ssh成功。