首先建立一個新目錄用於存放咱們製做鏡像所需的文件 html
進入到新目錄中 執行touch Dockerfile
建立一個Dockerfile文件,Dockerfile 定義了容器運行的須要的環境,網絡端口、磁盤資源、要執行的命令等等。python
複製如下內容到Dockerfile中web
#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 8081 # Define environment variable ENV NAME World # Run app.py when the container launches CMD ["python", "app.py"]
在新目錄下執行命令 touch requirements.txt
複製如下內容redis
Flask Redis
在新目錄下執行命令 touch app.py
複製如下內容docker
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=8081)
執行命令 docker build --tag=helloworld:v0.0.1 .
構建你的第一個docker鏡像,別忘了命令的最後一個. 。flask
經過下面命令查看您剛剛製做的鏡像網絡
# docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE helloworld v0.0.1 f471662fe76e 2 minutes ago 131MB
該鏡像經過Python代碼啓了一個簡單的web服務,下面開始運行您的鏡像app
#docker run -p 8099:8081 helloworld:v0.0.1 * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://0.0.0.0:8081/ (Press CTRL+C to quit)
看到上面的輸出說明您的docker 鏡像 helloworld 啓動成功,您能夠經過curl命令測試容器是否正在正常運行,docker run -p 其實是將本地的8099端口映射到容器的8081端口。curl
# curl http://localhost:8099 <h3>Hello World!</h3><b>Hostname:</b> a64e25c2a522<br/><b>Visits:</b> <i>cannot connect to Redis, counter disabled</i>
您能夠經過一下命令查看當前機器正在運行的容器socket
# docker container ls CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a64e25c2a522 helloworld:v0.0.1 "python app.py" 7 minutes ago Up 7 minutes 0.0.0.0:8099->8081/tcp frosty_newton