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:
# 使用Python官方镜像作为镜像的基础
FROM python:2.7-slim
# 设置工作空间为/app
WORKDIR /app
# 把当前目录下的文件拷贝到 容器里的/app里
ADD . /app
# 安装requirements.txt中指定的依赖
RUN pip install -r requirements.txt
# 开放80端口
EXPOSE 80
# 设置 NAME 这个环境变量
ENV NAME World
# 当容器启动时,运行app.py
CMD ["python", "app.py"]
docker build -t flaskhello .
docker images
docker run -p 4000:80 flaskhello
后台运行,获得一个容器的ID
docker run -d -p 4000:80 flaskhello
看到缩短的容器ID:
docker ps
网页访问
http://localhost:4000
分享你的镜像
账号注册
test2018
aaaaaa
//登陆
docker login
给镜像打标签
docker tag flaskhello test2018/flaskapp:demo
推送到远端
docker push test2018/flaskapp:demo
随时随地都可以执行
docker run -p 4000:80 test2018/flaskapp:demo