Docker技術筆記:Docker入門淺嘗

adoryn發表於2018-03-18
版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/zhaobryant/article/details/79600059

簡介

本文將用Docker的方式來構建一個應用APP。

過去,如果要開發一個Python應用APP,所需做的第一件事就是在開發機上安裝Python執行時環境。在這種情形下,開發機的環境必須與APP所要求的環境一致,同時還需要與生產環境相匹配。

通過使用Docker,可以將一個可移植的Python執行時環境作為一個image獲取,而無需安裝。然後,就可以基於Python執行時環境image,將APP程式碼及其依賴庫合併構建,從而簡化了應用APP的部署難度。

用Dockerfile定義容器Container

Dockerfile是由一系列命令和引數構成的指令碼,這些命令應用於基礎映象並最終建立一個新的映象。它簡化了業務部署的流程,大大提高了業務的部署速度。Dockerfile的產出為一個新的可以用於建立容器的映象。

Dockerfile語法由兩部分構成,分別是“註釋”和“命令+引數”。

# Line blocks used for commenting
COMMAND argument1 argument2 ...

對於Dockerfile,我們首先建立一個空目錄,然後cd到該目錄,並建立Dockerfile檔案。

# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

其中,app.py和requirements.txt都位於與Dockerfile相同的目錄下,具體如下:

zjl@ubuntu:~/docker/pyapp$ ls
app.py  Dockerfile  requirements.txt

對於requirements.txt,其內容如下:

Flask
Redis

對於app.py,其內容如下:

from flask import Flask
from redis import Redis, RedisError
import os
import socket

redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr("counter")
    except RedisError:
        visits = "<i>cannot connect to Redis, counter disabled</i>"

    html = "<h3>Hello {name}!</h3>" 
           "<b>Hostname:</b> {hostname}<br/>" 
           "<b>Visits:</b> {visits}"
    return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80)

現在,我們知道,pip install -r requirements.txt為Python安裝了Flask和Redis庫,同時APP會列印出環境變數NAME,同時將socket.gethostname()列印出來。

構建新的image映象

下面,我們進行構建,具體如下:

zjl@ubuntu:~/docker/pyapp$ ls
app.py  Dockerfile  requirements.txt

zjl@ubuntu:~/docker/pyapp$ sudo docker build -t fhello .
Sending build context to Docker daemon  4.608kB
Step 1/7 : FROM python:2.7-slim
2.7-slim: Pulling from library/python
d2ca7eff5948: Pull complete 
cef69dd0e5b9: Pull complete 
50e1d7e4f3c6: Pull complete 
861e9de5333f: Pull complete 
Digest: sha256:e9baca9b405d3bbba71d4c3c4ce8a461e4937413b8b910cb1801dfac0a2423aa
Status: Downloaded newer image for python:2.7-slim
 ---> 52ad41c7aea4
Step 2/7 : WORKDIR /app
...
Step 3/7 : ADD . /app
...
Step 4/7 : RUN pip install --trusted-host pypi.python.org -r requirements.txt
...
Step 5/7 : EXPOSE 80
...
Step 6/7 : ENV NAME World
...
Step 7/7 : CMD ["python", "app.py"]
...
Successfully built d3fafd68e807
Successfully tagged fhello:latest

zjl@ubuntu:~/docker/pyapp$ sudo docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
fhello              latest              12d000cd7a1b        12 minutes ago      148MB

執行新的image映象

$ sudo docker run -p 4000:80 fhello
 * Running on http://0.0.0.0:80/ (Press CTRL+C to quit)

# 訪問該網站
$ curl localhost:4000
<h3>Hello World!</h3><b>Hostname:</b> f4e37f061593<br/><b>Visits:</b> <i>cannot connect to Redis, counter disabled</i>

$ sudo docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
4a150bdc67cd        fhello              "python app.py"     10 seconds ago      Up 9 seconds        0.0.0.0:4000->80/tcp   upbeat_austin

關閉容器,命令如下:

$ sudo docker container stop 4a150bdc67cd
4a150bdc67cd

給映象打上標籤

syntax: -->> docker tag image username/repository:tag


$ sudo docker tag fhello zhjl/getstarted:alpha-1
$ sudo docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
fhello              latest              12d000cd7a1b        18 minutes ago      148MB
zhjl/getstarted     alpha-1             12d000cd7a1b        18 minutes ago      148MB

$ docker run -p 4000:80 zhjl/getstarted:alpha-1

Recap and cheat sheet

# Create image using this directory`s Dockerfile
docker build -t fhello .

# Run "friendlyname" mapping port 4000 to 80
docker run -p 4000:80 fhello

# Same thing, but in detached mode
docker run -d -p 4000:80 fhello

# List all running containers
docker container ls

# List all containers, even those not running
docker container ls -a

# Gracefully stop the specified container
docker container stop <hash>

# Force shutdown of the specified container
docker container kill <hash>

# Remove specified container from this machine
docker container rm <hash>

# Remove all containers
docker container rm $(docker container ls -a -q)

# List all images on this machine
docker image ls -a

# Remove specified image from this machine
docker image rm <image id>

# Remove all images from this machine
docker image rm $(docker image ls -a -q)

# Log in this CLI session using your Docker credential
docker login

# Tag <image> for upload to registry
docker tag <image> username/repository:tag

# Upload tagged image to registry
docker push username/repository:tag

# Run image from a registry
docker run username/repository:tag


相關文章