简体   繁体   English

将使用 docker-compose 创建的容器连接到使用 docker run 创建的另一个容器

[英]Connect container created with docker-compose to another one created with docker run

I have the following container created with docker-compose (php:7.2.20-apache):我使用 docker-compose (php:7.2.20-apache) 创建了以下容器:

version: "3"
services
  php72:
    build:
     context: .
    ports:
      - 80:80
    volumes:
      - ./www:/var/www/html

And I have the following container created with docker run:我使用 docker run 创建了以下容器:

docker run --name mysql5 -p 3306:3306 -v mysql5-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7.27

I can connect to the mysql with MySQL Workbench, but my applications in the first container (php7 created with docker-compose) can't connect to the database with same connection credentials.我可以使用 MySQL Workbench 连接到 mysql,但是我在第一个容器(使用 docker-compose 创建的 php7)中的应用程序无法使用相同的连接凭据连接到数据库。

How to solve this?如何解决这个问题?

PS: It`sa test of a dev environment in MacOs PS:这是在 MacOs 中测试开发环境

You could manage a user-defined bridge for them to communicate with each other, see this , detail as next:您可以管理一个用户定义的网桥让他们相互通信,请参阅此内容,详细信息如下:

1. Create a user-define bridge 1.创建一个用户定义的桥

$ docker network create my-net

2. Link mysql container to this network 2. 将mysql容器链接到这个网络

$ docker run --name mysql5 -p 3306:3306 -v mysql5-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7.27
$ docker network connect my-net mysql5

3. Configure docker-compose to use the network 3.配置docker-compose使用网络

version: "3"
services
  php72:
    build:
     context: .
    ports:
      - 80:80
    volumes:
      - ./www:/var/www/html

networks:
  default:
    external:
      name: my-net

Then, from this :然后,从这个

User-defined bridges provide automatic DNS resolution between containers.用户定义的网桥提供容器之间的自动 DNS 解析。

You can visit each other with service name or container name.您可以使用服务名称或容器名称相互访问。

First make sure that you use the correct address in php:7.2.20-apache container for the database as your MySQL Workbench most likely use different ip address (eg 127.0.0.1) than the php:7.2.20-apache container (eg 172.19.0.1)首先确保您在 php:7.2.20-apache 容器中为数据库使用正确的地址,因为您的 MySQL Workbench 很可能使用与 php:7.2.20-apache 容器(例如 172.19)不同的 IP 地址(例如 127.0.0.1) .0.1)

Make sure the containers are on same network by listing your networks with通过列出您的网络,确保容器在同一网络上

docker network ls

And if they are not, connect them to same one with如果不是,请将它们连接到同一个

docker network connect

Usage: docker network connect [OPTIONS] NETWORK CONTAINER (See 'docker network connect --help' for more info.)用法:docker network connect [OPTIONS] NETWORK CONTAINER(有关更多信息,请参阅“docker network connect --help”。)

You can get more info about each network with command您可以使用命令获取有关每个网络的更多信息

docker network inspect

Usage: docker network inspect [OPTIONS] NETWORK [NETWORK...]用法:docker network inspect [OPTIONS] NETWORK [NETWORK...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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