To run MySQL server in a Docker container and connect to it from your host machine, follow these steps:
Pull MySQL Image
First, you need to pull the MySQL image. Use the following command to pull the static version 8:
docker pull mysql:8
Run MySQL Container
Next, run the MySQL container using the following command. Note that we are specifying a root password using the -e flag. In this example, we will use “123” as the password.
docker run -d -p 3306:3306 --name mysql-server -e MYSQL_ROOT_PASSWORD=123 mysql:8
The above command will start a MySQL container and run it in the background. You can confirm that the container is running using the following command:
docker ps
This will show you a list of running containers.
Connect to MySQL Container
Now, you can connect to the MySQL container using the MySQL client installed on your host machine. To connect to the MySQL container, use the following command:
mysql -u root -p -h 127.0.0.1 -P 3306
When prompted, enter the root password you specified earlier (in this case, “123”). This will connect you to the MySQL server running inside the container.
Alternatively, you can run a MySQL command inside the container using the following command:
docker exec -it mysql-server mysql -uroot -p -e "SELECT VERSION();"
This will run the SELECT VERSION();
command inside the container and return the version of MySQL that is currently running.
If you want to create a database inside the container, you can run the following command:
docker exec -it mysql-server mysql -uroot -p -e "CREATE DATABASE dbname;"
Replace dbname
with the name of the database you want to create.
Note that if you are using Windows, you may need to specify a different IP address and port when connecting to the MySQL container. You can specify a port mapping when running the container using the -p flag.