關於網路那些事...

網路行銷,SEO,網路趨勢,教學文章,網頁設計,生活時事

Docker - Get Start Part 2. Containers

這裡記錄 Containers 實作流程

在這裡按照下方流程就能快速建立出一個 python demo web

預計將專案放置在 docker_project/get_started/

建立檔案: 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"]

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)

這時,在資料夾內包含了 Dockerfile, app.py, requirements.txt 這三個檔案

透過下方指令建立 Docker image

docker build -t friendlyhello .

Docker 背景執行 friendlyhello

docker run -d -p 4000:80 friendlyhell

開啟瀏覽器,前往 http://0.0.0.0:4000

查看運行中的 container

docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
7dbb951f29b6        friendlyhello       "python app.py"     49 seconds ago      Up 54 seconds

停止運行指定的 docker

docker container stop 7dbb951f29b6

重新啟動

docker restart 7dbb951f29b6

關閉

docker stop 7dbb951f29b6

登入 Docker,輸入下方指令,並填寫帳號密碼登入你的 Docker

Docker login

註冊你的 images

docker tag image username/repository:tag

舉例來說:

docker tag friendlyhello gordon/get-started:part2

查看 images

$ docker image ls

REPOSITORY               TAG                 IMAGE ID            CREATED             SIZE
friendlyhello            latest              d9e555c53008        3 minutes ago       195MB
gordon/get-started         part2               d9e555c53008        3 minutes ago       195MB
python                   2.7-slim            1c7128a655f6        5 days ago          183MB

將 image 上傳

docker push gordon/get-started:part2

執行遠端的 repository

docker run -d -p 4000:80 gordon/get-started:part2

如果你喜歡我們的文章內容,請在這裡按個讚



最新文章推薦