如何使用docker cp从主机计算机同步到Docker容器

15

我正在尝试运行以下内容:

  1. 在后台启动一个容器

docker run -dit -p 8090:80 --name container repository:dockerfile bash

  1. 我想从/test中排除子目录/data

docker cp /Users/$USER/test container:/test

  1. 我考虑使用rsync进行操作 docker exec rsync -avP --exclude /Users/$USER/test/data /Users/$USER/test/ container:/test/

我收到以下错误:

rsync: Failed to exec ssh: No such file or directory (2)
rsync error: error in IPC code (code 14) at pipe.c(85) [sender=3.1.0]
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(226)
[sender=3.1.0]

我该如何从主机同步到容器中使用rsync?

5个回答

8

首先将宿主机目录映射到容器中:

docker run -v /Users/$USER/test:/temp-test -dit -p 8090:80 --name container repository:dockerfile bash

然后按照以下方式使用rsync:
docker exec container rsync -avP --exclude /temp-test/data /temp-test/ /test/

7

使用rsync将文件复制到Docker容器的方法

确保您的Docker容器安装了rsync,并定义此别名:

alias drsync="rsync -e 'docker exec -i'"

现在,您可以像使用远程机器一样使用容器来使用rsync:
drsync -av /source/ container:/destination/

协议版本不匹配--您的Shell是否干净?(请参阅rsync手册页面以获取说明) rsync错误:协议不兼容(代码2),位于compat.c(178)[sender=3.1.3]我应该添加bin/bash吗? - Kevin wang
如果容器在远程服务器上运行,您该如何处理?假设我使用以下命令将文件直接传输到服务器:“rsync -avP /source/ user@remote_server:/destination”并且容器名称为“container”。 - Irina S.
2
太好了!我会更加强调**"确保您的Docker容器已安装rsync"**。如果没有安装,您将会遇到一个晦涩的错误:"协议版本不匹配 - 您的shell是否干净?" - Brent Bradburn

4
当你运行 docker exec rsync [...] 命令时,你在容器中执行了 rsync 命令。 路径 /Users/$USER/test/ 对应的是你主机系统上的一个目录,因此在容器中,rsync 很难找到它。
基本上有两种方法可以使用 rsync 将文件传输到容器中:
  1. You can install an ssh server on you host system and use rsync to connect from within your container to the host system from the outside. If you have a running ssh server on you host and the host is reachable under the name host you can do

    docker exec rsync -avP --exclude /Users/$USER/test/data host:/Users/$USER/test /test
    
  2. You can install an ssh server inside the container and use rsync on your host system to connect to the container from the outside. I assume your container is reachable under the name container, then you can do

    rsync avP --exclude /Users/$USER/test/data /Users/$USER/test container:/test
    

    In this case you have to make sure that the ssh port (default is 22) is published by the docker daemon.


1
rsync有一个服务器模式,你不需要使用ssh。 - Jean-Bernard Jansen
如果你没有安装ssh,你就需要担心“协议版本不匹配”的问题。最终我也安装了ssh。 - Sridhar Sarnobat

1

0

这个

rsync: Failed to exec ssh: No such file or directory (2)

的原因是您的容器中未安装ssh。 您可以手动安装它,或将其添加到您的要求文件中以自动安装。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接