简体   繁体   中英

How to connect MySQL client with server running in Docker

I am using Docker first time. I am trying to connect docker based MySQL with my Navicat client. How do I get docker IP and then use it for connection? Here are a few details:

CONTAINER ID        IMAGE                    COMMAND                  CREATED             STATUS              PORTS                                      NAMES
b984b6659d20        mysql:5.7                "docker-entrypoint.sh"   8 minutes ago       Up 7 minutes        3306/tcp                                   myre_mysql_run_1
d34d8974912c        myre_php-apache-engine   "/usr/local/bin/entry"   20 hours ago        Up 7 minutes        80/tcp                                     myre_php_apache_engine_dev
981c2a7fa83b        mysql:5.7                "docker-entrypoint.sh"   20 hours ago        Up 47 seconds       3306/tcp                                   myre_mysql_dev
472531e09d08        jwilder/nginx-proxy      "/app/docker-entrypoi"   20 hours ago        Up 7 minutes        0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   nginx_proxy

If you need to access the mysql container from the outside. Than you need to map the container port on the port of your server (using -p ).

docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=my-secret-pw  -e MYSQL_USER=test -e MYSQL_PASSWORD=test -d mysql:latest

Now you can connect to your container using the IP of your server + the port. In my case I'm in a VLAN. The IP of my server is 192.168.140.30. So eg when I ssh to my server I use that IP. Now I've mapped the port of my container on the port of my server (with -p 3306:3306 which means: map the port 3306 of my container to port 3306 of my server. (so I can use the server IP to connect).

在此处输入图片说明 在此处输入图片说明

If you need use client to connect to MySQL in Docker container you need do port mapping with the host machine.

I see you MySQL container not use mapping the container port to host port so you can not use MySQL client to connect the MySQL server.

You can use -p parameter specify the port mapping. for example if you need use port 3306 to connect to MySQL server, use following command to create the MySQL container. PS: you need change some setting for following command.

docker run --name container-name -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=database-name -e MYSQL_USER=user -e MYSQL_PASSWORD=password  mysql:5.7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM