How to copy a file to a remote docker container

George Shuklin
OpsOps
Published in
1 min readMay 31, 2022

You have:

  1. a_file (local)
  2. a container (a_container) on a remote host (a_server).
  3. an access to a remote host via ssh with permissions to use docker or sudo. I’ll use sudo example here.

Goal: to copy local /tmp/a_file to /var into container a_container on a_server server.

The main part of solution is ‘docker cp’, which can copy files to and from a container. But there is a bit of complications there. docker cp can be called in this form (- used as ‘STDIN’ notation):

docker cp - container:/path

In this form it expects to have a tar stream from stdin, not a file stream. It’s not obvious, and is pretty hard to debug when combined with ssh, but it’s doable.

The solution

cd /tmp
tar c a_file | ssh a_server sudo docker cp - a_container:/var

Note that there is ‘cd’, because we need to trim ‘/tmp’ from tar archive.

If we just run tar c /tmp/a_file ... - a_container:/var it will create /var/tmp/a_file, which is not what we want.

Fun fact

You can do it with stopped containers! That means, you can copy your busybox in any container (even if this container is constantly failing and you can’t exec into it) and start it with your personal debugger (sh from busybox) as an entry point. Or just docker exec into it, if container is alive but has nothing to run for ‘exec’.

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.