Pricing Blog Compare Glossary
Login Start Free

TCP Port Monitoring: How to Monitor Services Beyond HTTP

Comprehensive guide to TCP port monitoring: how it works, common ports, monitoring databases and services, TLS on TCP, and combining with HTTP checks.

2026-03-26 · 10 min · Technical Guide

TCP monitoring — проверка того, что порт открыт и сервис принимает соединения. Это не HTTP (который отправляет запрос и ждёт ответ), это pure socket'овое подключение: есть соединение — порт работает, нет соединения — порт закрыт или сервис упал.

Для веб-приложений достаточно HTTP monitoring'а. Но если у вас есть database, cache, mail server, или любой non-HTTP сервис — TCP check необходим. Нельзя же мониторить PostgreSQL'ом HTTP запросом (SQL не понимает). Приходится опускаться на уровень TCP.

Когда HTTP monitoring недостаточно

Database servers (PostgreSQL, MySQL, MongoDB)

Database не слушают HTTP (обычно). PostgreSQL слушает port 5432 и ждёт PostgreSQL wire protocol'а. MySQL слушает 3306. MongoDB слушает 27017. Если попробуете отправить HTTP запрос — сервер вернёт ошибку сразу. Единственный способ проверить live это ли он — открыть socket соединение.

Cache systems (Redis, Memcached)

Redis слушает port 6379 и ожидает RESP protocol'а (Redis Serialization Protocol). Memcached слушает 11211. Вы можете отправить PING команду и вернёт +PONG, но это требует знания protocol'а. TCP monitoring будет достаточно для базовой проверки.

Mail servers (SMTP, IMAP, POP3)

SMTP слушает port 25 или 587. IMAP слушает 143 или 993 (SSL). POP3 слушает 110 или 995 (SSL). Когда вы подключитесь по TCP — сервер сразу отправит greeting banner (220 mail.example.com ESMTP). TCP соединение показывает, что сервер отвечает.

Game servers и custom protocols

Minecraft server, Discord bot, proprietary application backend — всё слушает на custom port'е и ожидает custom protocol'я. HTTP monitoring тут бесполезен. TCP check — единственный способ проверить базовую connectivity.

Internal services не через HTTP

Микросервис может слушать gRPC (port 50051), не HTTP. Или использовать raw TCP для performance. TCP check ловит это, HTTP health check не поможет.

Как работает TCP health check

TCP Three-Way Handshake

Step 1: SYN

Monitor отправляет SYN (synchronization) пакет на целевой IP:port с флагом SYN

Step 2: SYN-ACK

Сервер отвечает пакетом с флагом SYN и ACK (acknowledgement), которое подтверждает, что он получил наш SYN

Step 3: ACK

Monitor отправляет ACK пакет для подтверждения, что получил SYN-ACK

Результат: соединение establecido (established), порт открыт

Возможные результаты

✓ SUCCESS (port open): TCP handshake завершился, соединение open. Сервис слушает.

✗ TIMEOUT (connection refused): сервер молчит, не отвечает на SYN. Порт закрыт или сервис не запущен.

✗ RST (reset): сервер получил SYN и явно отправил RST (reset). Это активный отказ, обычно означает неправильный port или service не на этой machine.

✗ FIREWALL BLOCK: пакет теряется, timeout. Firewall может блокировать, или IP не маршрутизируется.

Распространённые порты для мониторинга

Databases

PostgreSQL: 5432 (default)

MySQL: 3306 (default)

MongoDB: 27017 (default)

Oracle: 1521 (default)

SQL Server (MSSQL): 1433 (default)

MariaDB: 3306 (same as MySQL)

Cache and Memory Stores

Redis: 6379 (default)

Memcached: 11211 (default)

Redis Cluster: 6379-6384 (nodes)

Email Services

SMTP (unencrypted): 25

SMTP (TLS): 587, 465

IMAP (unencrypted): 143

IMAP (SSL/TLS): 993

POP3 (unencrypted): 110

POP3 (SSL/TLS): 995

Search and Analytics

Elasticsearch: 9200 (HTTP), 9300 (node communication)

Solr: 8983 (default)

OpenSearch: 9200 (same as Elasticsearch)

Message Queues

RabbitMQ: 5672 (AMQP), 15672 (HTTP management)

Kafka: 9092 (default broker port)

NATS: 4222 (default)

Other Services

SSH: 22

DNS: 53

VNC (remote desktop): 5900

RDP (Windows remote): 3389

LDAP: 389 (unencrypted), 636 (SSL)

TCP connection latency

Время, которое требуется на TCP handshake — это ценный метрика. Если обычно это 5ms, а сейчас 500ms — сервис перегружен или сеть медленная.

< 50ms: быстро, сервис локальный или на быстрой сети

50-200ms: нормально, сервис в другом datacenter'е или region'е

200-1000ms: медленно, могут быть сетевые проблемы или перегрузка

1000ms+: очень медленно, критичная проблема или неправильная конфигурация

TLS на TCP: мониторинг SSL/TLS соединений

Много сервисов используют TLS encryption сверху TCP (TCP + TLS). MySQL можно конфигурить с TLS, SMTP требует TLS (port 587/465), Redis может быть с TLS.

TCP vs TLS monitoring

TCP check только: проверяет, что port open. Не проверяет TLS.

TLS check: проверяет, что TCP connection opening, потом проверяет TLS handshake, и извлекает certificate информацию (expiry, issuer, domain).

Рекомендация: для сервисов с TLS используйте TLS check, не простой TCP. Это ловит certificate expiry.

Пример: мониторинг PostgreSQL с TLS

PostgreSQL может быть сконфигурирован требовать TLS. Клиент отправляет sslmode=require в connection string.

Для мониторинга: используйте TLS check (не просто TCP) на port 5432 с TLS enabled.

Это ловит когда certificate истекает, или когда TLS handshake fails.

TCP monitoring в AtomPing

Создание TCP check

Тип: TCP

Host: db.example.com (или IP)

Port: 5432 (PostgreSQL)

Timeout: 10 секунд (достаточно для handshake)

Интервал: 60 секунд

Регионы: выберите несколько для geografically distributed checks

Комбинирование TCP и HTTP monitoring

Для critical сервисов лучше мониторить и TCP и HTTP:

TCP check (port открыт?): простой, fast, если fails — сервис completeness down

HTTP check (сервис отвечает корректно?): детальный, ловит application errors, returns 500

Интерпретация:

  • ✓ TCP pass, ✓ HTTP pass → нормально
  • ✓ TCP pass, ✗ HTTP fail → application problem (process up, logic broken)
  • ✗ TCP fail, - HTTP skip → network/infrastructure problem (port closed/firewall)

Типичные ошибки в TCP мониторинге

Ошибка 1: мониторить неправильный port

ps aux | grep postgres покажет процесс, но не порт. Проверьте конфиг:

# PostgreSQL
grep port /etc/postgresql/*/main/postgresql.conf

# MySQL
grep port /etc/mysql/my.cnf

# Redis
grep port /etc/redis/redis.conf

# Or use netstat/ss
ss -tlnp | grep postgres

Ошибка 2: firewall блокирует от monitor

TCP check returns timeout, но сервис локально отвечает. Причина: firewall блокирует входящие соединения от IP address'а monitor'а.

Решение: откройте port'а в firewall'е для IP'ов монитора (или для range, если monitor'ы distributed).

Ошибка 3: сервис слушает только на localhost

Сервис сконфигурирован слушать на 127.0.0.1:5432 (localhost), не на 0.0.0.0:5432 (все interfaces). Внешний monitor не может подключиться.

Решение: сконфигурируйте сервис слушать на всех interfaces или на публичном IP. Или используйте internal monitor (от той же machine или VPC).

Ошибка 4: database требует authentication

PostgreSQL/MySQL откроют TCP соединение, но потом требуют password. TCP check пройдёт (соединение open), но если нужны credentials для реальной проверки — используйте service-specific check.

Альтернатива: создайте read-only query в database и используйте health endpoint вместо директного database check'а.

Ошибка 5: слишком агрессивный monitoring

Если у вас 100 monitor'ов открывают соединение к database'е каждые 5 секунд — это 2000 connections в минуту. Сначала это overload connection pool, потом database crash'ится.

Решение: мониторьте реже (каждые 60 секунд), или используйте только 3-5 monitor'ов в разных region'ах, а не все 100.

Мониторинг внутренних сервисов

Если database находится inside VPC и не доступна from internet — используйте internal monitor (agent/worker внутри VPC) для TCP check'и.

Вариант 1: deploy agent в same VPC, чтобы он мог достучаться к database'е

Вариант 2: expose health endpoint'у внешнему миру (с auth), и мониторьте HTTP вместо TCP

Вариант 3: используйте bastion host/jumpbox и proxy'йте мониторинг через него

Комбинирование TCP с complete monitoring strategy

TCP check один не достаточен. Для production критичных сервисов используйте многоуровневый подход:

Layer 1: TCP check (is port responding?) — быстро, базовая connectivity

Layer 2: Health endpoint (is service healthy?) — детальная status информация

Layer 3: Synthetic transactions (can I actually use it?) — test реальный workflow (query для DB, payment charge для payment API)

Layer 4: Internal monitoring (logs, metrics, tracing) — контекст и root cause

TCP monitoring vs ICMP ping

Часто путают TCP check и ICMP ping (ICMP monitoring).

ICMP ping: проверяет, что host reachable (является ли машина доступна по сети). Не проверяет конкретный сервис.

TCP port check: проверяет, что конкретный сервис (port) принимает соединения. Более специфичен.

Рекомендация: для критичных сервисов используйте TCP (ловит service failures), не ICMP (ловит только network failures).

Checklist: TCP port monitoring

Сервис: правильно ли определён порт, на котором сервис слушает?

Firewall: открыт ли порт для monitor'а (или firewall разрешает из external)?

Network: сервис слушает ли на всех interfaces (0.0.0.0), не только localhost?

TLS: если сервис использует TLS, используйте TLS check, не TCP

Load: не перегружает ли мониторинг сервис частыми соединениями?

Комбинация: TCP + HTTP checks для defence-in-depth

Интерпретация: правильно ли интерпретируете результаты (TCP pass ≠ service здоров)

Связанные материалы

Complete Guide to Uptime Monitoring — overview всех типов checks

Health Check Endpoint Design — альтернатива TCP для HTTP сервисов

SSL Certificate Monitoring — TLS checks для encrypted services

ICMP Ping Monitoring — network-level checks

TCP Check — в AtomPing

FAQ

What is TCP port monitoring?

TCP port monitoring checks whether a specific service is listening and accepting connections on a given port. Unlike HTTP monitoring (which sends an HTTP request), TCP monitoring simply attempts to open a socket connection and checks if the server responds. It works with any service: databases (PostgreSQL port 5432), cache systems (Redis 6379), mail servers (SMTP 25), or custom protocols. If the connection succeeds, the service is reachable.

How is TCP monitoring different from HTTP monitoring?

HTTP monitoring sends a complete HTTP request and checks the response status, content, and headers. TCP monitoring only checks if the port accepts connections (TCP handshake completes). TCP is lighter-weight and works with non-HTTP services (databases, game servers, raw sockets). HTTP provides more detail about service health. Use TCP for services that don't speak HTTP, use HTTP for web APIs.

What are common ports to monitor?

PostgreSQL: 5432. MySQL: 3306. Redis: 6379. MongoDB: 27017. Elasticsearch: 9200. SMTP (mail): 25 or 587. IMAP (mail): 143 or 993 (SSL). SSH: 22. DNS: 53. RDP (Windows remote): 3389. Game servers typically use custom ports. Don't monitor privileged ports below 1024 from untrusted networks. Focus on application-critical services.

How does a TCP connection check work?

TCP handshake: 1) Client sends SYN (synchronization) packet. 2) Server responds with SYN-ACK. 3) Client sends ACK (acknowledgement) back. If all three succeed within timeout, the port is open. If server doesn't respond (timeout) or rejects the connection (RST), the port is closed or the service is down. Connection time is latency metric — slow opens indicate network or server load issues.

How do you combine TCP and HTTP monitoring for full coverage?

Monitor critical services with both: TCP check (is the port accepting connections? detects complete failures), and HTTP check (is the service responding correctly? detects application errors). If TCP passes but HTTP fails, the service is running but unhealthy. If TCP fails but HTTP passes (rare), network/firewall issue between monitor and service. Together they provide defense-in-depth.

What are the limitations of TCP monitoring?

TCP only checks connectivity, not service health. A database might have an open port but be out of memory. A web server might accept TCP connections but return 503 errors. Redis might respond to TCP ping but have insufficient memory. Use TCP for basic 'is it running?' checks. For detailed health, pair with service-specific checks (SQL queries for DB, HTTP requests for web, specific commands for cache).

Start monitoring your infrastructure

Start Free View Pricing