如何拷貝Docker容器內的文件?

  • 2019 年 11 月 20 日
  • 筆記

開始之前

某個項目容器需要添加 wkhtmltopdf 軟件包用於處理html與pdf文件轉換,由於默認的apt源服務器在國外,使用apt 安裝 wkhtmltopdf 時下載速度只有感人的幾kb/s。

我們需要更換一個國內的apt鏡像地址,例如使用 阿里雲、網易雲、等開源鏡像站。debain 或 ubuntu 系統 apt 倉庫配置保存在 /etc/apt/sources.list 配置文件中,我們可以替換容器中的這個文件。

環境描述

容器鏡像: php:5.6-fpm  容器系統: debian 8 (jessie)  配置文件: /etc/apt/sources.list  Docker主機: Ubuntu Server 16.04

舉個栗子

1. 創建 sources.list文件,內容如下:

cat sources.list    deb http://mirrors.aliyun.com/debian/ jessie main non-free contrib  deb http://mirrors.aliyun.com/debian/ jessie-proposed-updates main non-free contrib  deb-src http://mirrors.aliyun.com/debian/ jessie main non-free contrib  deb-src http://mirrors.aliyun.com/debian/ jessie-proposed-updates main non-free contrib

2. 備份容器內的文件

docker cp crm-test:/etc/apt/sources.list /tmp/sources.list.bak

這個條命令將把容器內的 sources.list文件,拷貝到宿主機上的 /tmp/目錄

3. 替換容器內的 sources.list文件

docker cp sources.list crm-test:/etc/apt/sources.list

相反這個條命令將把宿主機上的文件拷貝到容器

4. 驗證

docker exec -ti crm-test apt-get update  Ign http://mirrors.aliyun.com jessie InRelease  省略...  Fetched 22.0 MB in 19s (1120 kB/s)  Reading package lists... Done

5. 擴展 Dockerfile

每次都要為容器添加 sources.list文件實在是麻煩我們可以優化一下,把這個步驟定義在 Dockerfile 中例如:

head -n7 base/5.6/Dockerfile  # php-fpm:5.6    FROM php:5.6-fpm  MAINTAINER dongnan    # apt  COPY conf/sources.list /etc/apt/sources.list

命令幫助

docker cp --help    Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-      docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH    Copy files/folders between a container and the local filesystem    Options:    -a, --archive       Archive mode (copy all uid/gid information)    -L, --follow-link   Always follow symbol link in SRC_PATH

小結

最後來總結下文章中的知識點

  • docker cp子命令可以用來在容器與宿主機之間拷貝文件。
  • 拷貝文件時沒有提示會直接替換目的文件,請提前做好備份工作。
  • 每次重複添加 sources.list文件很麻煩,更優的方式是在自定義docker鏡像添加 sources.list 文件。