How to connect to MySQL database using the hostname?

I am currently connecting to the Mysql database using a hardcoded IP address for the mysql container in the XBlocks.

This is not a great practice as every time the devstack is restarted the ip addresses change and I have to manually change the IP address in all the xblocks.

Is there a way to connect to the Mysql service using the hostname or dynamically retrieve the ip address in the xblocks. (This is preferable)

If not then secondly is there a way to have a fixed IP address everytime the devstack services start?

@prithviraj-chaudhuri What is your use case for accessing MySQL directly?

Generally it’s preferable to not access the MySQL server directly within XBlocks - they have their own mechanism for storing data, which is stored in the database independently, by the XBlock runtime.

That said, there are some cases where accessing MySQL directly can be necessary, when the XBlock API doesn’t allow your use-case, or not easily - for example to share data between different instances of XBlocks. In that case, you would probably still not want to access the MySQL server directly, but instead use the Django database API, either to access your own data structures, or ones defined in other parts of the Open edX project. This will use the server settings for database access, so you won’t have to deal with this. Note however that this isn’t part of the official XBlock API, so it is unsupported.

My Use case was to share data between XBlock Instances, additionally, we added some custom tables to collect certain custom logs about user activity. I will take a look into the Django database API. Will the Django database API be able to connect to a custom table in OpenEdx.

Yes, you can create a Django app and models specific to your XBlock. See an example of this in the Problem Builder XBlock for example. If you are unfamiliar with Django, going through the Django tutorial could be helpful.