如何让同一个nginx docker容器的两台主机进行通信?

问题描述 投票:0回答:1

我有一个 docker 环境,可以在本地使用两个 php-fpm 容器(php 8.2 和 php 7.4)和一个 nginx Web 服务器。

由于我有多个应用程序,它们在不同版本的 php 上运行,因此我在 nginx 中为每个应用程序创建了一个 .conf 文件,并确定在

fastcgi-pass
指令中使用哪个版本的 php-fpm。

我的问题是,我有两个特定的应用程序,即前端客户端和 api。我在 nginx 中配置了他们的每个主机,我可以像平常一样使用配置的 URL 访问它们。但是,每当我需要让他们相互交流时,它就不起作用。

从 client.localhost 应用程序内部调用 api.localhost 不起作用,并给出错误:

cURL error 7: Failed to connect to api.localhost port 80 after 0 ms: Couldn't connect to server

那么,我应该更改什么,才能使 api.localhost 主机对 client.localhost 应用程序可见?考虑到它们都由同一个 nginx 容器运行?

这是我的conf文件(每个文件之间唯一的区别是php版本,服务器名称和根目录):

server {

    listen 80;
    listen [::]:80;

    server_name api.localhost;
    root /var/www/html/api/public;
    index index.php index.html index.htm;

    location / {
         try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_pass php82:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 600;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    error_log /var/log/nginx/api_error.log debug;
    access_log /var/log/nginx/api_access.log;
}

这是我的 docker-compose.yml:

version: "3.8"
services:
  nginx:
    build:
      context: nginx
    ports:
      - "80:80"
    volumes:
      - ./nginx/conf:/etc/nginx/conf.d
      - /var/www/html:/var/www/html
      - ./logs:/var/log/nginx

  php82:
    build:
      context: php
      args:
        PHP_VERSION: 8.2
    volumes:
      - /var/www/html:/var/www/html
    extra_hosts: 
      - "host.docker.internal:host-gateway"

    environment:
      XDEBUG_CONFIG: client_host=host.docker.internal
      DEBUG: 1

  php74:
    build:
      context: php
      args:
        PHP_VERSION: 7.4
    volumes:
      - /var/www/html:/var/www/html
    extra_hosts: 
      - "host.docker.internal:host-gateway"
    environment:
      XDEBUG_CONFIG: client_host=host.docker.internal
      DEBUG: 1

我尝试在 docker-compose.yml 中使用

extra_hosts
指令,但是到目前为止还没有成功

docker nginx docker-compose
1个回答
0
投票

供以后参考,我解决了。

问题实际上出在curl本身上。

由于某种原因,curl auto 会将所有以 .localhost 结尾的域解析为 127.0.0.1,在这种情况下,会破坏功能,因为 fpm 容器内的 127.0.0.1 指向容器本身,而要指向的

api.localhost
域到 nginx。

解决方案是使用不同的域进行本地开发,例如 api.dev(需要将其映射到您的

/etc/hosts
)并在 nginx 容器上使用网络别名,以便 php-fpm 容器可以将该别名识别为 nginx容器。

    networks:
      default:
        aliases:
          - api.dev
© www.soinside.com 2019 - 2024. All rights reserved.