How to Copy Files From Docker Container to Host


If you need to copy files from a Docker Container to the Host, then you can do one of the following:

Option 1 – Using docker cp

Syntax:

docker cp [OPTIONS] CONTAINER: SRC_PATH DEST_PATH

Setup the container:

# pull the ubuntu image
docker pull ubuntu

# run the container locally
docker run -it -d ubuntu

# connect to the container
docker exec -it abcde123456 /bin/bash

Create a file from the container:

cd usr
cd share
touch some_file.txt
ls

Copy the file from the container to the host:

docker cp abcde123456:/usr/share/some_file.txt ./some_file.txt
ls

Option 2 – Using Docker Mounts

Syntax:

docker run -ti -v <host_directory>:<container_directory>

Perform the copy:

docker run -it -v $HOME/directory/some_container:/some_container --name some_container ruby bash

Option 3 – Using COPY in the Dockerfile

Syntax:

COPY <SRC> <DEST>

Create a Dockerfile with the COPY syntax:

FROM python

WORKDIR /var/www/

# Copy any resources required
COPY ./app.py /var/www/app.py
COPY ./requirements.txt /var/www/requirements.txt

RUN pip install -r /var/www/requirements.txt

ENTRYPOINT ["echo", "Hello from the container"]