美文网首页容器技术
二十三、练习:构建Flask镜像

二十三、练习:构建Flask镜像

作者: InsaneLoafer | 来源:发表于2021-12-08 12:45 被阅读0次

    1. 准备flask文件

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    

    2. 准备Dockerfile

    FROM python:3.9.5-slim
    COPY app.py /zhangtao/app.py
    RUN pip3 install flask
    WORKDIR /zhangtao
    ENV FLASK_APP=app.py
    CMD ["flask","run"]
    

    3. 构建镜像

    [root@localhost zhangtao]# docker image build -f Dockerfile -t flask-demo .
    Sending build context to Docker daemon  3.698MB
    Step 1/6 : FROM python:3.9.5-slim
    3.9.5-slim: Pulling from library/python
    b4d181a07f80: Downloading [========================>                          ]  13.04MB/27.15MB
    a1111a8f2ec3: Download complete
    445d04774519: Download complete
    24f3f85d41f3: Download complete
    d299f7fb612d: Download complete
    

    4. 运行容器

    [root@localhost zhangtao]# docker container run -d flask-demo
    30324fee8eaaf5e9e4dc3d0f9d9cab33240ad0198e9c9c27e6c235e619202213
    [root@localhost zhangtao]#
    [root@localhost zhangtao]# docker container ls
    CONTAINER ID   IMAGE        COMMAND                  CREATED         STATUS         PORTS                               NAMES
    30324fee8eaa   flask-demo   "flask run"              7 seconds ago   Up 6 seconds                                       determined_galois
    f82028e4f127   nginx        "/docker-entrypoint.…"   2 weeks ago     Up 2 weeks     0.0.0.0:80->80/tcp, :::80->80/tcp   condescending_brattain
    

    5. 进行端口转发

    • 修改Dockerfile
    FROM python:3.9.5-slim
    
    COPY app.py /zhangtao/app.py
    
    RUN pip3 install flask
    
    WORKDIR /zhangtao
    ENV FLASK_APP=app.py
    
    EXPOSE 5000
    
    CMD ["flask", "run", "-h", "0.0.0.0"]
    
    • 重新构建镜像
      docker build -t flask-demo .

    • 重新运行容器

    [root@localhost zhangtao]# docker container run -d -p 5000:5000 flask-demo
    3533523e34335212bad30537494dba3bb4caa2563222f49081d73988a5d19660
    [root@localhost zhangtao]#
    [root@localhost zhangtao]# docker container ls
    CONTAINER ID   IMAGE        COMMAND                  CREATED         STATUS         PORTS                                       NAMES
    3533523e3433   flask-demo   "flask run -h 0.0.0.0"   6 seconds ago   Up 5 seconds   0.0.0.0:5000->5000/tcp, :::5000->5000/tcp   quizzical_herschel
    f82028e4f127   nginx        "/docker-entrypoint.…"   2 weeks ago     Up 2 weeks     0.0.0.0:80->80/tcp, :::80->80/tcp           condescending_brattain
    

    6. 访问5000端口

    image.png

    相关文章

      网友评论

        本文标题:二十三、练习:构建Flask镜像

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