在 docker 容器中使用 SSH 密钥

新手上路,请多包涵

我有一个应用程序可以用 Git 执行各种有趣的东西(比如运行 git clone 和 git push),我正在尝试对它进行 docker 化。

我遇到了一个问题,尽管我需要能够将 SSH 密钥添加到容器以供容器“用户”使用。

我尝试将其复制到 /root/.ssh/ ,更改 $HOME ,创建一个 git ssh 包装器,但仍然没有运气。

以下是 Dockerfile 供参考:

 #DOCKER-VERSION 0.3.4

from  ubuntu:12.04

RUN  apt-get update
RUN  apt-get install python-software-properties python g++ make git-core openssh-server -y
RUN  add-apt-repository ppa:chris-lea/node.js
RUN  echo "deb http://archive.ubuntu.com/ubuntu precise universe" >> /etc/apt/sources.list
RUN  apt-get update
RUN  apt-get install nodejs -y

ADD . /src
ADD ../../home/ubuntu/.ssh/id_rsa /root/.ssh/id_rsa
RUN   cd /src; npm install

EXPOSE  808:808

CMD   [ "node", "/src/app.js"]

app.js 运行 git 命令,如 git pull

原文由 ebensing 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

结果在使用 Ubuntu 时,ssh_config 不正确。您需要添加

RUN  echo "    IdentityFile ~/.ssh/id_rsa" >> /etc/ssh/ssh_config

到您的 Dockerfile 以使其识别您的 ssh 密钥。

原文由 ebensing 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您需要在构建时使用 SSH,这是一个更难的问题。例如,如果您使用 git clone ,或者在我的情况下 pipnpm 从私有存储库下载。

我找到的解决方案是使用 --build-arg 标志添加您的密钥。然后您可以使用新的实验性 --squash 命令(添加1.13)来合并图层,以便在删除后不再可用密钥。这是我的解决方案:

构建命令

$ docker build -t example --build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" --squash .

Dockerfile

 FROM python:3.6-slim

ARG ssh_prv_key
ARG ssh_pub_key

RUN apt-get update && \
    apt-get install -y \
        git \
        openssh-server \
        libmysqlclient-dev

# Authorize SSH Host
RUN mkdir -p /root/.ssh && \
    chmod 0700 /root/.ssh && \
    ssh-keyscan github.com > /root/.ssh/known_hosts

# Add the keys and set permissions
RUN echo "$ssh_prv_key" > /root/.ssh/id_rsa && \
    echo "$ssh_pub_key" > /root/.ssh/id_rsa.pub && \
    chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/id_rsa.pub

# Avoid cache purge by adding requirements first
ADD ./requirements.txt /app/requirements.txt

WORKDIR /app/

RUN pip install -r requirements.txt

# Remove SSH keys
RUN rm -rf /root/.ssh/

# Add the rest of the files
ADD . .

CMD python manage.py runserver


更新: 如果您使用 Docker 1.13 并且具有实验性功能,您可以将 --squash 附加到将合并层的构建命令,删除 SSH 密钥并将它们隐藏在 docker history 中。

原文由 Daniel van Flymen 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题