基于 alpine
镜像, 体积小, 方便做小实验, 本次实践使用 alpine:3.8
版本, 若使用其它本版, 更改 Dockerfile
中 FROM alpine:3.8
版本号与阿里源的版本号.
Dockerfile
文件
FROM alpine:3.8
RUN echo "http://mirrors.aliyun.com/alpine/v3.8/main/" > /etc/apk/repositories
RUN echo "http://mirrors.aliyun.com/alpine/v3.8/community/" >> /etc/apk/repositories
RUN apk update && \
apk add --no-cache openssh openrc tzdata && \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
sed -i "s/#PermitRootLogin.*/PermitRootLogin yes/g" /etc/ssh/sshd_config && \
mkdir -p /root/.ssh && chmod 700 /root/.ssh/ && \
ssh-keygen -A && \
echo "root:root" | chpasswd && \
apk del tzdata && \
rm -rf /var/cache/apk/*
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
使用方法
构建镜像
# docker build -t alpine:sshd .
创建容器 test
# docker run -d --name test -p 10022:22 alpine:sshd
本地ssh登录
# ssh root@127.0.0.1 -p10022
// 输入密码, 密码为root
# root@127.0.0.1's password:
Welcome to Alpine!
The Alpine Wiki contains a large amount of how-to guides and general
information about administrating Alpine systems.
See <http://wiki.alpinelinux.org>.
You can setup the system with the command: setup-alpine
You may change this message by editing /etc/motd.
559df031682e:~#
也可查看容器 test
的ip后 用ip进行ssh登录
# docker exec test ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
24: eth0@if25: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP
link/ether 05:12:ac:12:09:01 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
valid_lft forever preferred_lft forever
// 查出ip为 172.17.0.2
# ssh root@172.17.0.2
// 输入密码, 密码为root
# root@172.17.0.2's password:
Welcome to Alpine!
The Alpine Wiki contains a large amount of how-to guides and general
information about administrating Alpine systems.
See <http://wiki.alpinelinux.org>.
You can setup the system with the command: setup-alpine
You may change this message by editing /etc/motd.
559df031682e:~#
免密登录容器
创建容器 test
(ps: 本地 id_rsa.pub
文件拥有者为root)
# docker run -d --name test -p 10022:22 -v ~/.ssh/id_rsa.pub:/root/.ssh/authorized_keys alpine:sshd
这样本地ssh登录就不用输入密码了
也可创建多个容器, 若想容器与容器之间免密登录, 需要 docker exec
进入容器a创建公钥, 复制到容器b中
若不想以root权限登录容器, 需要更改 Dockfile
文件, 添加 adduser
和 addgroup
等命令, 具体做法请自行百度或谷歌