Dockerfile ssh免密登錄容器小實踐 docker-alpine-sshd

基於 alpine 鏡像, 體積小, 方便做小實驗, 本次實踐使用 alpine:3.8 版本, 若使用其它本版, 更改 DockerfileFROM 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 [email protected] -p10022
// 輸入密碼, 密碼爲root
# [email protected]'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 [email protected]
// 輸入密碼, 密碼爲root
# [email protected]'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 文件, 添加 adduseraddgroup 等命令, 具體做法請自行百度或谷歌






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章