Search code examples
pythonmysqldockermysql-connector-python

Accessing a Database in a Container


I have a python-app dockerized in a container(windows 10 for now), which connects to a MySQL8.0 DB, loads and manipulates data, converts to xml and publishes them with MQTT. Although a docker novice with some trouble understanding, i built a simple image and container for the python-app alone. Problem is, me and my team may want to place the DB inside the docker. Is it possible to insert the tables/data in our DB in a docker-container ?

There are docker-images for all DB's online but i failed to pass the DB we use with the data and the tables. Access host database from a docker container I searched before and i found some interesting posts but none answer my question exactly

Here is the part of the code tha connects to db :

conc = mysql.connector.connect(user='root3r', password='**********', host='******',
                               database='sql_data', auth_plugin='mysql_native_password')

If the DB is inside the container, WHAT IP should i pass in the host argument ?

EDIT : Ok after many trials i used command "docker-machine ip" and THAT IP worked for me, so my local app, managed to connect to the Dockerised-DB BUT i cannot connect from any other remote machine with the same python.app

Is docker-machine IP visible only for the docker host ?


Solution

  • If you're using docker-compose Docker will make aa internal network between all composed containers. In this case you can pass name of the container as a host. For example in docker-compose.yml file there are 2 containers runnning:

    version: "3.2"
    services:
      api:
        image: python
      db_container_name:
        image: postgres
    

    You can make a HTTP call from api to db container with something like:

    conc = mysql.connector.connect(user='root3r',password='**********',hostst='db_container_name',database='sql_data',auth_plugin='mysql_native_password') ```