利用Docker构建Flask的Hello world

作者: JaeGwen | 来源:发表于2018-06-28 10:40 被阅读4次

    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/

    相关文章

      网友评论

        本文标题:利用Docker构建Flask的Hello world

        本文链接:https://www.haomeiwen.com/subject/vizwyftx.html