Setting up MySQL docker container with local connection

Scenario

Things happen when I need to have multiple mysql versions on my macbook, and I foudn taht the homebrew's version is not good enough. I cannot start a mysql process. So I want docker to fix the issue.

Solution

Pull the latest mysql image


docker pull mysql/mysql-server:latest

Run docker container based on docker image


docker run --name mysql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -v /docker/mysql_data:/var/lib/mysql mysql/mysql:5.6

Parameter explanation

--name mysql: your container name, I set this to mysql56

-d: run the container at the background and return the contianer ID

-p 3306:3306: former port stands for local port, and latter port is the container port. By default the mysql port on docker container is 3306

-e MYSQL_ROOT_PASSWORD=123456: you can set your own root password

-v /docker/mysql_data:/var/lib/mysql: map the folder in container to the local path, please make sure that on Mac you have permitted the folder in GUI. This is for data persistance usage.

mysql/mysql:5.6: this defines that I want to use mysql 5.6 version. You can check the tag name you want on the docker hub website.

[optional]--restart always: always restart the ocntainer when the container exit.

Check the current running cotainer


docker ps

Get into the container with bash



docker exec -it mysql56 bash

mysql -uroot -p

Grant permission for external login

You still cannot login to the mysql container externally because for now the mysql only permit user from localhost, e.g. [email protected], you need to type:


GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'your_password' WITH GRANT OPTION;