Dockerfile
容器container自定義的安裝
由一行行命令語句組成,並且支援以 # 開頭的註解行。
他大致上會擁有四個東西
- 基底映像檔
- 維護者(非必要)
- 操作指令
- 容器啟動時執行指令(不一定每個都有)
建置流程
建立一個目錄
使用 cd 指令進入到該目錄
建立一個檔案名稱為
Dockerfile編輯該檔案內容如下
# 使用一個image為基底 FROM python:2.7-slim # 維護者 MAINTAINER william [email protected] # 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 -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"]依照不同application建立相關部署檔案, 以Python為例
requirements.txtFlask Redisapp.pyfrom 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)建立App的Docker image, 並命名為
friendlyhellodocker build -t friendlyhello .查詢在本地端建立好的Docker image
$ docker images REPOSITORY TAG IMAGE ID friendlyhello latest 326387cea398運行使用該Docker image 運行 container 並指定將Host主機的 4000 Port 對應到 Container的80 Port
docker run -p 4000:80 friendlyhelloYou should see a notice that Python is serving your app at
http://0.0.0.0:80. But that message is coming from inside the container, which doesn’t know you mapped port 80 of that container to 4000, making the correct URLhttp://localhost:4000.Go to that URL in a web browser to see the display content served up on a web page, including “Hello World” text, the container ID, and the Redis error message.
