从另一个容器连接到mysql容器

问题描述:

我正试图从撰写文件指定的同一网络上的另一个容器中连接到mysql容器.

I'm trying to connect to a mysql container from within another container on the same network specified by a compose file.

version: "2"
services:
  web:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "8080:80"
    volumes:
      - ./data:/srv
  php:
    build:
      context: .
      dockerfile: php-fpm/Dockerfile
    volumes:
      - ./data:/srv
  mysql:
    image: mysql
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
      - MYSQL_USER=dummy_user
      - MYSQL_PASSWORD=12345

我不确定我要从php容器连接到mysql容器时,连接参数是什么.

I'm not really sure what the connection parameters would be if I'm trying to connect to the mysql container from the php container.

具体来说,来自 位于同一docker-compose网络中的另一个容器的mysql容器的主机和端口是什么?

Specifically, what are the host and port for the mysql container from within another container of the same docker-compose network?

我尝试使用主机:mysql端口:3306,但这似乎不起作用.

I've tried host: mysql port: 3306, but that doesn't seem to work.

您应该链接容器.将 ports 部分添加到 mysql 容器中,并将 links 部分添加到 php 容器中.

You should link the containers. Add ports section to mysql container and links section to php container.

version: "2"
services:
  web:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "8080:80"
    volumes:
      - ./data:/srv
  php:
    build:
      context: .
      dockerfile: php-fpm/Dockerfile
    links:
      - mysql:mysql
    volumes:
      - ./data:/srv
  mysql:
    image: mysql
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
      - MYSQL_USER=dummy_user
      - MYSQL_PASSWORD=12345

使用该配置,您将可以使用 mysql:3306

With that configuration you'll be able to access mysql container from php with mysql:3306

一些文档: https://docs.docker.com/compose/联网/#updating-containers