CI/CD:用 Jenkins 通过 Git Push 触发自动制作 Flask 项目的 Docker 镜像

Flask 项目文件

$ tree flask_docker_jenkins_demo/
flask_docker_jenkins_demo/
├── Dockerfile
├── README.md
└── app.py

app.py

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'


@app.route('/health')
def health_checking():
    ret = {'status': 'UP'}
    return jsonify(ret)

Dockerfile

FROM python:3.6.9-alpine

RUN pip install --no-cache-dir -i http://mirrors.aliyun.com/pypi/simple/ \
--trusted-host mirrors.aliyun.com Flask gunicorn

ADD . /app

ENV GUNICORN_CMD_ARGS="--bind=0.0.0.0:5001 --chdir=./app/ --workers=4"

CMD ["gunicorn", "app:app"]

使用 docker 启动 jenkins :

docker-compose.yml:

version: '3'
services:
  jenkins:
    image: 'jenkins/jenkins'
    container_name: jenkins
    restart: always
    ports:
      - '8080:8080'
      - '50000:50000'
    user: root
    volumes:
      - /root/jenkins/jenkins_home:/var/jenkins_home
      - /usr/bin/docker:/usr/bin/docker
      - /var/run/docker.sock:/var/run/docker.sock

启动过程中会显示初始密码,也会保存在 /var/jenkins_home/secrets/initialAdminPassword 中,启动完成用浏览器访问 8080 端口,用初始化密码解锁 jenkins。

建立构建任务

  • Jenkins -> 新建任务 -> 起名字,构建一个自由风格的软件项目 -> 保存
  • 【源码管理】 -> 【Git】 -> 填写 Github 地址
  • 【构建触发器】 -> 【轮询 SCM】 -> 日程表填写* * * * *
  • 【构建】 -> 【增加构建步骤】 -> 【执行 shell】
    docker build -t my-flask-image:latest .
    a=`docker images -f 'dangling=true' -q | wc -l`
    if [ $a -ge 0 ];then docker rmi $(docker images -f "dangling=true" -q);fi
    
    -> 【保存】

注意

  • docker-compose.yml 里要把 docker 命令和 docker.sock 映射进容器
  • 装插件容易失败,好像不怎么用装插件也可以
  • 无需配置 Publish over SSH
  • 构建触发器的启程表里面是 cron 表达式
  • 如果在 docker build 前已经存在同名镜像,那么在完成后会出现一个无名(dangling)镜像,最后清理一下。

参考:

  • https://medium.com/@angellom/automatically-building-a-flask-docker-image-on-git-push-with-jenkins-5a30c9fc9beb
发布了66 篇原创文章 · 获赞 21 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_35753140/article/details/104076162