我有一个包含3个容器的项目,该项目将由我们的Jenkins构建系统运行。我已经做到了这3个容器可以相互通信,现在我需要弄清楚是否正在同时进行构建,我该如何在docker-compose中使用某种UUID或随机生成的网络名称?我需要这样做,以使它们的容器不会意外地与来自不同内部版本的其他类似名称的容器通信。
是否可以在docker-compose文件中创建随机生成的名称?
答案 0 :(得分:1)
假设您的CI从git中签出您的源代码,则可以使用git-commit用作容器/图像/网络的唯一标识符;例如
# get the sha of the commit that you're building from
export GIT_COMMIT=$(git rev-parse --short HEAD)
# build your image
docker build -t myimage:git-${GIT_COMMIT} .
# create your network
docker network create nw_${GIT_COMMIT}
# start your container
docker run -d --network=nw_${GIT_COMMIT} --name=foo_${GIT_COMMIT} myimage:git-${GIT_COMMIT}
根据当前的git-commit设置项目名称;设置COMPOSE_PROJECT_NAME
环境变量将覆盖默认项目名称(基于当前目录的名称)。还要设置一个GIT_COMMIT
环境变量,以便可以单独使用。
export COMPOSE_PROJECT_NAME=myproject_$(git rev-parse --short HEAD)
export GIT_COMMIT=$(git rev-parse --short HEAD)
创建一个docker-compose.yml
和Dockerfile
version: "3.7"
services:
web:
build:
context: .
args:
GIT_COMMIT:
image: myproject/web:${GIT_COMMIT:-unknown}
Dockerfile:
FROM nginx:alpine
ARG GIT_COMMIT=unknown
RUN echo "This is build ${GIT_COMMIT}" > /usr/share/nginx/html/index.html
在运行之前清理所有内容(同一项目的其他实例;旧版本的映像,卷);
docker-compose down --rmi=all --volumes --remove-orphans
Stopping myproject_a9f48b5_web_1 ... done
Removing myproject_a9f48b5_web_1 ... done
Removing network myproject_a9f48b5_default
Removing image myproject/web:a9f48b5
为您的服务构建图像
docker-compose build
Building web
Step 1/3 : FROM nginx:alpine
---> 315798907716
Step 2/3 : ARG GIT_COMMIT=unknown
---> Running in 78515fcdd331
Removing intermediate container 78515fcdd331
---> bb2414522a62
Step 3/3 : RUN echo "This is build ${GIT_COMMIT}" > /usr/share/nginx/html/index.html
---> Running in 9bf1f2023915
Removing intermediate container 9bf1f2023915
---> 3debb1a96b63
Successfully built 3debb1a96b63
Successfully tagged myproject/web:a9f48b5
然后开始堆栈;
docker-compose up -d
Creating network "myproject_a9f48b5_default" with the default driver
Creating myproject_a9f48b5_web_1 ... done
找到分配给web
服务的随机端口;
docker-compose port web 80
0.0.0.0:32770
并连接到它:
curl localhost:32770
This is build a9f48b5