I have two services in my docker-compose file. One for Python django app and another for mysql database. When I use same network for both containers, the django app can connect with the database without any error but whenever I use different networks for them the django can not connect with mysql.
Now my question is -
How to connect multiple containers running in different networks
Docker Compose file:
mysql_database:
image: mysql_db:latest
container_name: mysql_db
command:
mysqld --default-authentication-plugin=mysql_native_password
volumes:
- "/mysql:/var/lib/mysql-files"
ports:
- "3306:3306"
restart: always
stdin_open: true
tty: true
environment:
- MYSQL_HOST=localhost
- MYSQL_PORT=3306
- MYSQL_DATABASE=myDataBase
- MYSQL_USER=myname
- MYSQL_PASSWORD=somepassword
- MYSQL_ROOT_PASSWORD=somepassword
networks:
mysql_network:
ipv4_address: 172.16.0.18
django_app:
image: backend_app:latest
container_name: backend_app
build:
context: .
dockerfile: Dockerfile
tty: true
ports:
- "8000:8000"
volumes:
- ./my_backend_app:/code/
networks:
- backend_network
depends_on:
- mysql_database
links:
- mysql_database
command: >
bash -c "apt update
&& apt install python3-dev
&& source ./venv/bin/activate
&& python manage.py makemigrations
&& python manage.py migrate
&& python manage.py runserver 0.0.0.0:8000"
networks:
backend_network:
driver: bridge
mysql_network:
driver: bridge
ipam:
config:
- subnet: 172.16.0.0/16
volumes:
my_backend_app:
You can add multiple networks to a single service. In this case you need to add the mysql_network to the django_app:
networks:
- backend_network
- mysql_network
See the docker-compose network documentation for more details on this topic