docker-compose 运行 多次与不同的项目名称并行但不重建

docker-compose run multiple times in parallel with different project names but without rebuilding

在我们的 Jenkins CI 中,我们正在 运行 并行进行端到端集成测试(使用 3 个 docker-compose 运行-命令)。分离通过为每个调用分配单独的项目名称来实现,但是这会导致所有容器都被重建(因为它们的项目名称不同)。有什么办法可以避免吗?

那么我们实际需要的是:

我们基本上是这样做的:

这里基本上是我们的 docker-compose 文件:

version: '3'
services:
  db:
    environment:
      - POSTGRES_PASSWORD=foo
      - POSTGRES_USER=foo
      - POSTGRES_DB=foo_test
  backend:
    build:
      context: ../backend
      dockerfile: .docker/Dockerfile
    command: /workspace/.docker/start_end2end.sh
    depends_on:
      - db
      - redis
    volumes:
      - ./e2e.env:/.env
  cypress:
      ipc: host
      build: 
        context: ../tests
        dockerfile: Dockerfile
      volumes:
        - ../tests/cypress:/app/code/cypress
      depends_on:
        - backend
        - frontend
      environment:
        - CYPRESS_baseUrl=http://frontend:4200
        - CYPRESS_defaultCommandTimeout=10000
        - CYPRESS_RETRIES=3
        - NO_COLOR=1
  frontend:
    build:
      context: ../frontend
      dockerfile: .docker/Dockerfile
    command: /workspace/.docker/start_end2end.sh
    depends_on:
      - backend
    environment:
      - BACKEND_HOST=backend

这是 Jenkinsfile 中的相关部分:

stage('Building containers') {
    steps {
        sh "docker-compose -f ./shared/docker-compose.yml -f ./tests/docker-compose.override.yml build"
    }
}
parallel {
    stage('End2End Tests 1') {
        steps {
            sh "docker-compose -f ./shared/docker-compose.yml -f ./tests/docker-compose.override.yml -p ${env.JOB_NAME}_${env.BUILD_ID}_1 run --rm cypress npm run end2end:1"
        }
    }
    stage('End2End Tests 2') {
        steps {
            sh "docker-compose -f ./shared/docker-compose.yml -f ./tests/docker-compose.override.yml -p ${env.JOB_NAME}_${env.BUILD_ID}_2 run --rm cypress npm run end2end:2"
        }
    }
    stage('End2End Tests 3') {
        steps {
            sh "docker-compose -f ./shared/docker-compose.yml -f ./tests/docker-compose.override.yml -p ${env.JOB_NAME}_${env.BUILD_ID}_3 run --rm cypress npm run end2end:3"
        }
    }
}

我无法存档我上面描述的内容,只有:

docker compose file reference for the build section

中指定

If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:

build: ./dir
image: webapp:tag

因此,无论当前项目名称如何,如下所示的内容始终会为所有具有相同名称的服务构建图像,并在调用 docker-compose up 时默认使用这些图像(如果它们已经存在)。

services:
  service1:
    image: my_service1:1.0.0
    build:
      context: ../service1
      dockerfile: .docker/Dockerfile
  service2:
      image: my_service2:1.0.0
      build: 
        context: ../service2
        dockerfile: Dockerfile
  service3:
      image: my_service3:1.0.0
      build:
        context: ../service3
        dockerfile: path/to/another/Dockerfile

此示例稍后可以根据您自己的需要进行扩展(例如,通过在环境文件中传递标记...)