Dockerfile ssh免密登录容器小实践 docker-alpine-sshd

10 篇文章 0 订阅

基于 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 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 文件, 添加 adduseraddgroup 等命令, 具体做法请自行百度或谷歌






  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值