利用Docker构建Flask的Hello world

Docker Version 1.13 or higher
Platform: Raspberrypi 3 arm32v7

Dockerfile

FROM arm32v7/python:2.7-slim

WORKDIR /app

ADD . /app

RUN pip install --trusted-host pypi.python.org -r requirements.txt

EXPOSE 80

ENV NAME World

CMD ["python", "app.py"]

requirements.txt

Flask
Redis

app.py

from flask import Flask
from redis import Redis, RedisError
import os
import socket

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)

目录结构:

$ ls
Dockerfile     app.py    requirements.txt

构建app

docker build -t friendlyhello .

$ docker image ls
REPOSITORY                           TAG                 IMAGE ID            CREATED             SIZE
friendlyhello                        latest              24e6c465d783        34 minutes ago      105MB

运行容器

docker run -itd -p 4000:80 friendlyhello

docker ps -l
CONTAINER ID        IMAGE                            COMMAND                  CREATED             STATUS              PORTS                    NAMES
44daf44bc5c9        friendlyhello                    "python app.py"          33 minutes ago      Up 33 minutes       0.0.0.0:4000->80/tcp     eloquent_ardinghell
屏幕快照.png

参考链接:https://docs.docker.com/get-started/part2/#conclusion-of-part-two

dockerhub: https://hub.docker.com/r/314315960/friendlyhello/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容