Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #16: Redirect a Container's File onto Your Docker Host

docker-tips-and-tricks.jpg

Every once in a while I find the need to dump a container's file onto my Docker host. Here's one way to do that very easily.

Quick Jump:

Sometimes for debugging purposes, you may want to copy the contents of a config file that’s sitting inside of a container over to your Docker host so that you can either open it in your favorite code editor or send it to someone.

This comes in handy for 1 off cases where you have an already running Docker container, and you don’t feel like restarting it with a volume because you need a single file “right now”.

You can easily do this by leveraging 2 things:
# 1. Override a Docker image's CMD to cat the file you want.
docker container run --rm alpine cat /etc/hosts

The above will print out the contents of the container’s /etc/hosts file. That’s half the solution.

# 2. Modify the command to redirect that output to a new file on your Docker host instead.
docker run --rm alpine cat /etc/hosts > /tmp/alpinehosts

You can confirm it works by running ls -la /tmp | grep alpinehosts. You’ll see the file.

Of course, you’ll need to make a few small adjustments if you’re running Windows instead of MacOS or Linux on your Docker host. For example, > does not work on Windows. You’ll need to Google on how to redirect output to a file if you’re using PowerShell, etc..

Also, in both cases, you will need the cat utility to be installed within your Docker image, but all major distributions of Linux have it (including Alpine, as we’ve just demonstrated).

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments