Docker學習筆記(二)容器

文中內容摘自官網

創建容器:

1. Create an empty directory. Change directories (cd) into the new directory, create a file called Dockerfile, copy-and-paste the following content into that file, and save it. Take note of the comments that explain each statement in your new Dockerfile.

    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
COPY . /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"]

2. Create two more files, requirements.txt and app.py

    requirements.txt文件內容如下:

Flask
Redis

    app.py文件內容如下:

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

# Connect to Redis
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)

3. 創建Docker image

    完成上述操作後,可以在新建目錄下看到Dockerfile、requirements.txt、app.py三個文件。在此目錄下執行下列命令即可創建名爲friendlyhello的Docker image。注意,不要遺漏最後的小數點。

$ docker build -t friendlyhello .

    可以用下列語句查看Docker的image列表:

$ docker image ls

REPOSITORY            TAG                 IMAGE ID
friendlyhello         latest              326387cea398

4. 運行app

    Run the app, mapping your machine’s port 4000 to the container’s published port 80 using -p:

docker run -p 4000:80 friendlyhello

    The current URL: http://localhost:4000.

分享容器

1. 登錄Docker Hub

    使用公有容器服務器(免費)

    在hub.docker.com網站,註冊帳號,然後使用下列語句登錄服務器。

$ docker login

    使用私有容器服務器

    使用Docker Trusted Registry可以搭建私有的Docker服務器,詳細資料請參看下面URL:

    https://docs.docker.com/datacenter/dtr/2.2/guides/

2. 標記影像文件

    所有上傳到Docker Hub上的影像文件全部以 username/repository:tag 格式標記的,其中,username是你在Docker Hub上註冊的用戶名,repository是倉庫名,tag是當前影像文件在倉庫中的資源名稱。具體標記的語句格式如下:

docker tag image username/repository:tag

3. 發佈影像文件

    使用下列語句將影像文件上傳到倉庫:

docker push username/repository:tag

4. 下載並運行

    使用下列語句,Docker會先檢查本地有無該影像文件,若沒有,則會自動從倉庫中下載該文件後運行:

docker run -p 4000:80 username/repository:tag

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章