1. 程式人生 > >docker容器開啟sshd

docker容器開啟sshd

開啟 clas pass bash ssh連接 iyu -o abcd roc

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

我們知道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
[root@a8c8e0fbd74f ~]# 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!

docker容器開啟sshd