1. 程式人生 > >docker使用ssh遠端連線容器(沒錢買伺服器又不想安裝虛擬機器患者必備)

docker使用ssh遠端連線容器(沒錢買伺服器又不想安裝虛擬機器患者必備)

沒錢買伺服器又不想安裝虛擬機器怎麼辦?

我們知道docker是可以用exec來直接訪問容器的,但是還不夠high,有時候要模擬伺服器的登入總不能用docker exec吧,來吧,老司機帶你飛!

以centos為例,需要幾步操作

1.安裝openssh-server

2.初始化root使用者密碼

3.開啟sshd服務

廢話不多說,dockerfile獻上

FROM centos
RUN yum install -y wget && \
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo  && \
yum install -y passwd && \
yum install -y openssh-server  ssh-keygen && \
echo 
'abcd1234' | passwd root --stdin RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N "" -q && \ ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N "" -q && \ ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N "" -q #RUN systemctl enable sshd CMD /usr/sbin/sshd && tail -f /var/log/wtmp

簡單解釋一下,

安裝openssh-server

yum install -y wget && \
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo  && \
yum install -y passwd && \
yum install -y openssh-server  ssh-keygen

修改root密碼為abcd1234

echo 'abcd1234' | passwd root --stdin

建立ssh-keygen建立相關的ssh檔案,-q的意思是靜默模式(就是預設是需要讓你回車輸入的,加上這個直接跳過)

RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N "" -q && \
ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N "" -q && \
ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N "" -q

開啟sshd服務,並用tail來前臺執行阻止docker容器退出 

CMD /usr/sbin/sshd && tail -f /var/log/wtmp

 

構建映象

Dockerfile目錄下執行,yeah,就是chenqionghe/centos映象,你也可以弄成自己的,例如muscle/lightwegiht

docker build -t chenqionghe/centos .

執行容器

docker run --name centos_ssh -p 2222:22 -it chenqionghe/centos  

 

使用ssh連線容器

 這裡使用了2222埠來對映容器裡的22埠,執行起來就可以使用ssh連線了,輸出設定好的abcd1234密碼,注意,這裡用的是2222對映的埠  

➜  ~ ssh [email protected] -p 2222
[email protected]'s password:
Last login: Tue Nov 20 04:10:17 2018 from 172.17.0.1
[[email protected] ~]# ls -l /
total 56
-rw-r--r--   1 root root 12030 Oct  6 19:15 anaconda-post.log
lrwxrwxrwx   1 root root     7 Oct  6 19:14 bin -> usr/bin
drwxr-xr-x   5 root root   360 Nov 20 04:09 dev
drwxr-xr-x  54 root root  4096 Nov 20 04:09 etc
drwxr-xr-x   2 root root  4096 Apr 11  2018 home
lrwxrwxrwx   1 root root     7 Oct  6 19:14 lib -> usr/lib
lrwxrwxrwx   1 root root     9 Oct  6 19:14 lib64 -> usr/lib64
drwxr-xr-x   2 root root  4096 Apr 11  2018 media
drwxr-xr-x   2 root root  4096 Apr 11  2018 mnt
drwxr-xr-x   2 root root  4096 Apr 11  2018 opt
dr-xr-xr-x 223 root root     0 Nov 20 04:09 proc

就這麼簡單,hight起來吧,yeah buddy light weight baby!