⚡ The main thing in 60 seconds (TL;DR)
⏱ ~ 9 мин чтения- This week, an old story resurfaced in the top: a fresh VPS, ufw default deny incoming, only 22, 80 and 443 appear, and then it appears in the compose file...
- Why this happens has already been discussed in detail.
- I want to talk about something else: how to make sure that such a compose file does not reach the server at all. Below — two small Python scripts.
This week, an old story surfaced in the top again: a fresh VPS, ufw default deny incoming, only 22, 80 and 443 appear, and then ports: - "5432:5432" appears in the compose file - and a couple of days later there is a note with a Bitcoin wallet in the database. Why this happens has already been discussed in detail. I want to talk about something else: how to make sure that such a compose file does not reach the server at all.
Below are two small Python scripts. The first one checks compose files before deployment and crashes with a non-zero code if the port is published to all interfaces. The second one looks at what he actually listens to on the machine, without ss and netstat, straight from /proc. I ran all the code in Python 3.13 and PyYAML 6.0.3, the output in the article is real.
Why isn't the UFW involved?
Briefly, so that it is clear further what we are catching. The Docker documentation explicitly states that Docker and ufw are incompatible: traffic to the container's published ports is redirected in the nat table, that is, before the packets reach the INPUT and OUTPUT chains with which ufw works. ufw rules simply do not apply to such traffic.

Hence the simple conclusion: a firewall on the host is not the line of defense that containers should rely on. It’s safer not to publish unnecessary things at all, but to post what only you need on 127.0.0.1 and go through the SSH tunnel.
Another detail from the same documentation: if the port mapping does not specify a host address, Docker publishes the port to all addresses - both 0.0.0.0 and [::]. That is, "5432:5432" and "0.0.0.0:5432:5432" have the same meaning.
What are the types of port entries?
Compose understands two forms. Short - a string like [host_ip:][published:]target[/protocol]. Long - a dictionary with the keys target, published, host_ip, protocol. We are interested in three cases:
host address - loopback (
127.0.0.1,::1). It's normal;there is no address, the port is clearly allowed for publication (80, 443). This is a conscious decision;
there is no address, and the port is not from the white list. This is what needs to be caught.
A separate unpleasant case is a record of one number, for example "9100". It is often written thinking that it is “just declaring a port.” In fact, Compose will publish container port 9100 to a random host port, and on all interfaces.
Script 1: audit the composite file
Test file on which we will check:
services:
api:
image: myapp/api:1.4
ports:
- "80:8000"
db:
image: postgres:17
ports:
- "5432:5432"
redis:
image: redis:7
ports:
- "127.0.0.1:6379:6379"
adminer:
image: adminer
ports:
- target: 8080
published: 8081
metrics:
image: prom/node-exporter
ports:
- "9100"
The script itself:
import sys
import yaml
SAFE_HOSTS = {"127.0.0.1", "::1", "localhost"}
ALLOWED_PUBLIC = {80, 443}
def parse_short(spec: str):
"""'[host_ip:][published:]target[/proto]' -> (host_ip, published, target)"""
spec = str(spec).split("/")[0]
if spec.startswith("["): # IPv6: [::1]:5432:5432
host, rest = spec[1:].split("]:", 1)
parts = [host] + rest.split(":")
else:
parts = spec.split(":")
if len(parts) == 1:
return "0.0.0.0", None, parts[0]
if len(parts) == 2:
return "0.0.0.0", parts[0], parts[1]
return parts[0], parts[1], parts[2]
def parse_long(item: dict):
return (item.get("host_ip", "0.0.0.0"),
item.get("published"),
item.get("target"))
def audit(path: str) -> int:
with open(path, encoding="utf-8") as f:
data = yaml.safe_load(f)
problems = 0
for name, svc in (data.get("services") or {}).items():
for p in svc.get("ports") or []:
host, published, target = (parse_long(p) if isinstance(p, dict)
else parse_short(p))
if host in SAFE_HOSTS:
status = "ok "
elif published is None:
status = "RANDOM"
problems += 1
elif int(str(published).split("-")[0]) in ALLOWED_PUBLIC:
status = "public"
else:
status = "OPEN "
problems += 1
print(f"{status} {name:<8} {host}:{published or '?'} -> {target}")
return problems
if __name__ == "__main__":
n = audit(sys.argv[1] if len(sys.argv) > 1 else "compose.yaml")
print(f"\nпроблем: {n}")
sys.exit(1 if n else 0)
Launch:
$ python3 compose_audit.py; echo "exit=$?"
public api 0.0.0.0:80 -> 8000
OPEN db 0.0.0.0:5432 -> 5432
ok redis 127.0.0.1:6379 -> 6379
OPEN adminer 0.0.0.0:8081 -> 8080
RANDOM metrics 0.0.0.0:? -> 9100
проблем: 3
exit=1

Three problems out of five services, and this is a fairly typical picture for “quickly fix it, then I’ll fix it.” Redis is correctly tied to the loopback, the API is honestly public, the rest needs to be fixed.
A non-zero return code is the main thing here. Thanks to it, the script without modifications is included in the pre-commit or CI step before deployment: a file with OPEN or RANDOM simply will not pass.
How the parser deals with IPv6, UDP and ranges
I checked the parsing of the short form on several non-obvious lines:
from compose_audit import parse_short
for s in ["5432:5432", "127.0.0.1:6379:6379", "[::1]:5432:5432",
"9100", "53:53/udp", "8000-8005:8000-8005"]:
print(f"{s!r:<26} -> {parse_short(s)}")
'5432:5432' -> ('0.0.0.0', '5432', '5432')
'127.0.0.1:6379:6379' -> ('127.0.0.1', '6379', '6379')
'[::1]:5432:5432' -> ('::1', '5432', '5432')
'9100' -> ('0.0.0.0', None, '9100')
'53:53/udp' -> ('0.0.0.0', '53', '53')
'8000-8005:8000-8005' -> ('0.0.0.0', '8000-8005', '8000-8005')
The protocol is discarded: for the question “does it stick out?” it is not important. The range is checked on the first port - if you need strictness, expand the range and check each one. The script does not substitute variables of the form ${DB_PORT}; if you have them, it’s easier to run an audit on the output docker compose config, where everything is already disclosed.
Script 2: what is actually listening
Static checking catches errors in files, but does not see what was launched manually through docker run -p, or the service that itself decided to listen to 0.0.0.0. Therefore, the second half is to look at a living car.
You can take ss -tlnp, but I wanted something that runs in a minimal container or on someone else's server without unnecessary packages. The kernel already gives the socket table to /proc/net/tcp and /proc/net/tcp6: addresses in hexadecimal, state 0A means LISTEN.
import ipaddress
import socket
import struct
def hex_to_ip(h: str) -> str:
if len(h) == 8: # IPv4, little-endian
return socket.inet_ntoa(struct.pack("<I", int(h, 16)))
# IPv6: четыре 32-битных слова, каждое little-endian
raw = b"".join(struct.pack("<I", int(h[i:i + 8], 16)) for i in range(0, 32, 8))
return str(ipaddress.IPv6Address(raw))
def listeners():
for path in ("/proc/net/tcp", "/proc/net/tcp6"):
with open(path) as f:
next(f)
for line in f:
cols = line.split()
if cols[3] != "0A": # 0A = TCP_LISTEN
continue
ip_hex, port_hex = cols[1].split(":")
yield hex_to_ip(ip_hex), int(port_hex, 16)
if __name__ == "__main__":
for ip, port in sorted(set(listeners()), key=lambda x: x[1]):
addr = ipaddress.ip_address(ip)
scope = "локально" if addr.is_loopback else "СНАРУЖИ"
print(f"{scope:<9} {ip}:{port}")
To check, I set up two test servers - one on all interfaces, the other only on loopback:
$ python3 -m http.server 18080 --bind 0.0.0.0 >/dev/null 2>&1 &
$ python3 -m http.server 18081 --bind 127.0.0.1 >/dev/null 2>&1 &
$ python3 listeners.py | grep 1808
СНАРУЖИ 0.0.0.0:18080
локально 127.0.0.1:18081
Why this also works for containers: by default, Docker has userland-proxy enabled (--userland-proxy=true), and for a published port, a process docker-proxy is raised on the host, which listens to this port. So you'll see 0.0.0.0:5432 in the list. If userland-proxy is disabled, there will be no socket, but the NAT rule will remain - then look in docker ps or in the firewall rules.
Why do addresses in /proc look backwards?
The IPv4 address in /proc/net/tcp is a 32-bit number in host byte order, and on x86 and most ARM machines it is little-endian. Therefore 127.0.0.1 is written as 0100007F. Hence struct.pack("<I", ...) before inet_ntoa. It’s the same with IPv6, only the address is divided into four 32-bit words, and you need to expand each one separately, and not the entire line. The port, on the contrary, is output as a regular hexadecimal number; it just needs to be passed to int(..., 16).
How to repair what you find
For each type of find, the recipe is simple.
OPEN (base, admin, broker). Bind to loopback: "127.0.0.1:5432:5432". From the laptop go through the tunnel: ssh -L 5432:127.0.0.1:5432 user@server, and connect DBeaver to localhost:5432. If the database only needs a neighboring container, section ports is not needed at all: within the same compose network, services see each other by name.
RANDOM. This was almost always an attempt to "announce" a port. For communication between containers, publication is not needed - remove the line. If the port is really needed externally, specify it explicitly and with an address.
Security at the daemon level. You can change the default address for publishing ports in custom bridge networks (and compose creates exactly them). In /etc/docker/daemon.json:
{
"default-network-opts": {
"bridge": {
"com.docker.network.bridge.host_binding_ipv4": "127.0.0.1"
}
}
}
After restarting the daemon, "5432:5432" without an address will only listen to loopback, and public ports will have to be specified explicitly, for example "0.0.0.0:443:443". Please note that this setting does not apply to Swarm services: according to the documentation, they are always published on 0.0.0.0. And one more warning from the same place: in Docker releases older than 28.0.0, even the port on 127.0.0.1 could be accessible to hosts from the same L2 segment. If you have an old Docker, this is a reason to upgrade.

Where to embed it
Both scripts live in my infrastructure repository. compose_audit.py is launched in CI on each compose file, or more precisely on the output of docker compose config, so that the variables and override files are already substituted. listeners.py runs once a day via cron on servers and sends output if the line СНАРУЖИ appears in it with a port not from the list of expected ones.
This is not a replacement for external port scanning from another machine - it is still the best way to see the server through the eyes of a bot. But it answers the question “what is already open”, and the audit of the compose file answers the question “what are we going to open now”. The second question is cheaper to ask in advance.
💬 Discussion 0
BBCode & Emoji supportedParticipate in discussions, ask authors questions, and share benchmarks by joining the ProArena engineering community.