Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
df:8f:28:b0:74:97:bb:48:07:a2:3a:12:31:f6:3b:cd root@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
| |
| |
| |
|o. |
|.o. . S . |
|. . .o..oo. |
| . =. +..o.. |
|. .+ E...o.. o |
| .... ..o.. . |
+-----------------+
REPOSITORY TAG IMAGE ID CREATED SIZE
docker.io/centos centos6 cf2c3ece5e41 13 months ago 194.6 MB
编辑Dockerfile
[root@localhost ~]# cd sshd_dockerfile/
[root@localhost sshd_dockerfile]# ls
authorized_keys Dockerfile run.sh
[root@localhost sshd_dockerfile]# vim Dockerfile
FROM cf2c3ece5e41
RUN yum install -y openssh-server sudo httpd
RUN useradd admin
RUN echo "admin:admin" | chpasswd
RUN echo "admin ALL=(ALL) ALL" >> /etc/sudoers
RUN ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key
RUN mkdir -p /var/run/sshd
RUN mkdir -p /home/admin/.ssh
RUN sed -i "s/#ServerName/ServerName/g" /etc/httpd/conf/httpd.conf
RUN sed -i 's/session reqired pam_loginuid.so/#session reqired pam_loginuid.so/g' /etc/pam.d/sshd
ADD authorized_keys /home/admin/.ssh/authorized_keys
ADD run.sh /run.sh
RUN chmod 775 /run.sh
CMD ["apachectl -k start"]
EXPOSE 22 80 443
CMD ["/bin/bash","/run.sh"]
在sshd_dockerfile目录下,使用docker build命令来创建镜像,注意:在最后还有一个”.”,表示使用当前目录中的dockerfile
[root@localhost sshd_dockerfile]# docker build -t "centos:http" .
REPOSITORY TAG IMAGE ID CREATED SIZE
centos http 5377fab12932 About a minute ago 298.6 MB
docker.io/centos centos6 cf2c3ece5e41 13 months ago 194.6 MB
当使用–P(大写)标记时,Docker 会随机映射一个随机的端口到内部容器开放的网络端口。
注:-P使用时需要指定--expose选项或dockerfile中用expose指令容器要暴露的端口,指定需要对外提供服务的端口
使用 docker ps 可以看到,本地主机的32776被映射到了容器的22端口,本地主机的32775被映射到了容器的80端口,本地主机的32774被映射到了容器的443 端口。
[root@localhost ~]# docker run -d -P centos:http
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a244bac6b823 centos:http "/bin/bash /run.sh" 13 seconds ago Up 10 seconds 0.0.0.0:32776->22/tcp, 0.0.0.0:32775->80/tcp, 0.0.0.0:32774->443/tcp desperate_curran
此时访问本机的 32770端口即可访问容器内 ssh 应用。
[root@localhost sshd_dockerfile]# ssh admin@192.168.1.107 -p 32776
The authenticity of host '[192.168.1.107]:32776 ([192.168.1.107]:32776)' can't be established.
RSA key fingerprint is d9:7c:08:54:eb:b0:78:3f:64:2c:54:32:e1:c3:56:9f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[192.168.1.107]:32776' (RSA) to the list of known hosts.
[admin@a244bac6b823 ~]$
注:192.168.1.107是宿主主机地址。
查看容器运行的httpd进程
[admin@a244bac6b823 ~]$ pgrep httpd