Php curl failed connect to

Docker Nginx PHP Laravel curl failed to connect to api.localhost port 80. Connection refused

Both http://api.localhost and http://app.localhost are able to run on my web browser. However, when the APP do a curl request to the API, I get the following error. cURL error 7: Failed to connect to api.localhost port 80: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://api.localhost Both are residing in the same network when I execute docker network inspect my_network .

"Containers": < "0d77c5cc22c36f8086eb8e5d580562354c4c6b3c7bdd962e0f8cebfa7a3d844b": < "Name": "my_api", "EndpointID": "93bb1cd93ccd09b7c1fd2de3e074525b2fc98919eba0cf2cc96c2112d4e1e1b5", "MacAddress": "02:42:ac:17:00:09", "IPv4Address": "172.23.0.9/24", "IPv6Address": "" >, "53432448ea91677c643d2f1ff206dcfdc6209741ba9951da342756f752672ab8": < "Name": "webserver_my_app", "EndpointID": "09ec9ae65461bcc42a750fb0a4fee8305b299c1ad2f1b8e16c65902119489b0d", "MacAddress": "02:42:ac:17:00:03", "IPv4Address": "172.23.0.3/24", "IPv6Address": "" >, "55c2fef084b249a7b3537c641c7101276d9130c6d81d77b21e88206bd10001ec": < "Name": "webserver_my_api", "EndpointID": "ad1d3b1bedd140a26aec05de276f6f5edc0631b22fa2e77595f5bdf63d9eabca", "MacAddress": "02:42:ac:17:00:08", "IPv4Address": "172.23.0.8/24", "IPv6Address": "" >, "dedfe7f75ef76e913b4483708b9920b7d94f8d4931db74e9831cc86194113d75": < "Name": "my_app", "EndpointID": "80f2c8e1b83817dda62c682f9ed8e098d8cd3cf4c6d05b3af145e58660368779", "MacAddress": "02:42:ac:17:00:05", "IPv4Address": "172.23.0.5/24", "IPv6Address": "" >>, 

enter image description here

I am able to do a request via postman as well with no issues. It is just when the APP do a curl on the API. Anything I missed out? Thank you EDIT: Added screenshot from docker ps command

Источник

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

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

Я добавлю две вещи, которые в конечном итоге позволили решить мою проблему: 1. запустить cURL из командной строки с помощью —verbose 2. Если вы работаете в OSX с Little Snitch (или аналогичным), посмотрите на это.

9 ответов

Код ошибки CURL 7 (CURLE_COULDNT_CONNECT)

очень явно. это означает, что не Failed to connect() to host or proxy.

Следующий код будет работать в любой системе:

$ch = curl_init("http://google.com"); // initialize curl handle curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $data = curl_exec($ch); print($data); 

Если вы не видите страницу Google, тогда.. your URL is wrong или у вас есть проблема с firewall или restriction .

Я могу видеть страницу Google. Но затем тот же URL, я использую его в localhost, и там он работает нормально.

Я не думаю , что это публичный IP — адрес доступен network-tools.com/. Pinging 122.165.82.61 с 32 байтами данных: запрос истек. Истекло время запроса. Истекло время запроса. Истекло время запроса.

Эй, ребята, я также пытаюсь отправить файл, используя PHP curl и получая код ошибки 7, который не может подключиться к хосту, я попробовал подход Бабы, чтобы проверить, загружается ли google.com, и это происходит. IP-адрес, который я пытаюсь установить по ftp, является общедоступным, например, когда я отправляю ping на IP-адрес, который он дает (64 байта из 31.170.160.98: icmp_req = 1 ttl = 42 время = 249 мс), IP-адрес, конечно, — 31.170.160.98, Кроме того, когда я пытаюсь ftp с помощью браузера, он позволяет мне войти. Но это скрипт curl, который создает ошибку. Может кто-нибудь помочь мне решить эту проблему или указать мне, что нужно проверить, например, брандмауэр, порты и т. Д.

Источник

PHP: Guzzle 6 — cURL error 7 Connection Refused

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 
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; >> 
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; >> 
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; >
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 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. () /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 

This is how I’m currently implementing the client (including some of the code I’ve added in my attempts to remedy 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!

Читайте также:  Power bi api python

Источник

CURL ERROR: Recv failure: Connection reset by peer — PHP Curl

I’m having this strange error, CURL ERROR: Recv failure: Connection reset by peer This is how it happens, if I did not connect to the server and all of a sudden trying to connect to the server via CURL in PHP I get the error. When I run the CURL script again the error disappears and then works well the whole time, if I leave the remote server idle for about 30mins or reboot the remote server and try to connect again, I get the error again. So it seems like the connection is idle and then all of sudden the server wakes up and then works and then sleeps again. This is how my CURL script looks:

$url = Yii::app()->params['pdfUrl']; $body = 'title='.urlencode($title).'&client_url='.Yii::app()->params['pdfClientURL'].'&client_id='.Yii::app()->params['pdfClientID'].'&content='.urlencode(htmlentities($content)); $c = curl_init ($url); $body = array( "client_url"=>Yii::app()->params['pdfClientURL'], "client_id"=>Yii::app()->params['pdfClientID'], "title"=>urlencode($title), "content"=>urlencode($content) ); foreach($body as $key=>$value) < $body_str .= $key.'='.$value.'&'; >rtrim($body_str,'&'); curl_setopt ($c, CURLOPT_POST, true); curl_setopt ($c, CURLOPT_POSTFIELDS, $body_str); curl_setopt ($c, CURLOPT_RETURNTRANSFER, true); curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0); curl_setopt ($c, CURLOPT_TIMEOUT , 20); $pdf = curl_exec ($c); $errorCode = curl_getinfo($c, CURLINFO_HTTP_CODE); $curlInfo = curl_getinfo($c); $curlError = curl_error($c); curl_close ($c); 

I’m totally out of ideas and solutions, please help, I’ll appreciate it. If I verbose the output to see what happens using

curl_setopt ($c, CURLOPT_VERBOSE, TRUE); curl_setopt($c, CURLOPT_STDERR, $fp); 
* About to connect() to 196.41.139.168 port 80 (#0) * Trying 196.x.x.x. * connected * Connected to 196.x.x.x (196.x.x.x) port 80 (#0) > POST /serve/?r=pdf/generatePdf HTTP/1.1 Host: 196.x.x.x Accept: */* Content-Length: 7115 Content-Type: application/x-www-form-urlencoded Expect: 100-continue * Recv failure: Connection reset by peer * Closing connection #0 012 20:23:49 GMT < Server: Apache/2.2.15 (CentOS) < X-Powered-By: PHP/5.3.3 < Connection: close < Transfer-Encoding: chunked < Content-Type: text/html; charset=UTF-8 < * Closing connection #0 
curl_setopt ($c, CURLOPT_HTTPHEADER, array( 'Expect:' ) ); > Accept: */* Content-Length: 8414 Content-Type: > application/x-www-form-urlencoded > > * Recv failure: Connection reset by peer > * Closing connection #0 r: Apache/2.2.15 (CentOS) < X-Powered-By: PHP/5.3.3 < Connection: close < Transfer-Encoding: chunked < >Content-Type: text/html; charset=UTF-8 < >* Closing connection #0 

Источник

Читайте также:  Сортировка пузырьком javascript массива

Failed to connect host:80:Timed Out cURL php

I have two applications. One is PHP and another is a Laravel app in which both are residing on different servers. I want to send data from the PHP application to the Laravel application, which I am doing using cURL. But it is throwing a 'Failed to connect: Timed out' error. This is how I am sending the json-data using POST using cURL:

$url ='http://host_name/project/public/index.php/login'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS,$userdata); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); if (curl_error($ch)) < $error_msg = curl_error($ch); >echo $error_msg."
"; print_r(curl_getinfo());
Failed to connect to host_name port 80: Timed out [url] => http://host_name/project/public/index.php/login [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 20.234 [namelookup_time] => 0.015 [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 ) 

Источник

Оцените статью