简体   繁体   中英

How do I connect from my host to a mysql server running in a docker container?

I am unable to connect from my host(OSX 10.13.6) to a mysql server running in a docker container.

If I start a mysql server(mariadb) on my host (not using docker), I can use the mysql client to successfully connect to the mysql server:

~$ mysql.server start
Starting MariaDB
.200805 13:41:03 mysqld_safe Logging to '/usr/local/var/mysql/My-MacBook-Pro-2.local.err'.
200805 13:41:03 mysqld_safe Starting mysqld daemon with databases from /usr/local/var/mysql
 SUCCESS! 

~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.5.5-10.4.13-MariaDB Homebrew

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mydb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

mysql> select * from people;
+----+--------+------+
| id | name   | info |
+----+--------+------+
|  1 | 7stud  | abc  |
|  2 | Beth   | xxx  |
|  3 | Diane  | xyz  |
|  4 | Kathy  | xyz  |
|  5 | Kathy  | xyz  |
|  6 | Dave   | efg  |
|  7 | Tom    | zzz  |
|  8 | David  | abc  |
|  9 | Eloise | abc  |
| 10 | Jess   | xyz  |
| 11 | Jeffsy | 2.0  |
| 12 | XXX    | xxx  |
| 13 | XXX    | xxx  |
+----+--------+------+
13 rows in set (0.00 sec)

mysql> exit
Bye

~$ mysql.server stop
Shutting down MariaDB
.. SUCCESS! 

Next, if I run a mysql server inside a docker container, I can successfully connect to the mysql server from within the container:

~$ docker run --rm --name my-mysql -e MYSQL_ROOT_PASSWORD=kathy -p 3606:3606 -d mysql
7457d62496b109fda41b57dea026cc6762bb2b7e754cb3e1987228b55ec461f7

~$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                         NAMES
7457d62496b1        mysql               "docker-entrypoint.s…"   2 seconds ago       Up 2 seconds        3306/tcp, 33060/tcp, 0.0.0.0:3606->3606/tcp   my-mysql

~$ docker exec -it my-mysql bash
root@7457d62496b1:/# mysql -u root -p
Enter password: kathy
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.21 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

mysql> exit
Bye
root@7457d62496b1:/# exit
exit
~$ 

But, if I try to connect from my host to the mysql server running in the docker container, I am unsuccessful:

~$ mysql -h 127.0.0.1:3306 -u root -p
Enter password: kathy

ERROR 2005 (HY000): Unknown MySQL server host '127.0.0.1:3306' (0)

~$ docker inspect my-mysql
[
    {
        "Id": "7457d62496b109fda41b57dea026cc6762bb2b7e754cb3e1987228b55ec461f7",
        "Created": "2020-08-05T19:49:32.0561306Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "mysqld"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 7109,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-08-05T19:49:32.4423804Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:0d64f46acfd1af4ee6a162f80c6e07e843761bf14d412060023bf0e69e720fb4",
        "ResolvConfPath": "/var/lib/docker/containers/7457d62496b109fda41b57dea026cc6762bb2b7e754cb3e1987228b55ec461f7/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/7457d62496b109fda41b57dea026cc6762bb2b7e754cb3e1987228b55ec461f7/hostname",
        "HostsPath": "/var/lib/docker/containers/7457d62496b109fda41b57dea026cc6762bb2b7e754cb3e1987228b55ec461f7/hosts",
        "LogPath": "/var/lib/docker/containers/7457d62496b109fda41b57dea026cc6762bb2b7e754cb3e1987228b55ec461f7/7457d62496b109fda41b57dea026cc6762bb2b7e754cb3e1987228b55ec461f7-json.log",
        "Name": "/my-mysql",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "3606/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "3606"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": true,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/bd8cf726bca86b4a5da2253ba4d8fd809e7888bd0a8585337e365f00d4ce0a3c-init/diff:/var/lib/docker/overlay2/d28436ec5b86d97829d4db76ecac79feedf9d7de78be7fac9364b9030e5501c6/diff:/var/lib/docker/overlay2/b4ccb4e64dccd4466971f59b4ddefc0d69943e8a0bb6327dbeccd602d2550378/diff:/var/lib/docker/overlay2/b033c732901687d589a6bd69df8249f661fc9221b8305b32084dfd506dd6014f/diff:/var/lib/docker/overlay2/7078174167da7480c3bea6bf1bb831c1de53479e6c866ac88634ba83560c702e/diff:/var/lib/docker/overlay2/413086cc620e9c9a9bfab7fccaa0cb7e5836419ad52453ae76accf6c9f09be8d/diff:/var/lib/docker/overlay2/0a2c718ad2009d757554e539995cf5901bca5cd1a5ffb9d430ee137fb843adc8/diff:/var/lib/docker/overlay2/00e175c2a0975b7663ccadde84d5bd2f8ea957e9e302ab5c20a9840e34ddd0c5/diff:/var/lib/docker/overlay2/7be82f60f3b9fcb23d0d6336005987dd2c98667622833b58fa9f6362a2a02ba5/diff:/var/lib/docker/overlay2/8c347ec6ae30e0109728c0a056d36b5c64b8f907ec482dc9680bc2d8cfe6e9ad/diff:/var/lib/docker/overlay2/aaf2ed3d56a5312f4daf6efe6f456d95e54cda92e4efe972862c43489d891d3d/diff:/var/lib/docker/overlay2/88bacf56afbf61f9f8c94037a48df63c9fd549682ecf2c446a705ae661f6fe51/diff:/var/lib/docker/overlay2/3b9cf88d35e75201fd69adf020d396d079f7a513b64bd799c118459fe13446af/diff",
                "MergedDir": "/var/lib/docker/overlay2/bd8cf726bca86b4a5da2253ba4d8fd809e7888bd0a8585337e365f00d4ce0a3c/merged",
                "UpperDir": "/var/lib/docker/overlay2/bd8cf726bca86b4a5da2253ba4d8fd809e7888bd0a8585337e365f00d4ce0a3c/diff",
                "WorkDir": "/var/lib/docker/overlay2/bd8cf726bca86b4a5da2253ba4d8fd809e7888bd0a8585337e365f00d4ce0a3c/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "f11c80d7d01140465818fac7d5f7e6083ff509abe8591166a20caa1f568c7646",
                "Source": "/var/lib/docker/volumes/f11c80d7d01140465818fac7d5f7e6083ff509abe8591166a20caa1f568c7646/_data",
                "Destination": "/var/lib/mysql",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "7457d62496b1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "3306/tcp": {},
                "33060/tcp": {},
                "3606/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "MYSQL_ROOT_PASSWORD=kathy",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.12",
                "MYSQL_MAJOR=8.0",
                "MYSQL_VERSION=8.0.21-1debian10"
            ],
            "Cmd": [
                "mysqld"
            ],
            "Image": "mysql",
            "Volumes": {
                "/var/lib/mysql": {}
            },
            "WorkingDir": "",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "d7ae1d7c552ff3bd8e3b457646a314cddad73082d463ccca4c8d67a4c77aa574",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3306/tcp": null,
                "33060/tcp": null,
                "3606/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "3606"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/d7ae1d7c552f",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "a642243a0c85b09821ab0bb4e42d310e02a8c29e4b6949212776938c37d23019",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "ce024a8603c56f96f22700049e12c7687e804c4f1aa00638ed9156ddab36b152",
                    "EndpointID": "a642243a0c85b09821ab0bb4e42d310e02a8c29e4b6949212776938c37d23019",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

~$ mysql -h 172.17.0.2:3306 -u root -p
Enter password: kathy
ERROR 2005 (HY000): Unknown MySQL server host '172.17.0.2:3306' (0)

~$ mysql -h localhost -P 3306 --protocol=tcp -u root -p
Enter password: kathy
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (61)

~$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                         NAMES
7457d62496b1        mysql               "docker-entrypoint.s…"   10 minutes ago      Up 10 minutes       3306/tcp, 33060/tcp, 0.0.0.0:3606->3606/tcp   my-mysql

What am I doing wrong?

Trying Neo Anderson's suggestion:

~$ docker run --rm --name my-mysql -e MYSQL_ROOT_PASSWORD=kathy -p 3306:3306 -d mysql
4cba45a3d758f53256fe88aa9e33ea709a23d0c55c035d4009bbc5685d2e09ee

~$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
4cba45a3d758        mysql               "docker-entrypoint.s…"   4 seconds ago       Up 4 seconds        0.0.0.0:3306->3306/tcp, 33060/tcp   my-mysql

~$ mysql --host=127.0.0.1 -P 3306 --user=root -p
Enter password: kathy 
ERROR 2026 (HY000): SSL connection error: unknown error number

I didn't have docker-machine installed, so I installed it, but I get:

~$ docker-machine ip default
Docker machine "default" does not exist. Use "docker-machine ls" to list machines. Use "docker-machine create" to add a new one.

~$ docker-machine ls
NAME   ACTIVE   DRIVER   STATE   URL   SWARM   DOCKER   ERRORS

. .

Okay, got it! The reason for the SSL connection error :

mysql8 can not be accessed by mysql clients lower then version 8

https://www.digitalocean.com/community/questions/error-2026-hy000-ssl-connection-error-unknown-error-number

On my host, I have mysql version:

~$ mysql --version
mysql  Ver 14.14 Distrib 5.7.10, for osx10.9 (x86_64) using  EditLine wrapper

and I am using the mysql client that came with mysql 5.7.10 to try to connect to the mysql server running in the docker container. But, the image running in the docker container is mysql:latest , and the latest version of mysql is 8.x . To fix everything, I used the docker image mysql:5.7 instead:

~$ docker run --rm --name my-mysql -e MYSQL_ROOT_PASSWORD=kathy -p 56789:3306 -d mysql:5.7
94dfc72013bec3fada45225153974173a816ffc4b8a424eea735d57fecf50c4c

Now I can connect from my host to a mysql server running in a docker container using the mysql 5.7 client on my host:

~$ mysql -P 56789 -u root -p
Enter password: kathy
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

The error there is due to the fact that tcp is not the default protocol, so you can either specify localhost as -h 127.0.0.1 , which implicitly sets the protocol to tcp, or you can explicitly set the protocol with --protocol=tcp :

~$ mysql -h 127.0.0.1 -P 56789 -u root -p
Enter password: kathy

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
  

or:

~$ mysql -P 56789 --protocol=tcp -u root -p
Enter password: kathy

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

By default, the mysql image listens on port 3306.
In your docker run command you are using -p 3606:3606 . This creates a DNAT rule from your host 3606 to the container on the same port - where no service is listening.

Try to start the container with this command(note that the source can be any port that is not in use on your host - in the example below I kept your initial port 3606):

docker run --rm --name my-mysql -e MYSQL_ROOT_PASSWORD=kathy -p 3606:3306 -d mysql

To connect with the mysql client from the host to the container, add the -P (port) and specify explicitly that you are not using the default port:

mysql --host=127.0.0.1 -P 3606 --user=root -p

If this still does not work, run docker-machine ip default on your Mac and replace 127.0.0.1 with that IP address.

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