Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

docker-compose: Sharing container between multiple projects by using the same container_name

I want to use a MySQL docker container for multiple projects running on the same server.

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

The second application has a similar docker-compose.yml file, but with app2 instead of app1.

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.

What can I do to share the MySQL container between multiple docker projects?

question from:https://stackoverflow.com/questions/45915182/docker-compose-sharing-container-between-multiple-projects-by-using-the-same-co

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

In order to do so, create a network:

docker network create shared

Assign your network to your mysql container:

version: '3'
services:
  mysql:
    ...
    networks:
    - shared
networks:
  shared: 
    external:
      name: shared

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...