In this article, we will show you how to use docker cp to copy files or folders from a docker container to the host (local file system) or the reversed.

For example, here is a running container, id is d362659da5fc, later we will copy files from and to this container.

$ docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS                   NAMES
d362659da5fc        markdownhtml:1.1    "java -jar app.jar"   20 minutes ago      Up 20 minutes       0.0.0.0:80->8080/tcp,   xenodochial_volhard

The docker cp command works similar to scp command.

1. Container -> Local Host

Copy file or folder from a docker container to the local file system.

$ docker cp <containerId>:/file/path/in/container/file /host/local/path/file

# Copy /opt/app/app.log from the container d362659da5fc to the current local working directory
$ docker cp d362659da5fc:/opt/app/app.log .

# Copy /opt/app/app.log from the container d362659da5fc to local host, /home/mkyong/backup/app.log
$ docker cp d362659da5fc:/opt/app/app.log /home/mkyong/backup/

# Copy /opt/app/app.log from the container to local host, renamed to /home/mkyong/backup/app.bk.20200511.log
$ docker cp d362659da5fc:/opt/app/app.log /home/mkyong/backup/app.bk.20200511.log

# Copy files from folder /opt/app/ (container) to local host /home/mkyong/backup2/
$ docker cp d362659da5fc:/opt/app/ /home/mkyong/backup2/

If the copy file doesn’t exist in the container, it shows error.

$ docker cp d362659da5fc:/opt/app/abc.txt /home/mkyong/backup

Error: No such container:path: d362659da5fc:/opt/app/abc.txt

2. Local Host -> Container

Copy file or folder from the local file system to a docker container, it works the same.

$ docker cp /host/local/path/file <containerId>:/file/path/in/container/file

# Copy db.config from the current working directoty to a container da3430062137 /opt/app/db.config
$ docker cp db.config d362659da5fc:/opt/app/

# Copy /var/www/app/db.config from the local host to a container /opt/app/db.prod.config
$ docker cp /var/www/app/db.config d362659da5fc:/opt/app/db.prod.config

# Copy files from folder /var/www/app/ (local host) to container /opt/app/
$ docker cp /var/www/app/ d362659da5fc:/opt/app/

Further Reading

Commentaires

  1. Pingback: How to list containers in Docker ? » JavaTuto

Laisser un commentaire