9

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.

1 Answer 1

8

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

1
  • this example works pretty good also for compose version 2.4 using the previous syntax
    – Evhz
    Oct 23, 2021 at 9:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .