目錄

docker cp 指令:在主機與容器之間複製檔案

docker cp 在主機與容器之間複製檔案,容器執行中或已停止都可以使用。

語法

docker cp [參數] 容器:來源路徑 主機目的地     # 容器 → 主機
docker cp [參數] 主機來源路徑 容器:目的地路徑   # 主機 → 容器
參數說明
-a, --archive保留檔案的擁有者(uid/gid)資訊
-L, --follow-link來源是符號連結時,複製它指向的實際檔案
-q, --quiet不顯示複製進度

把來源或目的地寫成 -,可以用 tar 格式從標準輸入讀取或輸出到標準輸出。

範例

對一個名為 web 的 nginx 容器操作:

$ docker cp web:/etc/nginx/nginx.conf ./nginx.conf

$ head -n 3 nginx.conf

user  nginx;
worker_processes  auto;

$ echo "<h1>copied in</h1>" > page.html

$ docker cp page.html web:/usr/share/nginx/html/page.html

$ docker exec web cat /usr/share/nginx/html/page.html
<h1>copied in</h1>

$ docker cp web:/etc/nginx/conf.d ./confd

$ ls confd
default.conf

$ docker cp web:/no/such/file .
Error response from daemon: Could not find the file /no/such/file in container web
指令說明
docker cp web:/etc/nginx/nginx.conf ./nginx.conf把容器的設定檔複製到主機,常用來取得預設設定再修改
docker cp page.html web:/usr/share/nginx/html/page.html把主機的檔案放進容器
docker cp web:/etc/nginx/conf.d ./confd複製整個資料夾。目的地 confd 不存在時,會建立它並放入資料夾的內容
docker cp web:/no/such/file .來源不存在時的錯誤訊息

複製資料夾的規則:

  • 目的地不存在:建立目的地資料夾,複製來源資料夾的內容進去(如上例)。
  • 目的地已存在:把來源資料夾整個放進目的地中,成為 目的地/來源資料夾名稱。
  • 來源路徑結尾加 /.(例如 web:/etc/nginx/conf.d/.):只複製內容,不包含資料夾本身。

什麼時候用 docker cp

適合:

  • 取出容器中的預設設定檔、日誌、產生的檔案。
  • 臨時放一個檔案進去測試。
  • 在 Windows PowerShell 中備份與還原資料庫:先在容器內匯出成檔案再 docker cp 出來,避開 PowerShell 不支援 < 和編碼的問題(實測見 常見錯誤訊息)。

不適合:

  • 開發時同步程式碼:用 Bind mount 或 docker compose watch(見 Node.js 應用)。
  • 需要保留的資料:用 Volume。

相關章節

動手練習

練習:把 web 容器中 nginx 的歡迎頁 /usr/share/nginx/html/index.html 複製到主機,修改標題後再複製回去,用瀏覽器確認(容器需要用 -p 8080:80 啟動)。

答案
docker cp web:/usr/share/nginx/html/index.html ./index.html
# 用編輯器修改 index.html
docker cp ./index.html web:/usr/share/nginx/html/index.html

重新整理 http://localhost:8080 就會看到修改。刪除容器後修改就會消失。

常見問題

docker cp 可以用在已停止的容器嗎?

可以。docker cp 直接讀寫容器的檔案系統,容器停止時也能複製,這在容器啟動失敗、需要把設定檔或日誌拿出來檢查時很有用。

用 docker cp 修改設定檔,重建容器後還在嗎?

不在。複製進去的檔案存在容器的可寫層,刪除容器就消失了。需要長期使用的檔案,請用 Bind mount 掛載或寫進映像檔。

docker compose 有對應的指令嗎?

有,docker compose cp 服務名稱:路徑 目的地,寫法相同,用服務名稱代替容器名稱。

更新於 2026年10月14日