6

I am building on two projects which share some common data. The services of the two projects are built from two docker-compose YML files. I want to access the MySQL server specified in one stack from the Python script running on the other stack.

I am doing so by connecting to an internal docker IP. However, I have found that after server restart, the IP changes. I have tried connecting by container-name, or "linking" container name in docker-compose YML file. Both does not work. I think sharing one docker network interface between two stacks should solve the problem.

May I know how to specify the "network" in the two docker-compose YML file?

Or, is there any better way to achieve this?

Thanks.

ロジャー
  • 203
  • 3
  • 8

1 Answers1

5

Create a network outside of your compose files (this avoids dependencies on the order of either compose file being deployed):

$ docker network create dbnet

Then place the services you want to connect to each other on this external network. E.g. the compose file for mysql could be:

version: '3.5'

networks:
  dbnet:
    external: true
    name: dbnet

services:
  mysql:
    networks:
    - dbnet

And your other compose file would connect to the same network:

version: '3.5'

networks:
  dbnet:
    external: true
    name: dbnet

services:
  pythonapp:
    networks:
    - dbnet

From pythonapp, you connect to the DB as "mysql" (the service name) rather than IP. Docker will handle the DNS resolution for you as long as the containers are on the same network.

Note I've used the 3.5+ syntax for defining external networks. Before this the syntax was:

networks:
  dbnet:
    external:
       name: dbnet

For more details, see: https://docs.docker.com/compose/compose-file/#external-1

BMitch
  • 5,189
  • 1
  • 21
  • 30
  • this example works pretty good *also* for compose version `2.4` using the **previous** syntax – Evhz Oct 23 '21 at 09:32