如何通过Dockerfile或Docker-Compose将容器内生成的文件复制到宿主机?
Hey there! Let's break down how to solve this—since you want to skip manual docker cp and handle this through configuration, here's what you need to know:
First: Dockerfile Can’t Do This Directly
Dockerfile is for building images, and it runs in an isolated environment during the build process. It has no access to your host machine’s filesystem to write files directly, plus the data file your script generates is created when the container runs (not during image building). So Dockerfile alone can’t make this happen.
The Best Solution: Use Docker Compose Volumes
Volumes are Docker’s built-in way to share data between containers and the host. For your use case, a bind mount (which links a specific host directory to a container directory) is the most straightforward fix. Here’s how to adjust your setup:
Step 1: Update Your Docker Compose File
Add a volumes section to your worker service to map a host directory to a container directory. This will sync files between the two locations in real time:
version: "3" services: worker: image: image_worker container_name: container_worker build: dockerfile: ./worker/Dockerfile volumes: # Map the host's ./host_data directory to /data_output inside the container - ./host_data:/data_output
Step 2: Adjust Your Container’s Output Path
Modify your Dockerfile’s CMD to write the data file directly to the mounted directory instead of the container’s root. This ensures the file shows up immediately on your host:
FROM archlinux RUN pacman-db-upgrade \ && pacman -Syyu --noconfirm \ && pacman -S python --noconfirm \ && pacman -S python-pip --noconfirm \ && pip install requests COPY /worker/script.py . # Write output to the mounted directory instead of container root CMD python3 vmtracer.py >> /data_output/data
How It Works
- When you start the container with
docker-compose up, Docker will create the./host_datadirectory on your host if it doesn’t already exist. - Any file written to
/data_outputinside the container will automatically appear in./host_dataon your host—no manual copying required.
Alternative: Named Volumes (If You Don’t Need a Specific Host Path)
If you don’t care about the exact host directory and just want Docker to manage the storage, you can use a named volume instead:
version: "3" services: worker: # ... other existing config ... volumes: - worker_data:/data_output volumes: worker_data:
You can access the volume’s files on the host via Docker’s internal storage path (usually /var/lib/docker/volumes/<volume_name>/_data), but bind mounts are simpler for direct, predictable host access.
内容的提问来源于stack exchange,提问作者Vida Eninkio

