docker-compose:通过使用相同的 container_name 在多个项目之间共享容器 [英] docker-compose: Sharing container between multiple projects by using the same container_name
问题描述
我想为在同一台服务器上运行的多个项目使用 MySQL docker 容器.
I want to use a MySQL docker container for multiple projects running on the same server.
使用 docker-compose v3 文件,我只是在每个项目中具有相同的 mysql 容器配置,并且它们具有相同的 container_name
:
Using docker-compose v3 files, I simply have the same mysql container configuration in each of the projects, and they have the same container_name
:
version: "3"
services:
app1:
image: foo
links:
- mysql
mysql:
image: mysql/mysql:5.7
container_name: shared_mysql
第二个应用程序有一个类似的 docker-compose.yml
文件,但使用 app2
而不是 app1
.
The second application has a similar docker-compose.yml
file, but with app2
instead of app1
.
当为 app2
运行 docker-compose up --no-recreate
时,出现错误:
When running docker-compose up --no-recreate
for app2
, I get an error:
Creating shared_mysql ... error
ERROR: for shared_mysql
Cannot create container for service mysql: Conflict.
The container name "/shared_mysql" is already in use by container "deadbeef".
You have to remove (or rename) that container to be able to reuse that name.
如何在多个 docker 项目之间共享 MySQL 容器?
What can I do to share the MySQL container between multiple docker projects?
推荐答案
您可以简单地避免在两个 docker-compose.yml 文件之一中重新定义 mysql,并将 mysql 和其他容器连接到同一网络.
You can simply avoid redefining the mysql in one of the two docker-compose.yml files and connect mysql and the other containers to the same network.
为此,创建一个网络:
docker network create shared
将您的网络分配给您的 mysql 容器:
Assign your network to your mysql container:
version: '3'
services:
mysql:
...
networks:
- shared
networks:
shared:
external:
name: shared
对于任何其他需要访问mysql的容器,只需添加与上述相同的网络定义:
For any other container that has need to access mysql, just add the same network definition as above:
version: '3'
services:
app1:
...
networks:
- shared
app2:
...
networks:
- shared
...
networks:
shared:
external:
name: shared
这篇关于docker-compose:通过使用相同的 container_name 在多个项目之间共享容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!