草庐IT

PHP:Guzzle 6 - cURL 错误 7 连接被拒绝

coder 2024-04-07 原文

我搜索了又搜索,并阅读了 http://docs.guzzlephp.org/en/stable/request-options.html 上的文档并在 https://curl.haxx.se/libcurl/c/libcurl-errors.html 处确认错误对于我的一生,我无法弄清楚发生了什么。我的/etc/hosts 文件中有 app-one 和 app-two 的 URL,我知道它们是正确的,因为我可以在浏览器中访问它们,也可以通过终端使用 cURL 访问它们。

我的设置:

Docker 容器配置为:

App 1 = php-fpm - responding app
App 2 = php-fpm - requesting app, using Guzzle 6.3.2
Nginx Reverse Proxy

nginx 配置:

应用 1:

upstream php-app-one {
    server php-app-one:9000;
}

server {
    listen 80;
    listen [::]:80;
    server_name app-one.local;
    return 301 https://$server_name$request_uri;
}

server {
    # SSL configuration
    listen 443 ssl;
    listen [::]:443 ssl;

    ssl on;
    ssl_certificate /etc/nginx/certs/app-one.crt;
    ssl_certificate_key /etc/nginx/certs/app-one.key;
    ssl_dhparam /etc/nginx/certs/dhparam.pem;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_ecdh_curve secp384r1;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    server_name app-one.local;

    root /var/www/app-one;
    index index.php index.html;

    gzip_types text/plain text/css application/json application/x-javascript
               text/xml application/xml application/xml+rss text/javascript;

    # Add headers to serve security related headers
    #
    # Disable preloading HSTS for now.  You can use the commented out header line that includes
    # the "preload" directive if you understand the implications.
    # add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header Pragma "no-cache";
    add_header Cache-Control "no-cache";
    add_header X-uri "$uri";

    location ~* \.(eot|otf|ttf|woff|woff2)$ {
            add_header Access-Control-Allow-Origin *;
    }

    location / {
            proxy_read_timeout    90;
            proxy_connect_timeout 90;
            proxy_redirect        off;

            proxy_set_header      X-Real-IP $remote_addr;
            proxy_set_header      X-Scheme $scheme;
            proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header      X-Forwarded-Proto $scheme;
            proxy_set_header      X-Forwarded-Host $server_name;
            proxy_set_header      Host $host;
            proxy_set_header      X-Forwarded-Port 443;
            proxy_set_header      Authorization $http_authorization;
            proxy_pass_header     Authorization;

            try_files $uri $uri/ /index.php?$args;
    }

    # Pass all .php files onto a php-fpm/php-fcgi server.
    location ~ [^/]\.php(/|$) {
            add_header X-debug-message "A php file was used" always;
            # regex to split $uri to $fastcgi_script_name and $fastcgi_path
            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
            # This is a robust solution for path info security issue and 
            # works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)
            # if (!-f $document_root$fastcgi_script_name) {
            #         return 404;
            # }
            # Check that the PHP script exists before passing it
            # try_files $fastcgi_script_name =404;
            # Bypass the fact that try_files resets $fastcgi_path_info
            # see: http://trac.nginx.org/nginx/ticket/321
            set $path_info $fastcgi_path_info;
            fastcgi_param PATH_INFO $path_info;
            fastcgi_intercept_errors on;
            fastcgi_pass php-app-one;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            add_header X-debug-message "A static file was served" always;
            expires max;
            # log_not_found off;
    }

    location ~ /\. {
            deny all;
    }
}

应用 2:

upstream php-app-two {
    server php-app-two:9000;
}

server {
    listen 80;
    listen [::]:80;
    server_name app-two.local;
    return 301 https://$server_name$request_uri;
}

server {
    # SSL configuration
    listen 443 ssl;
    listen [::]:443 ssl;

    ssl_certificate /etc/nginx/certs/app-two.crt;
    ssl_certificate_key /etc/nginx/certs/app-two.key;
    ssl_dhparam /etc/nginx/certs/dhparam.pem;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_ecdh_curve secp384r1;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    server_name app-two.local;

    root /var/www/app-two;
    index index.php index.html;

    gzip_types text/plain text/css application/json application/x-javascript
               text/xml application/xml application/xml+rss text/javascript;


    # Add headers to serve security related headers
    #
    # Disable preloading HSTS for now.  You can use the commented out header line that includes
    # the "preload" directive if you understand the implications.
    # add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header Pragma "no-cache";
    add_header Cache-Control "no-cache";
    add_header X-uri "$uri";

    location ~* \.(eot|otf|ttf|woff|woff2)$ {
            add_header Access-Control-Allow-Origin *;
    }

    location / {
            proxy_read_timeout    90;
            proxy_connect_timeout 90;
            proxy_redirect        off;

            proxy_set_header      X-Real-IP $remote_addr;
            proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header      X-Forwarded-Host $server_name;
            proxy_set_header      Host $host;
            proxy_set_header      X-Forwarded-Proto $scheme;
            proxy_set_header      X-Forwarded-Port 443;
            proxy_set_header      Authorization $http_authorization;
            proxy_pass_header     Authorization;

            try_files $uri $uri/ /index.php;
    }

    # Pass all .php files onto a php-fpm/php-fcgi server.
    location ~ [^/]\.php(/|$) {
            add_header X-debug-message "A php file was used" always;
            # add_header Location "$uri" always;
            # regex to split $uri to $fastcgi_script_name and $fastcgi_path
            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
            # This is a robust solution for path info security issue and 
            # works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)
            if (!-f $document_root$fastcgi_script_name) {
                    return 404;
            }
            # Check that the PHP script exists before passing it
            try_files $fastcgi_script_name =404;
            # Bypass the fact that try_files resets $fastcgi_path_info
            # see: http://trac.nginx.org/nginx/ticket/321
            set $path_info $fastcgi_path_info;
            fastcgi_param PATH_INFO $path_info;
            fastcgi_intercept_errors on;
            fastcgi_pass php-app-two;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
    }
}

Nginx 反向代理:

worker_processes 1;

daemon off;

events {
    worker_connections 1024;
}

error_log   /var/log/nginx/error.log warn;
pid         /var/run/nginx.pid;

http {
    default_type application/octet-stream;
    include /etc/nginx/conf/mime.types;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;

    keepalive_timeout 65;

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    application/x-font-ttf ttc ttf;
    application/x-font-otf otf;
    application/font-woff woff;
    application/font-woff2 woff2;
    application/vnd.ms-fontobject eot;

    include /etc/nginx/conf.d/*.conf;
}

docker-compose.yml:

version: '3.3'
services:
  # configured to act as a proxy for wp and member portal
  nginx:
    image: evild/alpine-nginx:1.9.15-openssl
    container_name: nginx
    # volumes offer persistent storage
    volumes:
      - ./app_one:/var/www/app_one/:ro
      - ./app_two:/var/www/app_two/:ro
      - ./nginx/conf/nginx.conf:/etc/nginx/conf/default.conf:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - ./certs:/etc/nginx/certs
    # ports to bind to
    ports:
      - 80:80
      - 443:443
    # allows service to be accessible by other docker containers
    expose:
      - "80"
      - "443"
    depends_on:
      - php-app_one
      - php-app_two
    environment: 
      TZ: "America/Los_Angeles"


  # app-two php container
  php-app_two:
    environment: 
      TZ: "America/Los_Angeles"
    image: joebubna/php
    container_name: app_two_php
    restart: always
    volumes:
      - ./app_two:/var/www/app_two
    ports:
      - 9000:9000

   php-app_one:
     environment: 
       TZ: "America/Los_Angeles"
     image: joebubna/php
     container_name: app_one_php
     restart: always
     volumes:
       - ./app-one:/var/www/app-one
     ports:
       - 9001:9000

  db:
    image: mysql:5.6
    container_name: app_two_mysql
    volumes:
      - db-data:/var/lib/mysql
      - ./mysql/my.cnf:/etc/mysql/conf.d/ZZ-app-one.cnf:ro
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: cora
      TZ: "America/Los_Angeles"
    ports:
      - 3306:3306
    expose:
      - "3306"

    volumes:
      db-data:

应用程序 1 和应用程序 2 启用了 SSL,并使用在创建时由 docker-compose 导入的自签名证书。

App 1 有几个 API 端点 App 2 需要访问。当我尝试通过 Guzzle 访问时,我收到:

Fatal error: Uncaught GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect to app-one.local port 443: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in /var/www/app/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 185

GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect to app-one.local port 443: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in /var/www/app/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 185

Call Stack:
0.0026     366656   1. {main}() /var/www/app/index.php:0
0.2229    3355944   2. Cora\Route->routeProcess() /var/www/app/index.php:45
0.2230    3357208   3. Cora\Route->routeFind() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:89
0.2240    3357912   4. Cora\Route->routeFind() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:474
0.2245    3358576   5. Cora\Route->getController() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:441
0.2364    3477872   6. Controllers\Api\Dashboard->__construct() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:501
0.2984    4086336   7. GuzzleHttp\Client->get() /var/www/app/controllers/api/controller.Dashboard.php:36
0.2984    4086712   8. GuzzleHttp\Client->__call() /var/www/app/controllers/api/controller.Dashboard.php:36
0.2984    4086712   9. GuzzleHttp\Client->request() /var/www/app/vendor/guzzlehttp/guzzle/src/Client.php:89
0.3521    4321000  10. GuzzleHttp\Promise\RejectedPromise->wait() /var/www/app/vendor/guzzlehttp/guzzle/src/Client.php:131

这就是我目前实现客户端的方式(包括我在尝试补救时添加的一些代码):

<?php
namespace Controllers\Api;

use \GuzzleHttp\Client;
// use \GuzzleHttp\Psr7\Uri;

define('URL', 'https://app-one.local/api/');

class Dashboard extends ApiController 
{
    private $http;

    public function __construct($container)
    {
        // We're using guzzle for our requests to help keep opportunity
        // for cURL errors to a minimum
        $this->http = new Client([
            'base_uri'          => URL,
            'timeout'           => 30.0,
            'allow_redirects'   => true,
            'verify'            => false,
            'curl'              => [
                 CURLOPT_VERIFYPEER => false
            ],
            'headers'           => [
                'User-Agent'        => 'curl/7.38.0',
            ],
        ]);

        $response = $this->http->get('member/sales/hasalestest');
        var_dump($response);
        exit;
    }
}

正如我提到的,我可以通过浏览器很好地访问这个端点,并且可以在终端中使用 cURL 直接访问它,只要我使用 -k 标志来表示“不安全”。我不确定我还能做什么,因为 Guzzle 的文档对 5 和 6 之间的语法差异不是很清楚。然后 Drupal 和 Laravel 人群往往会遇到不相关的问题。

这个 SO 帖子看起来很相似(减去硬编码端口号和 Guzzle v.5)但没有提到任何我没有尝试过的东西:PHP Guzzle 5: Cannot handle URL with PORT number in it .

这个问题也很有趣,但基于与 App 1 交互的其他应用程序,它确实允许其他应用程序使用某些 API 端点:cURL error 7: Failed to connect to maps.googleapis.com port 443

此时我能想到的可能是 nginx 配置问题?朝着正确的方向插入是我向前迈进并获得我需要消费的其余端点所需要的。

感谢您的指导!

最佳答案

问题是本地计算机上的主机文件不会影响 docker 实例将 IP 映射到主机的方式。

尝试通过容器名称访问端点...

关于PHP:Guzzle 6 - cURL 错误 7 连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49889795/

有关PHP:Guzzle 6 - cURL 错误 7 连接被拒绝的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  3. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  4. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  5. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  6. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  7. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  8. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  9. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  10. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

随机推荐