Moving files in and out of a docker container
#docker
#development
I recently stumbled across an old note I wrote about moving files in and out of Docker containers. It’s one of those commands I don’t use often enough to remember, but when I need it, I really need it.
So here’s a cleaned-up version for future me.
TL;DR
docker cp works much like the regular cp command.
The only difference is that one side of the copy can be a Docker container.
# move file from host to a container
docker cp <file_path_in_host> <container_name_or_id>:<file_path_in_container>
# move file from container to a host
docker cp <container_name_or_id>:<file_path_in_container> <file_path_in_host> A Practical Example
Let’s restore a sample PostgreSQL database inside a Docker container, create a backup, and then copy that backup back to the host.
Prerequisite
For this example, I already have a PostgreSQL 18 container running locally.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
900ee02ff8eb postgres:18-alpine "docker-entrypoint.s…" About an hour ago Up About an hour 0.0.0.0:15432->5432/tcp, [::]:15432->5432/tcp pg-swe-kata I’ll be using the pg-swe-kata container throughout the rest of this guide.
Download the sample database
The PostgreSQL Tutorial from Neon provides a sample database called
dvdrental.wget https://neon.com/postgresqltutorial/dvdrental.zipCopy the ZIP file into the container
docker cp dvdrental.zip pg-swe-kata:dvdrental.zipThe file is now available inside the container’s current working directory.
Open a shell in the container and extract the archive
docker exec -it pg-swe-kata bash unzip dvdrental.zipCreate the database and restore it
psql -U postgres CREATE DATABASE dvdrental; \q # exit psqlRestore the database using
pg_restore.pg_restore -U postgres -d dvdrental dvdrental.tarVerify the database was restored
psql -U postgres \c dvdrental # connect to database \dt # list all tables \q # exit psqlCreate a database backup
pg_dump -U postgres -W -F tar dvdrental -vf dvdrental_db_backup.tarCopy the backup back to the host
docker cp pg-swe-kata:dvdrental_db_backup.tar dvdrental_db_backup.tar
That’s it.