Docker php_network_getaddresses错误

时间:2017-01-28 18:46:28

标签: php mysql docker dockerfile

我正在运行由PHPDocker生成的以下Docker容器:

learn-php-mysql:
  image: mysql:5.7
  container_name: learn-php-mysql
  volumes:
    - "./.data/db:/var/lib/mysql"
  restart: always
  environment:
    MYSQL_ROOT_PASSWORD: learning
    MYSQL_DATABASE: learning
    MYSQL_USER: learning
    MYSQL_PASSWORD: learning

learn-php-webserver:
  image: phpdockerio/nginx:latest
  container_name: learn-php-webserver
  volumes:
    - ./code:/code
    - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
  ports:
   - "8080:80"
  links:
   - learn-php-php-fpm

learn-php-php-fpm:
  build: .
  dockerfile: php-fpm/Dockerfile
  container_name: learn-php-php-fpm
  volumes:
    - ./code:/code
    - ./php-fpm/php-ini-overrides.ini:/etc/php/7.1/fpm/conf.d/99-overrides.ini
  links:
    - learn-php-mysql:mysql

除了尝试通过PHP代码连接MySQL服务器时,一切正常:

$mysqli = new mysqli("db", "learning", "learning", "learning");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

会抛出以下错误:

  

连接失败:php_network_getaddresses:getaddrinfo失败:名称或   服务未知

为什么会这样?

您可以找到此here的存储库。运行docker-compose up时,请转到 http://localhost:8080/classes/serialize.php 以产生相同的错误。

1 个答案:

答案 0 :(得分:8)

通过PHP(或任何其他)建立连接时,请使用容器的名称作为主机,以防 learn-php-mysql

因此

$mysqli = new mysqli("learn-php-mysql", "learning", "learning", "learning");

会工作。