Docker Compose:更改 COMPOSE_PROJECT_NAME 而不重建应用程序

Sri*_*esh 5 docker docker-compose

概括

我有一个应用程序 X,我想在同一操作系统中部署同一应用程序的多个实例(端口号将由 .env 处理),而无需build为每个实例启动 。

我尝试过的

所以我设法动态地(通过用户更改 .env 文件)更改container_name容器的。但是我们不能同时运行 5 个实例(即使端口不同,docker 也会停止第一个实例并为第二个实例重新创建容器)

接下来我发现COMPOSE_PROJECT_NAME这似乎有效,但开始了一个新的构建。


COMPOSE_PROJECT_NAME=hello-01

docker-compose up
Creating network "hello-01_default" with the default driver
Building test
Step 1/2 : FROM ubuntu:latest
 ---> 113a43faa138
Step 2/2 : RUN echo Hello
 ---> Using cache
 ---> ba846acc19e5
Successfully built ba846acc19e5
Successfully tagged hello-01_test:latest
WARNING: Image for service test was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating hello-01_test ... done
Attaching to hello-01_test
hello-01_test exited with code 0
Run Code Online (Sandbox Code Playgroud)

COMPOSE_PROJECT_NAME=hello-2

docker-compose up
Creating network "hello-02_default" with the default driver
Building test
Step 1/2 : FROM ubuntu:latest
 ---> 113a43faa138
Step 2/2 : RUN echo Hello
 ---> Using cache
 ---> ba846acc19e5
Successfully built ba846acc19e5
Successfully tagged hello-02_test:latest
WARNING: Image for service test was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating hello-02_test ... done
Attaching to hello-02_test
hello-02_test exited with code 0
Run Code Online (Sandbox Code Playgroud)

源文件

docker-compose.yml

version: '3'
services:
  test:
    container_name: "${COMPOSE_PROJECT_NAME}_test"
    build: .
Run Code Online (Sandbox Code Playgroud)

.env

COMPOSE_PROJECT_NAME=hello-02
Run Code Online (Sandbox Code Playgroud)

Dockerfile

FROM ubuntu:latest
RUN echo Hello
Run Code Online (Sandbox Code Playgroud)
Ubuntu 18.04.1 LTS 
Docker version 18.06.0-ce, build 0ffa825
docker-compose version 1.21.2, build a133471
Run Code Online (Sandbox Code Playgroud)

Bil*_*son 3

通过更改容器名称而不提供引用,image:撰写文件不会知道您已经构建了该映像。因此,如果您将该 docker 映像构建为某些本地映像example/image/local, you can add: example/image/local to your docker-compose file and do that to spawndocker-compose up -d` 通过在示例中使用环境变量更改名称多次。

然而,看来您可能想考虑使用副本,而不是在您从 docker-compose 中得到的一行完整内容之外将其变成一项可怕的手动工作。

https://docs.docker.com/compose/compose-file/#short-syntax