通過dockerfile製作映象

2020-08-13 14:43:44

Dockerfile是一個用於構建Docker映象的文字檔案,其中包含了建立Docker映象的全部指令。就是將我們安裝環境的每個步驟使用指令的形式存放在一個檔案中,最後生成一個需要的環境。

Docker使用Dockerfile構建映象步驟:

  • 建立dockerfile檔案
  • 通過build命令生成image映象檔案
  • 執行容器
  • 上傳倉庫

建立dockerfile檔案

1、建立dockerfile

新建一個資料夾,api-demo

然後進入api-demo,建立dockerfile

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox
$ mkdir api—-demo
$ cd api—-demo/
$ touch Dockerfile
$ vi Dockerfile

編寫Dockerfile檔案如下:

# 基於基礎映象
FROM python:3.6

# 設定code資料夾是工作目錄
WORKDIR /code

# 將程式碼新增到code資料夾下
COPY test_api.py  /code/

# 更新pip
RUN pip install --upgrade pip --index-url https://pypi.douban.com/simple

# pip安裝依賴包
RUN pip install -U pytest
RUN pip install -U requests

# 執行命令
CMD ["python", "test_api.py"]

2、dockerfile常用指令

Dockerfile 語法:

Dockerfile語法由兩部分構成,註釋和命令+參數

範例:

# 基於基礎映象
FROM python:3.6

常用指令如下

ADD

ADD命令有兩個參數,源和目標。它的基本作用是從源系統的檔案系統上覆制檔案到目標容器的檔案系統。如果源是一個URL,那該URL的內容將被下載並複製到容器中。

# Usage: ADD [source directory or URL] [destination directory]
ADD /my_app_folder /my_app_folder 

COPY

用於將檔案作爲一個新的層新增到映象中。通常使用 COPY 指令將應用程式碼賦值到映象中。

COPY test_api.py  /code/

CMD

和RUN命令相似,CMD可以用於執行特定的命令。和RUN不同的是,這些命令不是在映象構建的過程中執行的,而是在用映象構建容器後被呼叫。

CMD ["python", "test_api.py"]

ENTRYPOINT

設定容器啓動後執行的命令,並且不可被 docker run 提供的參數覆蓋。

每個 Dockerfile 中只能有一個 ENTRYPOINT,當指定多個時,只有最後一個起效。

ENTRYPOINT 幫助你設定一個容器使之可執行化,如果你結合CMD命令和ENTRYPOINT命令,你可以從CMD命令中移除「application」而僅僅保留參數,參數將傳遞給ENTRYPOINT命令。

# Usage: ENTRYPOINT application "argument", "argument", ..
# Remember: arguments are optional. They can be provided by CMD
# or during the creation of a container.
ENTRYPOINT echo
# Usage example with CMD:
# Arguments set with CMD can be overridden during *run*
CMD "Hello docker!"
ENTRYPOINT echo

ENV

ENV命令用於設定環境變數。這些變數以」key=value」的形式存在,並可以在容器內被指令碼或者程式呼叫。這個機制 機製給在容器中執行應用帶來了極大的便利。

# Usage: ENV key value
ENV SERVER_WORKS 4  

EXPOSE

EXPOSE用來指定埠,使容器內的應用可以通過埠和外界互動。

# Usage: EXPOSE [port]
EXPOSE 8080

FROM

FROM命令可能是最重要的Dockerfile命令。改命令定義了使用哪個基礎映象啓動構建流程。基礎映象可以爲任意鏡 像。如果基礎映象沒有被發現,Docker將試圖從Docker image index來查詢該映象。FROM命令必須是Dockerfile的首個命令。

# Usage: FROM [image name]
FROM ubuntu 

MAINTAINER

我建議這個命令放在Dockerfile的起始部分,雖然理論上它可以放置於Dockerfile的任意位置。這個命令用於宣告作者,並應該放在FROM的後面。

# Usage: MAINTAINER [name]
MAINTAINER authors_name 

RUN

RUN命令是Dockerfile執行命令的核心部分。它接受命令作爲參數並用於建立映象。不像CMD命令,RUN命令用於建立映象(在之前commit的層之上形成新的層)。

# pip安裝依賴包
RUN pip install -U pytest

USER

USER命令用於設定執行容器的UID。

# Usage: USER [UID]
USER 751

VOLUME

VOLUME命令用於讓你的容器存取宿主機上的目錄。

# Usage: VOLUME ["/dir_1", "/dir_2" ..]
VOLUME ["/my_files"]

WORKDIR

WORKDIR命令用於設定CMD指明的命令的執行目錄。

# Usage: WORKDIR /path
WORKDIR ~/

3、建立python檔案
建立python檔案 test_api.py,在這做一個簡單的介面測試,一個成功的測試用例和一個失敗的測試用例,程式碼如下:

# coding=utf-8
import requests
import pytest


def test_1():
    search_url = 'https://baidu.com/'

    respose = requests.get(url=search_url)

    assert 200 == respose.status_code


def test_2():
    search_url = 'https://baidu.com/'

    respose = requests.get(url=search_url)

    assert 400 == respose.status_code


if __name__ == "__main__":
    pytest.main(["-s", "test_api.py"]) 

通過build構建映象檔案

使用docker build 命令建立映象。

使用命令:(注意命令最後面的點)

docker build -t tynam/api-demo:v1.1 .

OPTIONS說明:
-tag, -t: 映象的名字及標籤,通常 name:tag 或者 name 格式;可以在一次構建中爲一個映象設定多個標籤。例如 tynam/api-demo:v1.1

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox/api—-demo
$ docker build -t tynam/api-demo:v1.1 .
Sending build context to Docker daemon  3.072kB
Step 1/7 : FROM python:3.6
---> 0db2e2bbf438
Step 2/7 : WORKDIR /code
---> Using cache
---> 688dd9856f6e
Step 3/7 : COPY test_api.py  /code/
---> 87e29f28e665
Step 4/7 : RUN pip install --upgrade pip --index-url https://pypi.douban.com/simple
---> Running in 14f5c424c164
Looking in indexes: https://pypi.douban.com/simple
Requirement already up-to-date: pip in /usr/local/lib/python3.6/site-packages (20.0.2)
Removing intermediate container 14f5c424c164
---> fbdb47946e97
Step 5/7 : RUN pip install -U pytest
---> Running in 6ffb142f983d
Collecting pytest
  Downloading pytest-5.4.1-py3-none-any.whl (246 kB)
Collecting wcwidth
  Downloading wcwidth-0.1.9-py2.py3-none-any.whl (19 kB)
Collecting importlib-metadata>=0.12; python_version < "3.8"
  Downloading importlib_metadata-1.6.0-py2.py3-none-any.whl (30 kB)
Collecting attrs>=17.4.0
  Downloading attrs-19.3.0-py2.py3-none-any.whl (39 kB)
Collecting more-itertools>=4.0.0
  Downloading more_itertools-8.2.0-py3-none-any.whl (43 kB)
Collecting pluggy<1.0,>=0.12
  Downloading pluggy-0.13.1-py2.py3-none-any.whl (18 kB)
Collecting packaging
  Downloading packaging-20.3-py2.py3-none-any.whl (37 kB)
Collecting py>=1.5.0
  Downloading py-1.8.1-py2.py3-none-any.whl (83 kB)
Collecting zipp>=0.5
  Downloading zipp-3.1.0-py3-none-any.whl (4.9 kB)
Collecting pyparsing>=2.0.2
  Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)
Collecting six
  Downloading six-1.14.0-py2.py3-none-any.whl (10 kB)
Installing collected packages: wcwidth, zipp, importlib-metadata, attrs, more-itertools, pluggy, pyparsing, six, packaging, py, pytest
Successfully installed attrs-19.3.0 importlib-metadata-1.6.0 more-itertools-8.2.0 packaging-20.3 pluggy-0.13.1 py-1.8.1 pyparsing-2.4.7 pytest-5.4.1 six-1.14.0 wcwidth-0.1.9 zipp-3.1.0
Removing intermediate container 6ffb142f983d
---> 0fe23e1c2a89
Step 6/7 : RUN pip install -U requests
---> Running in 21163a3acd67
Collecting requests
  Downloading requests-2.23.0-py2.py3-none-any.whl (58 kB)
Collecting certifi>=2017.4.17
  Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB)
Collecting chardet<4,>=3.0.2
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
Collecting idna<3,>=2.5
  Downloading idna-2.9-py2.py3-none-any.whl (58 kB)
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1
  Downloading urllib3-1.25.9-py2.py3-none-any.whl (126 kB)
Installing collected packages: certifi, chardet, idna, urllib3, requests
Successfully installed certifi-2020.4.5.1 chardet-3.0.4 idna-2.9 requests-2.23.0 urllib3-1.25.9
Removing intermediate container 21163a3acd67
---> 8a8ae3f778a5
Step 7/7 : CMD ["python", "test_api.py"]
---> Running in f7310b052d08
Removing intermediate container f7310b052d08
---> 308b0f67af64
Successfully built 308b0f67af64
Successfully tagged tynam/api-demo:v1.1
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

在執行過程中,可以看到執行步驟,及執行的指令。例如第五步:Step 5/7 : RUN pip install -U pytest

映象建立完成後可以使用命令檢視建立的映象:

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox/api—-demo
$ docker images
REPOSITORY                  TAG                IMAGE ID            CREATED            SIZE
tynam/api-demo              v1.1                308b0f67af64        12 minutes ago      927MB

執行容器

映象建立完成後開始執行,使用命令;

docker run -it tynam/api-demo:v1.1

執行結果如下:

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox/api—-demo
$ docker run -it tynam/api-demo:v1.1
================================================= test session starts ==================================================
platform linux -- Python 3.6.10, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: /code
collected 2 items

test_api.py .F

======================================================= FAILURES =======================================================
________________________________________________________ test_2 ________________________________________________________

   def test_2():
       search_url = 'https://baidu.com/'

       respose = requests.get(url=search_url)

>      assert 400 == respose.status_code
E      assert 400 == 200
E        +  where 200 = <Response [200]>.status_code

test_api.py:19: AssertionError
=============================================== short test summary info ================================================
FAILED test_api.py::test_2 - assert 400 == 200
============================================= 1 failed, 1 passed in 0.61s ==============================================

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox/api—-demo

上傳倉庫

docker擁有自己的映象倉庫,官方倉庫網站是 https://hub.docker.com/

映象上傳倉庫的流程爲:登錄>>tag操作>>push

1、建立賬號
進入docker hub https://hub.docker.com/ 註冊賬號,然後建立自己的倉庫

例如我建立的倉庫名爲 api
在这里插入图片描述
2、本地登錄docker
使用命令登錄自己的docker

docker login

範例:

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox
$ docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username (tynam): tynam
Password:
Login Succeeded

3、修改映象名
修改映象名和倉庫名一致,映象名稱必須和 hub 中的倉庫名稱一致,否則將會拋出錯誤, 使用命令:

docker tag IMAGEID(映象id) REPOSITORY:TAG(倉庫:標籤)

範例:

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox/api—-demo
$ docker tag 308b0f67af64 tynam/api:v1.1

修改後檢視映象

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox/api—-demo
$ docker images
REPOSITORY                  TAG                IMAGE ID            CREATED            SIZE
tynam/api-demo              v1.1                308b0f67af64        16 minutes ago      927MB
tynam/api                    v1.1                308b0f67af64        16 minutes ago      927MB

4、上傳映象

docker push [REPOSITORY]:[TAG]

範例:

TynamYang@XA-LSR-Tynam MINGW64 /d/docker/Docker Toolbox
$ docker push tynam/api:v1.1
The push refers to repository [docker.io/tynam/api]
de38accaade6: Pushed
52574f25c16c: Pushed
c2e450965650: Pushed
86dd60275049: Pushed
58f7d369eb64: Pushed
7e8b1f6898b0: Mounted from tynam/test
e91ff66f967f: Mounted from tynam/test
e05388744d34: Mounted from tynam/test
d4aeb4b1e8cc: Mounted from tynam/test
46829331b1e4: Mounted from tynam/test
d35c5bda4793: Mounted from tynam/test
a3c1026c6bcc: Mounted from tynam/test
f1d420c2af1a: Mounted from tynam/test
461719022993: Mounted from tynam/test
v1.1: digest: sha256:c821d6afcfb43cc03b47bf3e0241d04472f4ecc83455dd5b6a3acc6a1b5b3276 size: 3265

上傳完成後進入自己的倉庫可以檢視上傳結果
在这里插入图片描述