記錄Ubuntu下使用docker使用


關鍵詞:docker、Dockerfile等等。

這里主要記錄Ubuntu下docker使用細節。

首先是如何安裝,然后如何創建docker鏡像、搭建docker服務器、運行使用docker。

1. docker安裝

sudo apt install docker-ce

2. 創建docker鏡像

創建docker鏡像文件,可以通過docker build,則讀取PATH目錄下Dockerfile創建名稱為new_image,tag為v1.0的docker鏡像文件。

docker build -t new_image:v1.0 PATH

更多細節:

Build an image from a Dockerfile

Options:
      --add-host list           Add a custom host-to-IP mapping (host:ip)
      --build-arg list          Set build-time variables
      --cache-from strings      Images to consider as cache sources
      --cgroup-parent string    Optional parent cgroup for the container
      --compress                Compress the build context using gzip
      --cpu-period int          Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int           Limit the CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int          CPU shares (relative weight)
      --cpuset-cpus string      CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string      MEMs in which to allow execution (0-3, 0,1)
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
      --force-rm                Always remove intermediate containers
      --iidfile string          Write the image ID to the file
      --isolation string        Container isolation technology
      --label list              Set metadata for an image
  -m, --memory bytes            Memory limit
      --memory-swap bytes       Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --network string          Set the networking mode for the RUN instructions during build (default
                                "default")
      --no-cache                Do not use cache when building the image
      --pull                    Always attempt to pull a newer version of the image
  -q, --quiet                   Suppress the build output and print image ID on success
      --rm                      Remove intermediate containers after a successful build (default true)
      --security-opt strings    Security options
      --shm-size bytes          Size of /dev/shm
  -t, --tag list                Name and optionally a tag in the 'name:tag' format
      --target string           Set the target build stage to build.
      --ulimit ulimit           Ulimit options (default [])

通過docker image rm <REPOSITORY>則可刪除鏡像文件。

下面分別介紹Dockerfile語法規則,如何創建鏡像文件?以及如何保存鏡像更新。

2.1 如何編寫Dockerfile文件

Dockerfile reference中詳細介紹了編寫Dockerfile的語法:

FROM:指定基礎鏡像,必須為第一個命令

格式:
  FROM <image>
  FROM <image>:<tag>
  FROM <image>@<digest>
示例:
  FROM mysql:5.6
注:
  tag或digest是可選的,如果不使用這兩個值時,會使用latest版本的基礎鏡像


MAINTAINER: 維護者信息

格式:
    MAINTAINER <name>
示例:
    MAINTAINER Jasper Xu
    MAINTAINER sorex@163.com
    MAINTAINER Jasper Xu <sorex@163.com>


RUN:構建鏡像時執行的命令

RUN用於在鏡像容器中執行命令,其有以下兩種命令執行方式:
shell執行
格式:
    RUN <command>
exec執行
格式:
    RUN ["executable", "param1", "param2"]
示例:
    RUN ["executable", "param1", "param2"]
    RUN apk update
    RUN ["/etc/execfile", "arg1", "arg1"]
注:
  RUN指令創建的中間鏡像會被緩存,並會在下次構建中使用。如果不想使用這些緩存鏡像,可以在構建時指定--no-cache參數,如:docker build --no-cache


ADD:將本地文件添加到容器中,tar類型文件會自動解壓(網絡壓縮資源不會被解壓),可以訪問網絡資源,類似wget

格式:
    ADD <src>... <dest>
    ADD ["<src>",... "<dest>"] 用於支持包含空格的路徑
示例:
    ADD hom* /mydir/          # 添加所有以"hom"開頭的文件
    ADD hom?.txt /mydir/      # ? 替代一個單字符,例如:"home.txt"
    ADD test relativeDir/     # 添加 "test" 到 `WORKDIR`/relativeDir/
    ADD test /absoluteDir/    # 添加 "test" 到 /absoluteDir/


COPY:功能類似ADD,但是是不會自動解壓文件,也不能訪問網絡資源


CMD:構建容器后調用,也就是在容器啟動時才進行調用。

格式:
    CMD ["executable","param1","param2"] (執行可執行文件,優先)
    CMD ["param1","param2"] (設置了ENTRYPOINT,則直接調用ENTRYPOINT添加參數)
    CMD command param1 param2 (執行shell內部命令)
示例:
    CMD echo "This is a test." | wc -
    CMD ["/usr/bin/wc","--help"]
注:
   CMD不同於RUN,CMD用於指定在容器啟動時所要執行的命令,而RUN用於指定鏡像構建時所要執行的命令。


ENTRYPOINT:配置容器,使其可執行化。配合CMD可省去"application",只使用參數。

格式:
    ENTRYPOINT ["executable", "param1", "param2"] (可執行文件, 優先)
    ENTRYPOINT command param1 param2 (shell內部命令)
示例:
    FROM ubuntu
    ENTRYPOINT ["top", "-b"]
    CMD ["-c"]
注:
   ENTRYPOINT與CMD非常類似,不同的是通過docker run執行的命令不會覆蓋ENTRYPOINT,而docker run命令中指定的任何參數,都會被當做參數再次傳遞給ENTRYPOINT。Dockerfile中只允許有一個ENTRYPOINT命令,多指定時會覆蓋前面的設置,而只執行最后的ENTRYPOINT指令。


LABEL:用於為鏡像添加元數據

格式:
    LABEL <key>=<value> <key>=<value> <key>=<value> ...
示例:
  LABEL version="1.0" description="這是一個Web服務器" by="IT筆錄"
注:
  使用LABEL指定元數據時,一條LABEL指定可以指定一或多條元數據,指定多條元數據時不同元數據之間通過空格分隔。推薦將所有的元數據通過一條LABEL指令指定,以免生成過多的中間鏡像。


ENV:設置環境變量

格式:
    ENV <key> <value>  #<key>之后的所有內容均會被視為其<value>的組成部分,因此,一次只能設置一個變量
    ENV <key>=<value> ...  #可以設置多個變量,每個變量為一個"<key>=<value>"的鍵值對,如果<key>中包含空格,可以使用\來進行轉義,也可以通過""來進行標示;另外,反斜線也可以用於續行
示例:
    ENV myName John Doe
    ENV myDog Rex The Dog
    ENV myCat=fluffy


EXPOSE:指定於外界交互的端口

格式:
    EXPOSE <port> [<port>...]
示例:
    EXPOSE 80 443
    EXPOSE 8080
    EXPOSE 11211/tcp 11211/udp
注:
  EXPOSE並不會讓容器的端口訪問到主機。要使其可訪問,需要在docker run運行容器時通過-p來發布這些端口,或通過-P參數來發布EXPOSE導出的所有端口


VOLUME:用於指定持久化目錄

格式:
    VOLUME ["/path/to/dir"]
示例:
    VOLUME ["/data"]
    VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"
注:
  一個卷可以存在於一個或多個容器的指定目錄,該目錄可以繞過聯合文件系統,並具有以下功能:
1 卷可以容器間共享和重用
2 容器並不一定要和其它容器共享卷
3 修改卷后會立即生效
4 對卷的修改不會對鏡像產生影響
5 卷會一直存在,直到沒有任何容器在使用它


WORKDIR:工作目錄,類似於cd命令

格式:
    WORKDIR /path/to/workdir
示例:
    WORKDIR /a  (這時工作目錄為/a)
    WORKDIR b  (這時工作目錄為/a/b)
    WORKDIR c  (這時工作目錄為/a/b/c)
注:
  通過WORKDIR設置工作目錄后,Dockerfile中其后的命令RUN、CMD、ENTRYPOINT、ADD、COPY等命令都會在該目錄下執行。在使用docker run運行容器時,可以通過-w參數覆蓋構建時所設置的工作目錄。


USER:指定運行容器時的用戶名或 UID,后續的 RUN 也會使用指定用戶。使用USER指定用戶時,可以使用用戶名、UID或GID,或是兩者的組合。當服務不需要管理員權限時,可以通過該命令指定運行用戶。並且可以在之前創建所需要的用戶

 格式:
  USER user
  USER user:group
  USER uid
  USER uid:gid
  USER user:gid
  USER uid:group

 示例:
  USER www

 注:

  使用USER指定用戶后,Dockerfile中其后的命令RUN、CMD、ENTRYPOINT都將使用該用戶。鏡像構建完成后,通過docker run運行容器時,可以通過-u參數來覆蓋所指定的用戶。


ARG:用於指定傳遞給構建運行時的變量

格式:
    ARG <name>[=<default value>]
示例:
    ARG site
    ARG build_user=www


ONBUILD:用於設置鏡像觸發器

格式:
  ONBUILD [INSTRUCTION]
示例:
  ONBUILD ADD . /app/src
  ONBUILD RUN /usr/local/bin/python-build --dir /app/src
注:
  當所構建的鏡像被用做其它鏡像的基礎鏡像,該鏡像中的觸發器將會被鑰觸發
Dockerfile語法簡介

 參考文檔:《Dockerfile語法簡介

2.2 docker鏡像創建示例

創建Dockerfile:

FROM ubuntu:16.04
MAINTAINER Lu Baoquan
RUN apt update
RUN apt -y --force-yes install git make automake autoconf libtool g++ patch wget cpio python unzip rsync bc bzip2

創建一個新的docker鏡像:

docker build --rm --force-rm -t image_name:tag <Dockerfile_path>

通過docker images即可查看新創建的鏡像:

REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
build_machine_ubuntu_1604   v1.0                fd3aa2b241c6        4 seconds ago       121MB
ubuntu                      16.04               657d80a6401d        31 hours ago        121MB

2.3 保存/恢復docker鏡像(export/import)

通過docker export導出docker鏡像文件:

docker export <CONTAINER ID>/<NAMES> -o <output_file_name>

通過docker image import <output_file_name> <REPOSITORY>:<TAG>,即可將docker image save保存的文件導入到docker image中。

docker image import <output_file_name> <REPOSITORY>:<TAG> --change 'CMD /bin/bash'

注意:docker鏡像文件在export的時候會丟失image layers和meta data,這就造成丟失了啟動init進程的入口。

詳細解釋見《“No command specified” from re-imported docker image/container

2.4 保存/恢復docker鏡像(save/load)

在啟動docker鏡像后,在docker容器中所做的修改需要docker commit才能保存下來。

docker commit -a author_name -m "comment" <container_id> <new_image_name>

其中container_id通過docker ps -l獲取。

然后通過docker image save,擇新commit的image名稱或者image id

docker image save <REPOSITORY> -o <output_file_name>

則可將commit之后的鏡像保存下來。

然后通過load命令加載:

docker load -i <output_file_name>

則可將保存的鏡像加載。

3. 搭建docker鏡像服務器

通過創建Harbor可以搭建存儲Docker鏡像的企業級Registry服務,搭建方法參考《Docker Harbor》或者官方的《Installation and Configuration Guide》。

進入Harbor,選擇“新建項目”:

然后在“推送鏡像”中有推送鏡像的命令。

具體命令如下:

docker tag SOURCE_IMAGE[:TAG] 192.168.33.171:8091/runtime/IMAGE[:TAG] docker push 192.168.33.171:8091/runtime/IMAGE[:TAG]

執行結果如下:

al@al-B250-HD3:~/docker$ docker tag build_machine:v1.0 192.168.33.171:8091/runtime/build_machine:v1.0
al@al-B250-HD3:~/docker$ docker push 192.168.33.171:8091/runtime/build_machine:v1.0
The push refers to repository [192.168.33.171:8091/runtime/build_machine]
e4f9585af1cb: Pushed 
9acfe225486b: Pushed 
90109bbe5b76: Pushed 
cb81b9d8a6c9: Pushed 
ea69392465ad: Pushed 
v1.0: digest: sha256:143374e4032af644e6d69797f85dff644335d4a156a323357b54613ae9e33f0d size: 1363

4. 拉取docker進行並運行

配置本地docker,然后通過sudo docker restart重啟docker服務:

{
  "insecure-registries": ["192.168.33.171:8091","192.168.33.171" ]
}

 注冊到docker進行服務器:

docker login xxx

然后就是輸入用戶名和密碼。

4.1 下載docke鏡像

從docker服務器拉取docker鏡像:

docker pull 192.168.33.171:8091/runtime/build_machine:v1.0

顯示docker鏡像列表:

docker images

更多的操作docker鏡像的命令:

Usage:    docker image COMMAND

Manage images

Commands:
  build       Build an image from a Dockerfile
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Display detailed information on one or more images
  load        Load an image from a tar archive or STDIN
  ls          List images
  prune       Remove unused images
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rm          Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE

4.2 docker container使用

啟動新的docker容器:

docker run -it --name deepeye -v 本地目錄絕對路徑:docker目錄絕對路徑 docker倉庫名/鏡像ID

其中docker倉庫名可以通過docker images查看。

刪除docker容器運行實例:

docker rm docker倉庫名

其他命令包括:

docker start-------------------------啟動一個docker容器。
docker restart-----------------------重啟docker容器。
docker attach------------------------附着到一個啟動的docker容器上。

在docker容器運行起來后,就可以在里面執行新環境操作。

4.3 docker修改上傳

首先將當前容器changed_container_id的修改提交到新的鏡像new_image_name[:tag]中。

然后將保存的鏡像new_image_name[:tag]打tag到server_ip:port/path_to_image[:tag],然后用docker push提交到Harbor服務器。

docker commit -a author_name -m "comment" changed_container_id new_image_name[:tag]
docker tag new_image_name[:tag] server_ip:port/path_to_image[:tag]
docker push server_ip:port/path_to_image[:tag]

比如:

docker commit -a lubaoquan -m "Add pip packages for desdk python" 2ba9ecbd53eb build_machine:20200319
docker tag build_machine:20200319 192.168.33.171:8091/runtime/build_machine:latest
docker push 192.168.33.171:8091/runtime/build_machine:latest

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM