tutorials
ubuntu
linux
SSH
docker
可以透過
Dockerfile
Dockerfile
在 Dockerfile
最後 加入以下程式碼在最後片段
# ssh setting
RUN echo "$ssh_usr:$ssh_pwd" >> ~/passwdfile && \
chpasswd -c SHA512 < ~/passwdfile && \
rm ~/passwdfile && \
sed -i "s/#Port.*/Port 22/" /etc/ssh/sshd_config && \
sed -i "s/#PermitRootLogin.*/PermitRootLogin yes/" /etc/ssh/sshd_config && \
sed -i "s/#PasswordAuthentication.*/PasswordAuthentication yes/" /etc/ssh/sshd_config
# expose the port 22(which is the default port of ssh)
EXPOSE 22
# set entrypoint to restart ssh automatically
ENTRYPOINT service ssh restart && bash
預設會自動啟動 SSH
(藉由最後面的 ENTRYPOINT
)
在 docker run
contianer 時,加入 -p {remote_container_port}:{container_ssh_port}
來設定連到 container 的 port
-p
: 設定 local<->container 的 port mapping
例如 docker run -it --name test -p 5678:22 -d test_img
就是用 test_img
的 image 建立一個名字叫做 test
的 container,並且將 container 外部(就是 local)的 5678 port 對應到 container 內部的 port 22
container 內部 port(在這個例子是 22) 必須要是 container 裡 SSH 設定的 port
更多關於 docker 使用可以看這篇
$ docker exec -it {containerID_or_name} bash
-it
: 代表在執行 Docker 虛擬容器環境時,開啟虛擬終端機,以互動的模式執行以上面的例子來說就是
test
bash
: 因為要安裝 SSH 所以是以 bash 開啟$ apt-get update && apt-get install -y ssh
$ vim /etc/ssh/sshd_config
22
這個 port 是對應到上述的 {container_ssh_port}
PasswordAuthentication XXX
取消註解並修改成 PasswordAuthentication yes
PermitRootLogin XXX
取消註解並修改成 PermitRootLogin yes
$ passwd root
$ exit
$ docker restart {containerID_or_name}
$ docker exec -it {containerID_or_name} bash
$ /etc/init.d/ssh restart
每次重新啟動 container 後,都必須得進入 container 重新開啟 SSH
更多關於 SSH 安裝與設定可以看這篇
以 SSH 連線進剛剛設定的 container 的方式就是以和剛剛 server local 同樣 ip 連線,但 port 使用一開始設定的 {remote_contianer_port}