简体   繁体   中英

How to connect to a MySQL container from a different docker container over a docker network

I am trying to connect to a MySQL container from another docker container.

I created a.network:

docker network create netw

I created the MySQL container:

docker run --name oates -e MYSQL_ROOT_PASSWORD=localdb -p 3307:3306 --net=netw -d mysql:latest

I created a container from the official Drupal image:

docker run --name morse -p 8080:80 --net=netw -d drupal:latest

I then enter the Drupal container:

docker exec -it morse /bin/bash

And I attempt a remote connection a few different ways:

mysql -h oates -u root -p
mysql -h oates --port 3307 -u root -p
mysql -h 172.18.0.2 --port 3307 -u root -p

The output is always: "bash: mysql: command not found".

In case I am not using the correct host, here is the IP output if I inspect the mysql container:

$ docker inspect oates | grep IP
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
                    "IPAMConfig": null,
                    "IPAddress": "172.18.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,

It looks to me like there is an IP for the.network but not the MySQL container, but I'm not sure I understand the output.

Notes:

  • I am avoiding the use of --link since that is apparently no longer the preferred approach, and it doesn't seem practical to connect to a newly created container that way.
  • I am new to docker, and it's not yet clear to me that docker compose can be used in an ad hoc way to connect an existing container to another newly created container. But I would be interested to know if it can.

I needed to install mariadb client:

apt update
apt install mariadb-client

Apparently the mariadb client is compatible with mysql-client and is the right client for my Drupal container.

I also was wrong to specify port 3307. I suppose from the Drupal container's perspective, the port is 3306, so no port needs to be specified, and this simple connection string works...

mysql -h oates -u root -p

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