1. 程式人生 > >如何在centos docker容器中支援sshd

如何在centos docker容器中支援sshd

### 1 啟動容器,以centos 為例,其他沒試過

#####root使用者執行下面的語句,非root,加個sudo:
```shell
docker run -d --privileged=true --name=centos centos /usr/sbin/init whlile true
```
解釋一下
--privileged=true可以解決dbus沒有許可權啟動的問題
/usr/sbin/init 可以解決不啟動dbus的問題,因為centos映象Dockerfile的預設CMD為/bin/bash,不啟動dbus

### 2 進入容器檢視dbus
```shell
systemctl status dbus,
```
狀態正常應該如下所示
```shell
[

[email protected] /]# systemctl status dbus
● dbus.service - D-Bus System Message Bus
Loaded: loaded (/usr/lib/systemd/system/dbus.service; static; vendor preset: disabled)
Active: active (running) since Fri 2018-12-14 11:31:36 UTC; 1min 16s ago
Docs: man:dbus-daemon(1)
Main PID: 183 (dbus-daemon)
CGroup: /docker/7df194571ba40af24540694149be9c353ed201ef3495f97b7f91c7c3e5f6031b/system.slice/dbus.service
└─183 /usr/bin/dbus-daemon --system --address=systemd: --nofork --...
‣ 183 /usr/bin/dbus-daemon --system --address=systemd: --nofork --...

```
### 3 安裝openssh-server,如果要ssh到其他機器,也可以把openssh-clients也裝了
##### -y 直接確認 -q 不想看一堆的安裝資訊的時候加上
##### 命令列:
```shell
yum -y -q install openssh-server
```
### 4 編輯sshd配置檔案,可以修改埠等配置
非必須,net的host模式啟動會和宿主機衝突,不改起不來
```shell
vi /etc/ssh/sshd_config
#Port 22
```
### 5 啟動sshd服務並檢視即可
```shell
systemctl start sshd
systemctl status sshd
```
##### 如下啟動成功
```shell
[

[email protected] /]# systemctl start sshd
[[email protected] /]# systemctl status sshd
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2018-12-14 11:48:34 UTC; 12s ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 2292 (sshd)
CGroup: /docker/7df194571ba40af24540694149be9c353ed201ef3495f97b7f91c7c3e5f6031b/system.slice/sshd.service
└─2292 /usr/sbin/sshd -D
‣ 2292 /usr/sbin/sshd -D

Dec 14 11:48:34 7df194571ba4 systemd[1]: Starting OpenSSH server daemon...
Dec 14 11:48:34 7df194571ba4 sshd[2292]: Server listening on 0.0.0.0 port 22.
Dec 14 11:48:34 7df194571ba4 sshd[2292]: Server listening on :: port 22.
Dec 14 11:48:34 7df194571ba4 systemd[1]: Started OpenSSH server daemon.
[[email protected] /]#

```
### 6 設定密碼
```shell
[[email protected] /]# passwd
Changing password for user root.
New password:
BAD PASSWORD: The password is shorter than 8 characters
Retype new password:
passwd: all authentication tokens updated successfully.
[[email protected] /]#
```
### 7 本地登入測試一下,
##### 遠端要麼對映埠,要麼net=host模式改22為其他埠,登入成功
```shell
[[email protected] /]# ssh localhost
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:CGSoUYr82TXpUZXL2xM3PdB+1ku8ZS45yKp8JQdnW18.
ECDSA key fingerprint is MD5:c0:0d:f1:54:fe:f0:f2:83:ca:3b:b3:50:49:42:78:54.
Are you sure you want to continue connecting (yes/no)? yes

Last failed login: Fri Dec 14 11:54:27 UTC 2018 from localhost on ssh:notty
There were 3 failed login attempts since the last successful login.
```
轉載請註明出處
https://www.aibug.cn/doc/web/#/page/edit/9/12