Ravenix
Ravenix

Reputation: 1030

Unable to connect two dockers together, one database, one .net core application

I'm building an api with .NET Core and MySQL and it's all done. I am now setting it up in Docker. First I've set up the application in Docker connecting to the database running locally on my laptop. I'd had to add --add-host=docker:<My local IP-address> to the run command to connect to the database and change the Connection String to <My local IP-address>.

Now I want to have the MySQL database in a separate Docker instance. I run it by doing:

docker run -p 3306:3306 --name mysqlserver --expose 3306 -e MYSQL_ROOT_PASSWORD=password -e MYSQL_ROOT_HOST=% -d mysql/mysql-server


I can connect to this Docker database from my local machine by

mysql -h 127.0.0.1 -P 3306 -u root -p

Which works fine.

Now I want to connect to this database from my API in another Docker instance. I do use the --link option to link the containers together:

sudo docker run -p 5000:5000/tcp --link mysqlserver:mysql -it --rm apimysql

It starts fine but gives an exception that it cannot connect to the database. I think the problem is in the connection string. I don know what the correct IP-Address/Hostname is for the server that I have to connect with. This is my connection string:

"DefaultConnection":"Server=127.0.0.1;Uid=root;Pwd=password;Database=webapi;"

Upvotes: 2

Views: 198

Answers (1)

Ravenix
Ravenix

Reputation: 1030

I was just stupid for using 127.0.0.1 in the Connection String. I portforwarded 3306 to localhost so I thought; "I can use that in my connection string." But then localhost is not localhost in that docker. So I checked the Ip Address of the running MySQL container by:

sudo docker inspect mysqlserver | grep IPAddress

And then used that IP address in the connection string:

"DefaultConnection":"Server=172.17.0.2;Uid=root;Pwd=password;Database=webapi;"

I started the application and everything worked like a charm.

Upvotes: 2

Related Questions