Ошибка curl error 7 при установке

Я отправляю код товара в веб-сервис в формате xml, используя cUrl (php). Я получаю правильный ответ в localhost, но когда это делает сервер, он показывает

Ошибка cURL (7): не удалось подключиться к хосту

И вот мой код:

function xml_post($post_xml, $url)
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $ch = curl_init();    // initialize curl handle
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);          
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 50); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); 
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
//  curl_setopt($ch, CURLOPT_PORT, $port);          

    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    if ($curl_errno > 0) {
            echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
            echo "Data received\n";
    }
    curl_close($ch);

    echo $data;
}

Я отправляю код товара на счет и получаю от него детали. Я пытался использовать обе версии php 4+ и php5+, ничего не получается. Любое решение.

For a couple of days I was totally blocked on this. I’m very very new to networking/vms but was keen to try set it up myself instead of paying a hosting company to do it for me.

Context

I’m rebuilding the server side for an app that uses php routines to return various bits of data from internal sources as well as external APIs for a map based app. I have started an Oracle VM instance and have installed/set up Apache and php. All running totally fine, until one of my php routines tries to execute a cURL. I start implementing error logging to find that I don’t even get a message — just ‘7’, despite implementation being very similar to the above. My php routine accessing an internal file for data was running successfully so I was fairly sure it wasn’t an Apache or php issue. I also checked my Apache error logs, nothing telling.

Solution

I nearly gave up — there’s talk on disabling SELinux above and in other articles, I tried that and it did work for my purposes, but here’s a really good article on why you shouldn’t disable SELinux https://www.electronicdesign.com/technologies/embedded-revolution/article/21807408/dont-do-it-disabling-selinux

If temporarily disabling it works and like me you don’t want to do this (but it confirms that SELinux is blocking you!), I found a neat little command that actually prints out any SELinux issues in a more readable fashion:

sealert -a /var/log/audit/audit.log

This returned the following:


found 1 alerts in /var/log/audit/audit.log
--------------------------------------------------------------------------------

SELinux is preventing php-fpm from name_connect access on the tcp_socket port 443.

Great, I now get a bit more information than just ‘7’. Reading further down, I can see it actually makes suggestions:

*****  Plugin catchall_boolean (24.7 confidence) suggests   ******************

If you want to allow httpd to can network connect
Then you must tell SELinux about this by enabling the 'httpd_can_network_connect' boolean.

Do
setsebool -P httpd_can_network_connect 1

This has been mentioned further above but now I have a bit more context and an explanation as to what it does. I run the command, and I’m in business. Furthermore, my SELinux is still set to enforcing, meaning my machine is more secure.

There are many other suggestions logged out, if you’re blocked it might be worth logging out/checking out /var/log/audit/audit.log.

Добрый день! Установил lavarel-prerender на сайт, но сыпятся такие ошибки:

ConnectException in CurlFactory.php line 186:
cURL error 7: Failed to connect to foods-service.com.ua port 443: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
in CurlFactory.php line 186
at CurlFactory::createRejection(object(EasyHandle), array('errno' => '7', 'error' => 'Failed to connect to foods-service.com.ua port 443: Connection refused', 'url' => 'https://foods-service.com.ua/https%3A%2F%2Ffoods-service.com.ua%2F%3F_escaped_fragment_%3D', 'content_type' => null, 'http_code' => '0', 'header_size' => '0', 'request_size' => '0', 'filetime' => '-1', 'ssl_verify_result' => '0', 'redirect_count' => '0', 'total_time' => '0.004607', 'namelookup_time' => '0.004347', 'connect_time' => '0', 'pretransfer_time' => '0', 'size_upload' => '0', 'size_download' => '0', 'speed_download' => '0', 'speed_upload' => '0', 'download_content_length' => '-1', 'upload_content_length' => '-1', 'starttransfer_time' => '0', 'redirect_time' => '0', 'redirect_url' => '', 'primary_ip' => '', 'certinfo' => array(), 'primary_port' => '0', 'local_ip' => '', 'local_port' => '0')) in CurlFactory.php line 150
at CurlFactory::finishError(object(CurlHandler), object(EasyHandle), object(CurlFactory)) in CurlFactory.php line 103
at CurlFactory::finish(object(CurlHandler), object(EasyHandle), object(CurlFactory)) in CurlHandler.php line 43
at CurlHandler->__invoke(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in Proxy.php line 28
at Proxy::GuzzleHttp\Handler\{closure}(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in /home/admin/web/foods-service.com.ua/public_html/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php line 51
at Proxy::GuzzleHttp\Handler\{closure}(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in PrepareBodyMiddleware.php line 42
at PrepareBodyMiddleware->__invoke(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in Middleware.php line 30
at Middleware::GuzzleHttp\{closure}(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in RedirectMiddleware.php line 68
at RedirectMiddleware->__invoke(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in Middleware.php line 59
at Middleware::GuzzleHttp\{closure}(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in HandlerStack.php line 67
at HandlerStack->__invoke(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in Client.php line 275
at Client->transfer(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false, '_conditional' => array('User-Agent' => 'GuzzleHttp/6.2.1 curl/7.35.0 PHP/5.5.9-1ubuntu4.20'))) in Client.php line 123
at Client->requestAsync('get', 'https://foods-service.com.ua/https%3A%2F%2Ffoods-service.com.ua%2F%3F_escaped_fragment_%3D', array('headers' => array('User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'), 'synchronous' => true)) in Client.php line 129
at Client->request('get', 'https://foods-service.com.ua/https%3A%2F%2Ffoods-service.com.ua%2F%3F_escaped_fragment_%3D', array('headers' => array('User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'))) in Client.php line 87
at Client->__call('get', array('https://foods-service.com.ua/https%3A%2F%2Ffoods-service.com.ua%2F%3F_escaped_fragment_%3D', array('headers' => array('User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')))) in PrerenderMiddleware.php line 178
at Client->get('https://foods-service.com.ua/https%3A%2F%2Ffoods-service.com.ua%2F%3F_escaped_fragment_%3D', array('headers' => array('User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'))) in PrerenderMiddleware.php line 178
at PrerenderMiddleware->getPrerenderedPageResponse(object(Request)) in PrerenderMiddleware.php line 98
at PrerenderMiddleware->handle(object(Request), object(Closure))
at call_user_func_array(array(object(PrerenderMiddleware), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54

Скрин: joxi.ru/xAeBzLSpXjNMry
Кто может подсказать в чём проблема?

I’ve searched and searched, and read the documentation at http://docs.guzzlephp.org/en/stable/request-options.html and confirmed the error at https://curl.haxx.se/libcurl/c/libcurl-errors.html and for the life of me, I cannot figure out what’s going on. I have the URLs for both app-one and app-two in my /etc/hosts file, and I know they’re correct as I can access them in my browser and with cURL via terminal just fine.

My setup:

Docker containers configured as:

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

nginx configurations:

App 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;
    }
}

App 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 Reverse Proxy:

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:

App 1 and App 2 have SSL enabled with a self signed certificates that are imported on creation by docker-compose.

App 1 has several API endpoints App 2 needs to access. When I try to access via Guzzle, I receive:

Fatal error: Uncaught GuzzleHttpExceptionConnectException: 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

GuzzleHttpExceptionConnectException: 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. CoraRoute->routeProcess() /var/www/app/index.php:45
0.2230    3357208   3. CoraRoute->routeFind() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:89
0.2240    3357912   4. CoraRoute->routeFind() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:474
0.2245    3358576   5. CoraRoute->getController() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:441
0.2364    3477872   6. ControllersApiDashboard->__construct() /var/www/app/vendor/cora/cora-framework/system/classes/Route.php:501
0.2984    4086336   7. GuzzleHttpClient->get() /var/www/app/controllers/api/controller.Dashboard.php:36
0.2984    4086712   8. GuzzleHttpClient->__call() /var/www/app/controllers/api/controller.Dashboard.php:36
0.2984    4086712   9. GuzzleHttpClient->request() /var/www/app/vendor/guzzlehttp/guzzle/src/Client.php:89
0.3521    4321000  10. GuzzleHttpPromiseRejectedPromise->wait() /var/www/app/vendor/guzzlehttp/guzzle/src/Client.php:131

This is how I’m currently implementing the client (including some of the code I’ve added in my attempts to remedy this):

<?php
namespace ControllersApi;

use GuzzleHttpClient;
// use GuzzleHttpPsr7Uri;

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;
    }
}

As I mentioned, I can access this endpoint via browser just fine, and can access it directly with cURL in the terminal so long I use the -k flag for «insecure». I’m not sure what else I can do, as Guzzle’s documentation isn’t very clear on the syntax differences between 5 and 6. Then the Drupal and Laravel crowds tend to have unrelated issues.

This SO post seemed similar (minus the hard-coded port number and Guzzle v.5) but doesn’t mention anything I haven’t tried: PHP Guzzle 5: Cannot handle URL with PORT number in it .

This question is also of interest, but based on other apps that interact with App 1, it does allow other apps to consume certain API endpoints: cURL error 7: Failed to connect to maps.googleapis.com port 443

All I can think of at this point is maybe it’s an nginx configuration issue? A push in the right direction is all I need to get moving forward and get the rest of the endpoints I need to consume, being consumed.

Thanks for any guidance!

Are you frustrated with cURL error 7 failed to connect to port 443?

This error is common when using PayPal or Facebook login scripts on the website. This mainly occurs when the server firewall blocks the curl request.

At Bobcares, we often receive requests to fix this error as part of our Server Management Services.

Today, let’s discuss the error in detail and see how our Support Engineers fix it for our customers.

What is cURL error 7?

Have any idea about when does the curl error occur?

Curl error 7 mainly occurs when the TCP connection to a given host/port fails. It ends up in an error message.

PHP Fatal error: Uncaught exception 'Exception' with message 'cURL error: [7] Failed to connect to xxx.paypal.com port 443: Connection refused'

Let’s discuss the details of the exact scenario of the error. Recently, one of our WordPress customers approached us with a request stating:

I have installed a theme on my site, however, the theme won’t validate. I’ve installed a Query Monitor and saw that I’m receiving a cURL 7 error. Could you please help me resolve this issue?

cURL_error_7_failed_to_connect_to_port_443

On checking the error, our Support engineers ensured that no firewall was blocking outbound connection in this server. Also, we found port 443 opened in TCP In/Out and UDP Out for both IPv4 and IPv6.

So far we have seen the error in depth. Now, let’s check how our Support Engineers fix it efficiently.

Our Support Engineers tried to issue a telnet session to the host server and found some connection errors.

Upon checking, we found that the customer’s IP has been blocked in the WordPress theme update server. And, that is this error has occurred.

We asked the customer to contact them to whitelist the IP in their firewall. This resolved the error and the theme activation worked fine.

[Need more help to solve this error?- We’re available 24/7 to help you.]

Conclusion

In short, cURL error 7 failed to connect to port 443 mainly occurs when the firewall blocks the curl request. Today, we have discussed this error in detail and saw how our Support Engineers fix it for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

So, I am trying make Nginx serve my website via https, but it keeps hitting me with a refused to connect error.

So here are the outputs for:

  1. curl https://juristnet.ro (this is the website)

    curl: (7) Failed to connect to juristnet.ro port 443: Connection refused
    
  2. netstat -anltp

    tcp        0      0 0.0.0.0:80              0.0.0.0:*                  LISTEN      -               
    tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -               
    tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      -               
    tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      -               
    tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      -               
    tcp        0      0 46.101.111.197:80       66.249.64.215:60905     TIME_WAIT   -               
    tcp        0      0 46.101.111.197:80       66.249.64.211:57434     ESTABLISHED -               
    tcp        0      0 46.101.111.197:22       82.208.159.43:26902         ESTABLISHED -               
    tcp        0    476 46.101.111.197:22       82.208.159.43:11648     ESTABLISHED -               
    tcp        0      0 46.101.111.197:22       223.99.60.37:16862      ESTABLISHED -               
    tcp6       0      0 :::8080                 :::*                      LISTEN      -               
    tcp6       0      0 :::22                   :::*                    LISTEN      -               
    tcp6       0      0 :::30845                :::*                    LISTEN      -   
    

As you can see, port 443 is open and Nginx is listening

80/tcp   open  http
443/tcp  open  https
3306/tcp open  mysql
5432/tcp open  postgresql

Nmap shows port is open.

UFW is inactive, so not firewall issues. It’s a droplet at digitalocean, so no forwarding problems on their side.

  1. iptables -L

    Chain INPUT (policy ACCEPT)
    target     prot opt source               destination         
    ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
    ACCEPT     tcp  --  anywhere             localhost            tcp spts:1024:65535 dpt:https state NEW,ESTABLISHED
    
    Chain FORWARD (policy ACCEPT)
    target     prot opt source               destination         
    DOCKER-ISOLATION  all  --  anywhere             anywhere            
    DOCKER     all  --  anywhere             anywhere            
    ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
    ACCEPT     all  --  anywhere             anywhere            
    ACCEPT     all  --  anywhere             anywhere            
    
    Chain OUTPUT (policy ACCEPT)
    target     prot opt source               destination         
    
    Chain DOCKER (1 references)
    target     prot opt source               destination         
    ACCEPT     tcp  --  anywhere             172.17.0.2           tcp dpt:http
    ACCEPT     tcp  --  anywhere             172.17.0.2           tcp  dpt:https
    

My Nginx.conf:

user admin root;
worker_processes auto;

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


events {
    worker_connections  1024;
}


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

    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;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;

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

My other conf ( for the server blocks):

server {

listen 80;
listen 443 ssl;

server_name  juristnet.ro www.juristnet.ro;
keepalive_timeout   70;

ssl_certificate /etc/letsencrypt/live/juristnet.ro/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/juristnet.ro/privkey.pem;
ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers         HIGH:!aNULL:!MD5;

root /var/test/proiect;
client_max_body_size 10M;

location = /favicon.ico
{
    access_log off; log_not_found off;
            alias /var/test/proiect/favicon.ico;
}

location /static/
{
    autoindex on;
}

    location /assets/
{
            autoindex on;
            alias /var/test/proiect/assets/;
}

    location  ~ /.well-known/
{
            allow all;
}

location / {
    include /etc/nginx/fastcgi_params;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $http_host;
        proxy_pass http://unix:/var/test/proiect/Tutorial2.sock;
        fastcgi_param   HTTPS               on;
        fastcgi_param   HTTP_SCHEME         https;


}

There is also another subdomain, but i’m guessing that’s not relevant.

The error logs and access logs for nginx don’t show anything special.

The certificates were obtained from letsencrypt. If I try binding gunicorn
as it is on 0.0.0.0:8000, with the —keyfile and —certfile options, it does work with https, so I am guessing this is an nginx issue. Or maybe i need to add those settings somewhere? Anyway, I have been bashing my head on this for 2 days, so if anybody has any solution to this, I would be very thankful.

Здесь VPS на BrainyCP за 2$ в месяц, а здесь 50GB шаред-хостинг на BrainyCP за 1.9$ в месяц

micha

Сообщения: 8
Зарегистрирован: Ср фев 20, 2019 9:58 am

Ошибка:curl: (7) Failed to connect

Добрый день!
Перепробовал все советы, ну почти все из гугла, но проблемка так и осталась.

curl: (7) Failed to connect to example.com port 443: Connection refused

Сайт отлично работает. Сертификат стал без проблем. Мои идеи закончились..

Может кто-то уже сталкивался. Подскажите, пожалуйста!


Аватара пользователя

sbury

Сообщения: 1115
Зарегистрирован: Вт фев 06, 2018 7:51 am

Re: Ошибка:curl: (7) Failed to connect

Сообщение

sbury » Ср фев 20, 2019 10:17 am

попробуйте
NSS_DISABLE_HW_GCM=1 curl httpS://some_https_site.com

у покажите свою строку curl как вы обращаетесь к сайту. Пароль есть?


micha

Сообщения: 8
Зарегистрирован: Ср фев 20, 2019 9:58 am

Re: Ошибка:curl: (7) Failed to connect

Сообщение

micha » Ср фев 20, 2019 10:50 am

Спасибо за быстрый ответ!

Обращаюсь так:

curl -I https://example.com

Вот такой ответ получил:

curl: (6) Could not resolve host: example.comNSS_DISABLE_HW_GCM=1
<html>
<head><title>404 Not Found</title></head>
<body bgcolor=»white»>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
curl: (7) Failed to connect to example.com port 443: Connection refused

Потом набрал еще раз предложенную Вами строку и уже только это.

curl: (7) Failed to connect to example.com port 443: Connection refused

Сертификаты установились без проблем и отображаются в браузерах. Ошибок со стороны пользователя нет. Просто некоторые скрипты ругаются.
Если решение вопроса заморочистое, можно отложить. Спасибо за панель. Супер!

П.С., А пароль отчего?

Последний раз редактировалось micha Ср фев 20, 2019 3:05 pm, всего редактировалось 1 раз.


micha

Сообщения: 8
Зарегистрирован: Ср фев 20, 2019 9:58 am

Re: Ошибка:curl: (7) Failed to connect

Сообщение

micha » Ср фев 20, 2019 11:49 am

Возможно это решение?

в файле /etc/hosts

127.0.1.1 example.com example

заменил на

внешнее ip-сайта example.com example

и ошибки больше нет. Надеюсь, что сделал правильно..


micha

Сообщения: 8
Зарегистрирован: Ср фев 20, 2019 9:58 am

Re: Ошибка:curl: (7) Failed to connect

Сообщение

micha » Ср фев 20, 2019 1:10 pm

Похоже, что проблемка в другом. Одна програмка выдала такое сообщение «.. has received no response from the webpage. » Если будут идеи с удовольствием их потестирую. Проблема не критична, но непонятна..


Timothynor

Сообщения: 17
Зарегистрирован: Вс янв 27, 2019 9:25 am
Откуда: Denmark
Контактная информация:

Ошибка curl 7 Failed to connect

Сообщение

Timothynor » Сб фев 23, 2019 5:10 pm

Вылезает ошибка Fatal error: Call to undefined function curl_init на дэнвере. Как исправить ? Запускается паррсинг, на хостинге работает — на дэнвере нет. Чем это лечится ?


elitarno

Сообщения: 25
Зарегистрирован: Пт янв 11, 2019 11:56 am
Контактная информация:

Re: Ошибка:curl: (7) Failed to connect

Сообщение

elitarno » Чт мар 07, 2019 3:33 pm

Возможно, если ваш сервер крутится на вирт машине или за шлюзом, который вы можете админить, то

если курлите из под лок сети на самого себя, типа из под консоли Web Shell и получаете вы описанный недосуп,
то ищите трабл в настройках iptables:
для пример парвило в /etc/iptables_rules на Хост сервере , нарипмер Debian с Proxmox:

Код: Выделить всё

-A FORWARD -d 192.168.1.3/32 -i enp6s0 -p tcp -m tcp --dport 443 -j ACCEPT

т.е. зарешаем вирт машине с данным IP адресом обращаться по https через tcp/ip протокол

если конечно у вас похожий инвайромент.

elitarno.com


micha

Сообщения: 8
Зарегистрирован: Ср фев 20, 2019 9:58 am

Re: Ошибка:curl: (7) Failed to connect

Сообщение

micha » Ср мар 13, 2019 1:14 pm

elitarno, спасибо за совет. Попробовал, но, к сожалению, не помогло. Первый раз с такой проблемкой сталкиваюсь.
Команда curl -I http://example.com работает, а curl -I https://example.com выдает ошибку curl: (7) Failed to connect to example.com port 443: Connection refused Раньше никогда специально этот параметр не настраивал и все было ок. Найду решение отпишусь..


For anyone else who comes across this, here is my working setup.

I’ve got the docker-gitlab stack up and running over SSL in a Rancher environment using a standard Rancher load balancer.

docker-gitlab is simply configured with GITLAB_HTTPS=true

The Load Balancer is configured as follows:

Public Port 443 -> use SSL -> forwards to port 80 on docker-gitlab
Public Port 80 -> forwards to port 80 on docker-gitlab

Opening 80 allows gitlab to redirect HTTP users to HTTPS. If you have any issues with avatar images not displaying and being served over HTTP you will need to remove and re-upload each avatar image.

Thanks to everyone who was so quick to respond and help.

  • Hello

    I installed WP in a VM at home to perform some tests.
    Everything was working well, I can access to website from internet, etc…
    But when I go to “Tools > Site Health”, I have 3 Critical issues. All of them related to a “cURL error 7”, but without any details related to which error.

    The REST API encountered an error
    The REST API is one way WordPress, and other applications, communicate with the server. One example is the block editor screen, which relies on this to display, and save, your posts and pages.

    The REST API request failed due to an error.
    Error: [] cURL error 7:

    Could not reach WordPress.org
    Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.

    Error Your site is unable to reach WordPress.org at 198.143.164.251, and returned the error: cURL error 7:

    Your site could not complete a loopback request
    Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.

    The loopback request to your site failed, this means features relying on them are not currently working as expected.
    Error: [] cURL error 7:

    When I connect to Unix hosting WP, I’m able to perform a cURL to WordPress, and reach internet.
    I can’t find what is going on and how to fix it, since there is no error details, neither in WP logs.

    Any tips ?

  • Linux and its flavours are known for their many command-line utilities that simplify users’ jobs. However, since they don’t have graphical interfaces, any bugs or errors in these tools can be hard to diagnose as all you get is an error code on the terminal. 

    In this article, we’re talking about Curl error 7, the reasons behind it and what you can do to fix the problem. 


    What causes Curl error 7?

    Curl error 7 can actually be triggered by a number of reasons including:

    • Background updates
    • The server isn’t responding or is down
    • Internet connectivity issues

    Also read: How to fix Zsh: Command not found: Brew?


    Here are four fixes you can try out.

    Check your internet

    The first thing you should do in such situations is to check your internet connection. If you’re connected to a WiFi network, check if you have an active internet connection. Otherwise, you can try restarting your router or plugging in via LAN. 


    Try again in some time

    There’s a good chance that the receiving server is overloaded with requests and needs time to clear its pending overhead before it can get to new messages. Since the message is rather vague, you should wait some time and try again before trying anything else. 


    Use HTTPS

    If you’re using a program like curl or libcurl, entering URLs with the HTTPS prefix is necessary. Simply using the HTTP prefix means that the connection won’t be secure and will be dropped by the server more often than not, resulting in the error. Try replacing the HTTP:// with HTTPS://, and you should be ready. 


    Check if your IP has been blocked

    A lot of times, CURL might end up giving an error if the source IP you’re using to access the server is blocklisted. Especially if you’re trying to access the site over your school’s or office’s internet network, chances are they’ve blocked access to the particular server you’re trying to reach.

    You can try a VPN to see if you can get around any such blocks. Using a VPN also gives you a new IP address, meaning you can circumvent any problems caused by your IP address getting accidentally blocklisted. 

    Also read: How to fix fatal error: curl/curl.h: no such file or directory?

    Понравилась статья? Поделить с друзьями:
  • Ошибка cs1009 нераспознанная escape последовательность
  • Ошибка cs1003 синтаксическая ошибка требуется
  • Ошибка cups линукс
  • Ошибка cs1002 требуется
  • Ошибка cups запрещено astra linux