通过 sshd 连接至容器
实验要求 :
- ssh可以登录容器
- 在容器内yum 安装httpd并且启动
1) 创建容器
[root@localhost ~]# docker run -itd --name sshd centos /bin/bash
2aa983df1ee89931194df94dc895b723dabd129ccbd95a93e281fd2829cecbfe
2) 进入容器并安装一些必要的工具
[root@localhost ~]# docker exec -it sshd /bin/bash
[root@2aa983df1ee8 /]# yum -y install openssh-server openssh-clients passwd iproute net-tools
3) 修改 root 登录密码
[root@d950cc15754d /]# passwd root
4) 生成 sshd 启动所需的秘钥
- sshd 启动需要,并指定指定位置保存
[root@d950cc15754d /]# ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ''
[root@d950cc15754d /]# ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ''
[root@d950cc15754d /]# ssh-keygen -t dsa -f /etc/ssh/ssh_host_ed25519_key -N ''
- 编辑SSH 服务配置文件
[root@d950cc15754d /]# vi /etc/ssh/sshd_config
# UsePAM no
// 改为no,并且注释掉,因docker 容器中没有 pma模块
UsePrivilegeSeparation no
// 解开注释,并改为no,IP修改
PermitRootLogin yes
// 解开注释,允许超级用户(root)登录
- 查看 sshd 运行方式
[root@d950cc15754d /]# vi /usr/lib/systemd/system/sshd.service
[Unit]
Description=OpenSSH server daemon
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target sshd-keygen.service
Wants=sshd-keygen.service
[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D $OPTIONS // 此处为运行方式
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
7) 后台运行 sshd
- 放入后台运行
[root@d950cc15754d /]# /usr/sbin/sshd -D &
8) 退出容器,宿主机 ssh 连接容器
[root@localhost ~]# ssh root@172.17.0.2
root@172.17.0.2's password:
[root@d950cc15754d ~]#
9) yum 安装 httpd 服务
[root@d950cc15754d ~]# yum -y install httpd
10) 查看httpd 服务的启动方式
[root@d950cc15754d ~]# vi /usr/lib/systemd/system/httpd.service
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)
[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/httpd
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND // 启动方式
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful
ExecStop=/bin/kill -WINCH ${MAINPID}
# We want systemd to give httpd some time to finish gracefully, but still want
# it to kill httpd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give
# httpd time to finish.
KillSignal=SIGCONT
PrivateTmp=true
[Install]
WantedBy=multi-user.target
11) 启动httpd
[root@d950cc15754d ~]# /usr/sbin/httpd $OPTIONS -DFOREGROUND
[root@d950cc15754d ~]# netstat -anpt | grep 80
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 268/httpd
- 退出容器
- 并测试访问
[root@d950cc15754d ~]# exit
logout
Connection to 172.17.0.2 closed.
[root@localhost ~]# curl 172.17.0.2