Docker Community Forums

Share and learn in the Docker community.

Connecting Arduino to Mysql Database running in Docker

Hello,

Anyone know how to connect Arduino to mysql databse running in docker.

What ip should i enter in the below code when connecting to mysql server?
char server = “ip1.ip2.ip3.ip4”;

Please help anyone

Install Docker
You can install Docker in almost all primary OS, be it Linux, Windows, or macOS. Please follow the instruction given in the official docker site to install Docker in your local machine: Install Docker Engine | Docker Documentation
Install and Start Dockerized MySQL
Docker containers are stateless. So, if you use a Containerized MySQL, then you will lose all your saved Data once you restart the container. One way to avoid the issue is to create a docker volume and attach it to your MySQL container. Here are the commands to create a MySQL container including attached volume in your local machine:
The following command will create the volume in your local machine which you can connect with MySQL container later:
λ docker volume create mysql-volume
mysql-volume
The following command will pull the MySQL server version 8.0.20 from the Docker registry and then instantiate a Docker container with the name “mk-mysql.” It will also attach the previously created volume “mysql-volume” with the Database and will expose the port 3306 so that you can reach the MySQL database outside the container:
λ docker run --name=mk-mysql -p3306:3306 -v mysql-volume:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql/mysql-server:8.0.20
Unable to find image ‘mysql/mysql-server:8.0.20’ locally
8.0.20: Pulling from mysql/mysql-server
You can check whether the container is running by listing the running containers:
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d54e7992094b mysql/mysql-server:8.0.20 “/entrypoint.sh mysq…” Less than a second ago Up 4 seconds (health: starting) 0.0.0.0:3306->3306/tcp, 33060/tcp mk-mysql
You can also check the log file of the running MySQL container with the following command:
λ docker logs mk-mysql
Now, you can connect to the container’s interactive bash shell with the following command:
λ docker exec -it mk-mysql bash
bash-4.2#
Once you are inside your container, you can connect to your MySQL server and create a new Database as follows:
bash-4.2# mysql -u root -p
Enter password:

mysql> CREATE DATABASE MYSQLTEST;
Query OK, 1 row affected (0.00 sec)
Please note that you have to give the same password we have defined to run the container (my-secret-pw).
By default, MySQL restricts connection other than the local machine (here Docker container) for security reasons. So, to connect from the local machine, you have to change the connection restriction:
mysql> update mysql.user set host = ‘%’ where user=’root’;
Query OK, 1 row affected (0.02 sec)
Although for security reasons, it would be better to create a new non-admin user and grant access to that user only.