我需要从当前存储库的源代码构建 docker 映像,运行容器,然后执行一些 API 调用。如何通过 github 操作来做到这一点?
name: Docs Generator
on:
pull_request:
types: [opened]
jobs:
pr-labeler:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- name: Get the version
id: vars
run: echo ::set-output name=tag::$(echo ${GITHUB_REF:10})
- name: Build the tagged Docker image
run: docker build . --file Dockerfile --tag service:${{steps.vars.outputs.tag}}
- name: Run docker image
docker run -v ${{ inputs.path }}:/src service:${{steps.vars.outputs.tag}}
- name: Call API
run: |
curl +x http://localhost:8080/test
.....
Run Code Online (Sandbox Code Playgroud)
我们可以通过以下方法来实现这一点。
优点 :
docker/build-push-action构建 docker 并addnab/docker-run-action运行 docker。以下示例显示了单元测试流程。但这个概念与你的流程保持不变。
...
jobs:
unittest:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- uses: docker/setup-buildx-action@v2
- uses: docker/build-push-action@v4
with:
context: .
file: "Dockerfile.test"
tags: localpytest:latest
load: true
cache-from: type=gha
cache-to: type=gha,mode=max
push: false
- name: Run Pytest
uses: addnab/docker-run-action@v3
with:
image: localpytest:latest
run: pytest
Run Code Online (Sandbox Code Playgroud)
addnab/docker-run-action,观察load参数。该值的默认值为false。这必须是true在另一步骤中使用一个步骤中的图像。addnab/docker-run-action,观察push参数为false。所以我们不会将其推送到任何 docker 注册表。为此,您可以结合使用https://github.com/marketplace/actions/build-and-push-docker-images和https://github.com/addnab/docker-run-action
第一个将构建并发布一个容器,第二个将获取该容器并在那里运行命令。
示例如下。我自己没有使用这个设置,但我已经测试过了。替换username/container为您的用户名和容器。
name: Docker Image CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
compile:
name: Build and run the container
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v2
with:
push: true
tags: username/container
- name: Check out the repo
uses: actions/checkout@v2
- name: Run the build process with Docker
uses: addnab/docker-run-action@v3
with:
image: username/container:latest
options: -v ${{ github.workspace }}:/data
run: |
echo "Hello World"
Run Code Online (Sandbox Code Playgroud)
请注意,构建容器是一项相当漫长的任务,并且可能会很快耗尽您的 Github Action 限制。您可能会考虑单独构建/发布容器,或者在此处添加更好的缓存(即仅在 Dockerfile 更改时重建它)
请注意,您需要设置 DOCKERHUB_USERNAME 和 DOCKERHUB_TOKEN 机密。
而不是echo "Hello World"使用您想要运行的命令。/data对于此设置,存储库数据将位于目录中。
| 归档时间: |
|
| 查看次数: |
7379 次 |
| 最近记录: |