I have a docker mysql image running, following is what the docker-compose.yml file looks like:
db:
image: mysql
environment:
MYSQL_ROOT_PASSWORD: ""
MYSQL_ALLOW_EMPTY_PASSWORD: yes
ports:
- "3306:3306"
This works fine.
My question is: How can I connect to the MySQL instance running on that container from the command line mysql client on my the host (my macbook)?
To clarify:
- I have a macbook with Docker installed
- I have a docker container with mysql
- I want to connect to the mysql instance running on the aforementioned container from the Terminal on my macbook
- I do NOT want to user a
docker
command to make this possible. Rather, I want to use themysql
client directly from the Terminal (without tunneling in through a docker container).
I don't have MySQL running locally, so port 3306 should be open and ready to use.
The command I am using to start the container is: docker-compose run
Connect to MySQL via {host ip}:3306 since you've exposed the internal port to your host as 3306. If you need to access the MySQL CLI tools you will need to go
docker exec -it mycontainer bash
this will place you inside the container to access the tools installed with MySQL if you do not have them installed locally on the host o/s.If your Docker MySQL host is running correctly you can connect to it from local machine, but you should specify host, port and protocol like this:
Because you are running MySQL inside Docker container, socket is not available and you need to connect through TCP. Setting "--protocol" in the mysql command will change that.
Your yml file looks good.
You can directly connect docker container directly as it already mapped with local port 3306. Just goto terminal and run
Note: you must have access to mysql command line. If mysql command show an error, check '/usr/local/mysql/bin' other wise you can not connect to mysql server. In other word you must have mysql client on your machine.
Using
docker-compose up
Since you published port
3306
on your docker host, from that host itself you would connect to127.0.0.1:3306
.Using
docker-compose run
In that case the port mapping section of the
docker-compose.yml
file is ignored. To have the port mapping section considered, you have to add the--service-ports
option:Additional note
Beware that by default, the mysql client tries to connect using a unix socket when you tell it to connect to
localhost
. So do use127.0.0.1
and notlocalhost
:this worked for me.
I got it!! The answer is to use the
--service-ports
option when runningdocker-compose
:docker-compose run --service-ports db
(the original docker-compose.yml file works fine)Thanks to all for the help!