一,创建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
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)
以上三个文件位于同一目录下
四,Build the app
docker build -t friendlyhello .
通过以下命令查看
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
friendlyhello latest a10e529f7529 29 minutes ago 148MB
五,Run the app
docker run -p 4000:80 friendlyhello
六,验证
访问该机器的4000端口有如下结果
Hello World!
Hostname: c0e1b5bbb181
Visits: cannot connect to Redis, counter disabled