我有一个应用程序,执行各种有趣的东西与Git(像运行Git克隆& Git推送),我试图docker-ize它。
我遇到了一个问题,虽然我需要能够添加一个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
在我的情况下,我有一个问题与nodejs和'npm I '从一个远程存储库。我修复了添加'node'用户到nodejs容器和700到~/。容器中的SSH。
Dockerfile:
USER node #added the part
COPY run.sh /usr/local/bin/
CMD ["run.sh"]
run.sh:
#!/bin/bash
chmod 700 -R ~/.ssh/; #added the part
docker-compose.yml:
nodejs:
build: ./nodejs/10/
container_name: nodejs
restart: always
ports:
- "3000:3000"
volumes:
- ../www/:/var/www/html/:delegated
- ./ssh:/home/node/.ssh #added the part
links:
- mailhog
networks:
- work-network
在那之后,它开始工作
如果您需要在构建时使用SSH,那么这个问题就更难解决了。例如,如果你使用git克隆,或者在我的情况下,pip和npm从私有存储库下载。
我发现的解决方案是使用——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并且有实验功能,你可以在build命令中添加——squash,它将合并层,删除SSH密钥并从Docker历史记录中隐藏它们。
下面是我如何在使用docker composer构建图像时使用ssh键:
.env
SSH_PRIVATE_KEY=[base64 encoded sshkey]
docker-compose.yml
version: '3'
services:
incatech_crawler:
build:
context: ./
dockerfile: Dockerfile
args:
SSH_PRIVATE_KEY: ${SSH_PRIVATE_KEY}
dockerfile:
...
# Set the working directory to /app
WORKDIR /usr/src/app/
ARG SSH_PRIVATE_KEY
RUN mkdir /root/.ssh/
RUN echo -n ${SSH_PRIVATE_KEY} | base64 --decode > /root/.ssh/id_rsa_wakay_user