Giriş: ConnectionRefusedError Nedir?
ConnectionRefusedError, Python'da bir ağ bağlantısı kurmaya çalışırken hedef sunucunun bağlantıyı reddetmesi durumunda ortaya çıkan bir istisna (exception) türüdür. Bu hata, genellikle:
✔ Sunucu çalışmıyorken
✔ Yanlış port numarası kullanıldığında
✔ Firewall engellemesi olduğunda
✔ Hedef servis dinleme yapmıyorken
görülür. Bu kapsamlı rehberde, ConnectionRefusedError'ın nedenlerini, çözüm yöntemlerini ve profesyonel kullanım senaryolarını detaylıca inceleyeceğiz.
1. ConnectionRefusedError Ne Zaman Oluşur?
ConnectionRefusedError, bir TCP bağlantısı kurulmaya çalışılırken işletim sistemi tarafından ECONNREFUSED (errno 111) hatası döndüğünde ortaya çıkar.
Temel Örnek Senaryo
import socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', 9999)) # Açık olmayan port except ConnectionRefusedError as e: print(f"Hata: {e}") # [Errno 111] Connection refused
Çıktı:
Hata: [Errno 111] Connection refused
2. ConnectionRefusedError'ın Yaygın Nedenleri
a) Sunucu Çalışmıyor
Hedef sunucu başlatılmamış
Servis crash etmiş veya durdurulmuş
b) Yanlış Port Kullanımı
# PostgreSQL varsayılan portu 5432'dir wrong_port = 5433 try: conn = psycopg2.connect(host="localhost", port=wrong_port, dbname="test") except ConnectionRefusedError: print(f"{wrong_port} portunda servis çalışmıyor")
c) Firewall Engellemesi
import requests try: response = requests.get('http://firewall-engelli-site.com', timeout=5) except requests.exceptions.ConnectionError as e: print(f"Firewall engellendi: {e}")
d) Docker/Container Ağ Ayarları
Container'ın doğru portu expose etmemesi
Network bridge konfigürasyon hataları
3. ConnectionRefusedError Nasıl Çözülür?
a) Port Kontrolü ve Servis Durumu
import socket from contextlib import closing def check_port(host, port): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.settimeout(5) return sock.connect_ex((host, port)) == 0 # 0 = başarılı if not check_port('localhost', 5432): print("PostgreSQL servisi çalışmıyor veya port erişilebilir değil")
b) Yeniden Deneme Mekanizması
import time import psycopg2 from psycopg2 import OperationalError def connect_with_retry(conn_params, max_retries=5, initial_delay=1): delay = initial_delay for attempt in range(max_retries): try: return psycopg2.connect(**conn_params) except OperationalError as e: if attempt == max_retries - 1: raise print(f"Bağlantı hatası (deneme {attempt+1}): {e}") time.sleep(delay) delay *= 2 # Exponential backoff conn_params = { "host": "localhost", "port": 5432, "user": "postgres", "password": "secret" } connect_with_retry(conn_params)
c) Docker Ortamında Çözümler
# docker-compose.yml örneği
version: '3'
services:
db:
image: postgres:13
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 54. Gerçek Dünya Senaryoları
a) Mikroservis Mimarisinde Bağlantı Yönetimi
import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry def create_resilient_session(): session = requests.Session() retry_strategy = Retry( total=3, backoff_factor=1, status_forcelist=[502, 503, 504] ) adapter = HTTPAdapter(max_retries=retry_strategy) session.mount("http://", adapter) session.mount("https://", adapter) return session def call_service(url): session = create_resilient_session() try: response = session.get(url, timeout=5) response.raise_for_status() return response.json() except requests.exceptions.ConnectionError as e: print(f"Servis bağlantı hatası: {e}") return None
b) WebSocket Bağlantılarında Hata Yönetimi
import websockets import asyncio from backoff import on_exception, expo @on_exception(expo, websockets.exceptions.ConnectionRefusedError, max_tries=3) async def connect_websocket(): try: async with websockets.connect('ws://localhost:8765') as ws: await ws.send("Merhaba") return await ws.recv() except websockets.exceptions.ConnectionRefusedError as e: print(f"WebSocket sunucusu çalışmıyor: {e}") raise asyncio.run(connect_websocket())
5. Performans ve Güvenlik Optimizasyonları
a) Bağlantı Havuzu Kullanımı
from urllib3 import PoolManager http = PoolManager( maxsize=10, timeout=5.0, retries=3, block=True ) response = http.request('GET', 'http://api.service.com/data')
b) Circuit Breaker Deseni
from circuitbreaker import circuit @circuit(failure_threshold=5, recovery_timeout=30) def call_unstable_service(): response = requests.get('http://unstable-service/api') response.raise_for_status() return response.json()
c) Sağlık Kontrolü (Health Check)
import consul c = consul.Consul() def is_service_healthy(service_name): index, data = c.health.service(service_name) return bool(data) if not is_service_healthy('postgres'): print("Veritabanı servisi sağlıksız durumda")
Sonuç
✅ ConnectionRefusedError sunucu tarafından bağlantı reddi durumunda oluşur
✅ Port kontrolü ve servis sağlık kontrolü ile önlenebilir
✅ Yeniden deneme mekanizmaları ve circuit breaker deseni dayanıklılığı artırır
✅ Docker ve mikroservis ortamlarında ağ konfigürasyonu kritik öneme sahiptir
Sık Sorulan Sorular (SSS)
❓ ConnectionRefusedError ile ConnectionAbortedError farkı nedir?
ConnectionRefusedError: Bağlantı baştan reddedildiConnectionAbortedError: Bağlantı kurulduktan sonra kesildi
❓ Hangi Python sürümlerinde bulunur?
Python 3.3+ ile standart kütüphanede
❓ Test ortamında nasıl simüle edilir?
unittest.mockile socket bağlantıları mock'lanabilir
Özet Tablo
| Yöntem | Kullanım Senaryosu | Avantajlar |
|---|---|---|
| Port Kontrolü | Servis erişilebilirliği | Hızlı teşhis |
| Yeniden Deneme | Geçici hatalar | Basit uygulama |
| Circuit Breaker | Kronik hatalar | Sistem koruması |