美文网首页
Python Flask项目在Gitlab CI中自动打包Doc

Python Flask项目在Gitlab CI中自动打包Doc

作者: llkevin13579 | 来源:发表于2022-01-26 00:53 被阅读0次

第一步,在Gitlab中新建一个项目

第二步,克隆支本地

第三步,本地调通Python Flask项目

用VSCode打开该项目,先用flask在app.py下写了一个hello world:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')

def index():

    return render_template('index.html')

if __name__ == '__main__':

    app.run(port=5000, debug=True)

然后在index.html中写下hello world,放在templates目录下:

<html>

    <head></head>

    <body>

        <div>Hello World</div>

    </body>

</html>

安装flask依赖

pip3 install flask

用以下命令进行本地运行

python3 app.py

打开浏览器进入localhost:5000即可看到Hello World

本地调试成功

第四步,本地调通Docker打包与容器运行

于是尝试利用docker打包成镜像,由于该项目依赖flask库,所以在根目录添加了requirements.txt文件,里面标明了依赖库以及相应的版本

Flask==2.0.2

然后编写好了Dockerfile

FROM python:3

COPY . /app/

RUN pip install -r /app/requirements.txt

WORKDIR /app

EXPOSE 5000

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

运行命令开始打包:

docker build -t flask-gitlab-ci-build-docker:latest .

打包成功,运行容器:

docker run -d -p 80:5000 flask-gitlab-ci-build-docker:latest

在浏览器浏览localhost没有响应

查看日志发现没有报错

再尝试用浏览器打开127.0.0.1,也不行

网上搜索发现python flask在服务器不能直接运行,需要借助gunicorn

于是编写了配置文件gunicorn.conf.py:

workers = 5 # 定义同时开启的处理请求的进程数量,根据网站流量适当调整

worker_class = "gevent" # 采用gevent库,支持异步处理请求,提高吞吐量

bind = "0.0.0.0:5000" # 监听IP放宽,以便于Docker之间、Docker和宿主机之间的通信

同时修改了Dockerfile:

FROM python:3

COPY . /app/

RUN pip install -r /app/requirements.txt

WORKDIR /app

EXPOSE 5000

CMD ["gunicorn", "app:app", "-c", "./gunicorn.conf.py"]

以及修改了依赖包requirements.txt:

blinker==1.4

Flask==2.0.2

gevent==21.12.0

gunicorn==20.1.0

再打包镜像、运行容器,发现可以正常运作了:

第五步,Gitlab CI设置脚本自动打包Docker镜像

stages:

   - buildAndDeploy

buildAndDeploy:

  stage: buildAndDeploy

  image: docker:latest

  script:

    - docker login -u ${docker_registry_username} -p ${docker_registry_password} ${docker_registry_organization_qa}

    - docker build -t ${docker_registry_organization_qa}/${docker_registry_project}:$CI_COMMIT_SHORT_SHA .

    - docker push ${docker_registry_organization_qa}/${docker_registry_project}:$CI_COMMIT_SHORT_SHA

由于自建Docker镜像仓库和账号是隐私信息,因此使用Gitlab CI变量代替,再在项目CI/CD设置内赋值

相关文章

网友评论

      本文标题:Python Flask项目在Gitlab CI中自动打包Doc

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