How can I copy the newest file in docker directory to local directory? I know that I can use docker cp
but I have to know what file I have to copy. I can figure it out inside docker container by sorting the files at taking the last one but I don't know how to extract this path outside the container so that I could use docker cp
.
CodePudding user response:
Let's create a Docker image with 5 files with different timestamps
FROM debian
WORKDIR /app
RUN echo a > ahsgdfkjhagsdkf && sleep 1 && \
echo b > hsagdkfjhasgdkf && sleep 1 && \
echo c > ahsdgfkhjasgdfk && sleep 1 && \
echo d > hasgdfkjhasgdkh && sleep 1 && \
echo e > kasdflkjhasldfk
CMD ["tail", "-f", "/dev/null"]
Build and run it with
docker build -t test .
docker run -d --name mytest test
Then we can use ls -t | head -1
to find the newest file. Combine that with tar
to compress it in the container, send it to stdout and then decompress it on the host, like this
docker exec mytest /bin/sh -c 'tar -czO $(ls -t | head -1)' | tar -zxf -
The newest file, kasdflkjhasldfk, has now been copied to the host.
We need to execute /bin/sh
in the container and pass it the command in quotes. If we didn't have it in quotes, $(ls -t | head -1)
would be evaluated on the host and we would pass a filename to tar
that exists on the host, but not in the container.
By having the command that should be run in the container in quotes, $(ls -t | head -1)
is evaluated in the container and we get the correct filename.