我有一个项目,其中有3个容器,将由我们的Jenkins构建系统运行。我已经让这3个容器可以相互通信了,现在我需要弄清楚是否正在进行同步构建,我该如何在docker-compose中使用某种类型的UUID或随机生成的网络名称?我需要这样做,这样它们的容器才不会意外地与来自不同构建的其他类似名称的容器对话。
有没有办法在docker-compose文件中创建一个随机生成的名字?
发布于 2018-12-22 17:13:56
假设您的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}
使用docker compose
根据当前的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
https://stackoverflow.com/questions/53889105
复制