Docker php_network_getaddresses错误

我有以下由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();
}

它会抛出以下错误:

Connect failed: php_network_getaddresses: getaddrinfo failed: Name or
service not known

为什么会这样?

.

.

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

最佳答案
当通过PHP(或任何其他)进行连接时,使用容器的名称作为主机,以防万一,这是学习php-mysql.

从而

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

将工作.

转载注明原文:Docker php_network_getaddresses错误 - 代码日志