Lantern
Traces Docker Compose port bindings and Docker container port exposure, attributes listening sockets to Docker containers, and can stop containers or safely rewrite Compose port mappings to bind services to localhost.
Lantern
See exactly why your development machine exposes a service — and safely fix it.
Lantern is a local-first security CLI for developers. Instead of merely listing listening port numbers, Lantern traces configuration causality: identifying the exact file and source line in your Docker Compose configuration, container mapping, process, and host network interface responsible for exposing a service, and providing safe, deterministic remediation.
Deep Dive: Read the architectural breakdown on Why Docker Silently Binds to 0.0.0.0 (And How to Trace Port Causality in Go).
1. The Problem
During local software development, services frequently publish ports to wildcard addresses (0.0.0.0 or ::) instead of loopback (127.0.0.1):
# A common docker-compose.yml configuration
services:
db:
image: postgres:16-alpine
ports:
- "5432:5432" # Binds to 0.0.0.0:5432 on all host interfacesWhen this occurs, databases, caches, message brokers, and debug endpoints intended solely for local workstation use become reachable across the local office Wi-Fi, home network, or VPN subnet.
Standard diagnostic tools like ss, netstat, or lsof can tell you that port 5432 is open. However, they cannot answer:
Which container or process published it?
Which configuration file and source line caused it?
Is it reachable from the LAN, VPN, or only localhost?
How can I safely restrict it to localhost without breaking my configuration?
Lantern was built to solve this problem from the inside out.
Related MCP server: lazy-mcp-router
2. Approach: Configuration Causality
Lantern operates passively on your workstation without generating external network traffic:
Passive Socket Collection: Discovers active TCP listening sockets directly from the operating system (
ssand/proc/net/tcp).Process & Container Attribution: Attributes sockets to processes and Docker containers (
docker-proxyor direct process FDs).Causal Source-Line Resolution: Parses Docker Compose files using YAML Abstract Syntax Tree (AST) parsing to locate the exact service declaration and line number.
Reachability Classification: Enumerates host network interfaces (
net.Interfaces()) to classify whether a listening socket is restricted to loopback (127.0.0.1), accessible to the local network (LAN reachable), or bound to a VPN.Fail-Closed Remediation: Provides
lantern fixto restrict wildcard Docker Compose bindings to127.0.0.1:5432:5432with cryptographic TOCTOU checks, byte-verified backups, and atomic writes.
3. Terminal Demonstration
Discovery (lantern scan)
$ lantern scan
PORT ADDRESS PROCESS CONTAINER REACHABILITY
5432 0.0.0.0 docker-proxy postgres LAN reachable
8080 127.0.0.1 node - localhost onlyCausal Explanation (lantern why 5432)
$ lantern why 5432
postgres :5432
EXPOSURE PATH
docker-compose.yml
↓
5432:5432
↓
Docker container: postgres
↓
0.0.0.0:5432
↓
eth0 (192.168.1.50)
↓
LAN reachable
ROOT CAUSE
/home/user/app/docker-compose.yml:6
5432:5432
REACHABILITY
Local machine: YES
LAN: YES
Internet: UNKNOWN
RECOMMENDED CHANGE
127.0.0.1:5432:5432
Bind published port to localhost (127.0.0.1) in /home/user/app/docker-compose.yml to prevent local network exposure.Safe Remediation Preview (lantern fix 5432 --dry-run)
$ lantern fix 5432 --dry-run
Lantern Fix
Port: 5432
Root cause: /home/user/app/docker-compose.yml:6
Current:
5432:5432
Proposed:
127.0.0.1:5432:5432
This will modify:
/home/user/app/docker-compose.yml
Dry-run mode: no changes will be made.
Backup that would be created: /home/user/app/docker-compose.yml.lantern.bakApplying Remediation (lantern fix 5432)
$ lantern fix 5432
Lantern Fix
Port: 5432
Root cause: /home/user/app/docker-compose.yml:6
Current:
5432:5432
Proposed:
127.0.0.1:5432:5432
This will modify:
/home/user/app/docker-compose.yml
A backup will be created before modification.
Apply this change? [y/N]: y
Fix applied successfully.
Before:
5432:5432
After:
127.0.0.1:5432:5432
Backup:
/home/user/app/docker-compose.yml.lantern.bakContext-Aware Port Freeing (lantern free 5432 / lantern kill 5432)
Blunt utilities (kill -9 or npx kill-port) blindly terminate processes. When a port is owned by Docker, killing docker-proxy corrupts Docker's userland networking state. Lantern Free inspects what actually owns the port before taking action:
If held by a Docker container, it stops the container cleanly via the Docker API.
If held by a native process, it safely terminates the process.
$ lantern free 5432
Port 5432 is currently occupied by Docker container:
Container: postgres-dev (ID: c1234567890a)
Image: postgres:16-alpine
Project: my-backend (service: db)
Stop this container? [y/N]: y
[OK] Docker container "postgres-dev" stopped. Port 5432 is now free.Preview without taking action using --dry-run. In scripts, use -y / --yes to skip the prompt; the process still gets a graceful shutdown (SIGTERM, then SIGKILL after --timeout). -f / --force skips the prompt and kills immediately, which can lose unflushed data, so avoid it for databases:
lantern free 5432 --dry-run
lantern free 5432 -y
lantern free 5432 -f # immediate SIGKILL4. Installation
Option A: Shell Installer (Linux, macOS, WSL2)
The fastest way to install or update Lantern:
curl -fsSL https://raw.githubusercontent.com/DhyaanKanoja11/Lantern/main/install.sh | bashThe script automatically:
Detects operating system and architecture (
amd64/arm64).Downloads the official release binary.
Verifies cryptographic integrity against
checksums.txt(SHA-256).Installs to
/usr/local/bin(or~/.local/binif running without root privileges).Verifies whether the installation path is present in
$PATH, detecting your shell environment (bash,zsh,fish) and providing exact copy-pasteable persistence commands when necessary.
To install a specific version:
curl -fsSL https://raw.githubusercontent.com/DhyaanKanoja11/Lantern/main/install.sh | LANTERN_VERSION=v0.3.0 bashTo uninstall:
curl -fsSL https://raw.githubusercontent.com/DhyaanKanoja11/Lantern/main/install.sh | bash -s -- --uninstallOption B: Homebrew (macOS & Linuxbrew)
Install via the official tap:
brew tap DhyaanKanoja11/tap
brew install lanternTo upgrade:
brew upgrade lanternOption C: Windows Package Managers
1-Line PowerShell Installer
The fastest way to install or update Lantern on Windows:
irm https://raw.githubusercontent.com/DhyaanKanoja11/Lantern/main/install.ps1 | iexScoop
Install via the official Scoop bucket:
scoop bucket add dhyaan https://github.com/DhyaanKanoja11/scoop-bucket
scoop install lanternOr install directly via the standalone manifest:
scoop install https://raw.githubusercontent.com/DhyaanKanoja11/Lantern/main/packaging/scoop/lantern.jsonWinGet (Submission Pending Review)
Once approved in microsoft/winget-pkgs:
winget install DhyaanKanoja11.Lantern(Manifest is available in packaging/winget/).
Option D: Linux Packages (.deb, .rpm, AUR)
Arch Linux (AUR):
yay -S lantern-bin(PKGBUILD is available in
packaging/aur/).Debian / Ubuntu (.deb): Download the
.debarchive from Releases and install:sudo dpkg -i lantern_<version>_linux_amd64.debFedora / RHEL (.rpm): Download the
.rpmarchive from Releases and install:sudo rpm -i lantern_<version>_linux_amd64.rpm
Option E: Pre-Compiled Release Binaries
Download standalone pre-compiled archives directly from the Releases page:
Platform | Architecture | Archive |
Linux |
|
|
Linux |
|
|
macOS | Apple Silicon ( |
|
macOS | Intel ( |
|
Windows |
|
|
Verify archive integrity:
sha256sum --ignore-missing -c checksums.txtOption F: Go Install or Build from Source (Go 1.22+)
Install directly via go install:
go install github.com/DhyaanKanoja11/Lantern/cmd/lantern@latestOr clone the repository and build from source:
git clone https://github.com/DhyaanKanoja11/Lantern.git
cd Lantern
go install ./cmd/lanternEnsure your Go bin directory is in your PATH:
export PATH="$(go env GOPATH)/bin:$PATH"Shell Completion
Generate tab-completion scripts for bash, zsh, fish, or powershell:
# Bash (current session)
source <(lantern completion bash)
# Bash (persistent on Linux)
lantern completion bash | sudo tee /etc/bash_completion.d/lantern > /dev/null
# Zsh (persistent)
lantern completion zsh > "${fpath[1]}/_lantern"
# Fish (persistent)
lantern completion fish > ~/.config/fish/completions/lantern.fish# PowerShell (current session)
lantern completion powershell | Out-String | Invoke-ExpressionRun lantern completion --help for full setup details per shell.
5. Quick-Start Example
A self-contained demo configuration is provided in examples/:
# 1. Start a demo PostgreSQL database with a wildcard port binding (0.0.0.0:5432)
cd examples
docker compose up -d
# 2. Check environment prerequisites
lantern doctor
# 3. Discover exposed listening sockets
lantern scan
# 4. Trace why port 5432 is reachable
lantern why 5432
# 5. Preview safe remediation without writing to disk
lantern fix 5432 --dry-run
# 6. Safely apply the fix (creates verified backup and updates docker-compose.yml)
lantern fix 5432
# 7. Teardown
docker compose down6. Practical Command Reference
Command | Description | Example |
| Discovers active TCP listeners. Supports output formats ( |
|
| Explains the complete causal exposure path from network socket to configuration source line. Supports |
|
| Context-aware port freeing: cleanly stops Docker containers or terminates native processes occupying a port. Aliased as |
|
| Preflight collision checker: detects port conflicts and wildcard exposures before running |
|
| Interactively remedies supported Docker Compose wildcard exposures to localhost. |
|
| Starts the Model Context Protocol (MCP) stdio server for AI agents (Claude Code, Cursor, Windsurf). |
|
| Runs diagnostic probes checking host OS, |
|
| Generates shell tab-completion scripts for |
|
| Prints semantic version, commit hash, build date, and target architecture. |
|
| Displays usage instructions, flag descriptions, and POSIX exit codes. |
|
CI/CD Security Guardrails
Prevent accidental wildcard bindings (0.0.0.0 or ::) from reaching production by running Lantern in CI using the official GitHub Marketplace Action:
- name: Audit Port Exposures
uses: DhyaanKanoja11/lantern-action@v1
with:
fail-on-wildcard: 'true'
ignore-ports: '80,443'Or run directly via CLI:
lantern scan --fail-on-wildcard --ignore-ports 80,443When run inside GitHub Actions (GITHUB_ACTIONS=true), Lantern automatically emits native error annotations directly on the pull request diff and exits with a non-zero code to block insecure configurations.
GitHub Code Scanning & SARIF Integration
Generate standard OASIS SARIF v2.1.0 reports to populate GitHub's native Security → Code scanning alerts dashboard:
lantern scan --format sarif > lantern.sarifUpload the report directly in your GitHub Actions workflow:
- name: Audit Port Exposures (SARIF)
run: lantern scan --format sarif > results.sarif
continue-on-error: true
- name: Upload to GitHub Security Tab
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarifTeam Policy Configuration (.lantern.yaml)
Define shared port security rules for your repository by adding a .lantern.yaml file to your project root:
version: 1
policy:
fail_on_wildcard: true
ignore_ports:
- 80
- 443When .lantern.yaml is present, lantern scan automatically applies the policy in local development and CI without requiring long CLI flags.
Pre-Commit Hook Integration
Automatically audit active ports and prevent committing insecure configurations with pre-commit:
Add to your .pre-commit-config.yaml:
repos:
- repo: https://github.com/DhyaanKanoja11/Lantern
rev: v0.3.0
hooks:
- id: lantern-scan
args: ["--fail-on-wildcard", "--ignore-ports", "80,443"]Live Terminal Watch Mode
Continuously monitor network listeners and container ports as you start and stop development services:
lantern scan --watch
# Or specify a custom refresh interval:
lantern scan -w --interval 5sAI Coding Agent Integration (Model Context Protocol / MCP)
Lantern includes a native Model Context Protocol (MCP) stdio server, allowing AI coding assistants—including Claude Code, Claude Desktop, Cursor, and Windsurf—to inspect network exposure, trace port causality, and safely reclaim ports during autonomous execution.
Adding to Claude Code
Connect Lantern to Claude Code via the CLI:
claude mcp add lantern lantern mcpAdding to Claude Desktop / Cursor / Windsurf
Add the following configuration to your MCP configuration file (claude_desktop_config.json, .cursor/mcp.json, or .windsurf/mcp.json):
{
"mcpServers": {
"lantern": {
"command": "lantern",
"args": ["mcp"]
}
}
}Installing via Smithery
npx -y @smithery/cli install lanternExposed MCP Tools
Tool Name | Parameters | Description |
| (none) | Scans active TCP listeners on the host, returning structured process, container, and reachability classifications. |
|
| Traces causal exposure path for a port down to the exact |
|
| Safely reclaims an occupied port by cleanly stopping its Docker container or terminating its host process. |
|
| Pre-inspects a Compose file to detect and prevent |
| (none) | Runs diagnostic environment readiness checks for socket collection and Docker connectivity. |
7. Comparison with Existing Tools
Lantern does not compete with network scanners or socket dumpers; it bridges the gap between low-level socket inspection and developer configuration files:
Capability |
|
|
| Lantern |
Inspects local listening sockets | Yes | Yes | Probes remotely | Yes |
Attributes socket to Docker container | No | No | No | Yes |
Pinpoints source line in Docker Compose | No | No | No | Yes ( |
Classifies interface reachability (LAN/VPN) | No | No | Partial | Yes |
Zero external network traffic (passive inside-out) | Yes | Yes | No (sends packets) | Yes |
Deterministic, fail-closed remediation | No | No | No | Yes ( |
ssandnetstatquery kernel socket tables directly. They tell you that a socket is open on0.0.0.0:5432, but provide no configuration awareness.lsofmaps open file descriptors to process IDs, but cannot trace container published ports back to Compose definitions.nmapis an active network scanner that sends network packets over the wire. It answers what an external observer sees, but cannot identify why your workstation configuration exposes the service.Lanterninspects the system from the inside out, correlating sockets, processes, container inspect metadata, and YAML configuration files.
8. Supported Platforms and Limitations
Operating System Support
Platform | Support Level | Behavior |
Linux (kernel 3.10+) | Primary | Full native functionality ( |
WSL2 | Primary | Full native functionality inside WSL2 Linux environments. |
macOS | Primary | Full native functionality via |
Windows | Primary | Full native functionality via Win32 |
Technical Capabilities & Guardrails
Cross-Platform Socket Inspection: Socket discovery operates natively without virtual machines: Linux uses
ssand/proc/net/tcp, macOS uses nativelsof -iTCP -sTCP:LISTEN, and Windows uses native Win32netstat -ano -p tcp.Unprivileged Process Inspection & Inferred Attribution: When running as an unprivileged user on Linux (UID > 0), root-owned sockets (such as
docker-proxy) cannot have their PIDs or file descriptors read directly from/proc. Lantern automatically falls back to Docker published port metadata inference, clearly tagging the attribution asINFERRED, rendering an explicitATTRIBUTION NOTICEexplaining the unverified PID inlantern why, and restrictinglantern fixto read-only--dry-rundiffs until verified with root/sudo.Docker Daemon Diagnostic Guidance: If the Docker daemon is stopped, socket permission is denied, or the Docker CLI is not installed,
lantern scancontinues to collect and display listening host sockets while rendering actionable diagnostic notices beneath the table.Supported Remediation Scope:
lantern fixis strictly designed for Docker Compose configurations. It does not attempt to modify arbitrary native application configurations (e.g., PostgreSQLpostgresql.confor Redisredis.conf) where configuration syntaxes vary unpredictably.Variable Interpolation (
${PORT:-5432}:5432): Ports that use variables are resolved from your shell environment and the.envfile next to the compose file, sowhycan still point at the right line. Because the value atdocker compose uptime may have been different, these matches are always reported asLIKELY SOURCE, neverROOT CAUSE, andlantern fixwon't rewrite them (doing so would replace your variable with a hard-coded port). If a variable isn't set and has no default,whysays so instead of quietly skipping the line.Host Networking (
--net=host): Containers running in host network mode share the host network stack directly. Lantern attributes them only when PID correlation is established.Conservative Reachability: Wildcard bindings (
0.0.0.0or::) are classified asLAN reachablewithInternet: UNKNOWN. Lantern never claims a service is publicly accessible over the Internet without verified external routing evidence.
9. Security and Safety Model
The remediation engine (lantern fix) is built around a 10-layer fail-closed safety pipeline:
Read-Only by Default: Discovery and diagnostic commands (
scan,why,doctor,version) never write to disk or mutate system state.Explicit Confirmation: The interactive prompt defaults to
No([y/N]). Remediation requires an explicit affirmative answer (yoryes).Dry-Run Inspection:
--dry-runperforms full causal analysis and renders the before/after modification without creating temporary files or backups.Cryptographic TOCTOU Protection: Computes a SHA-256 fingerprint of the configuration file during analysis and re-verifies it immediately before writing. If the file was modified, moved, or deleted by another process, Lantern aborts cleanly.
No Automatic Replanning: If file modification is detected, Lantern never attempts to guess or re-apply a stale plan; it halts and requests that you re-run the command.
Byte-Verified Backup: Generates a sequenced backup (
docker-compose.yml.lantern.bak) and verifies byte equality against the original before touching the target file. Existing backups are never overwritten.YAML AST Precision: Targets the exact YAML AST node corresponding to the exposed port. Comments, indentation, unrelated services, and environment variables are preserved intact.
AST Invariant Verification: Validates the modified YAML structure in memory before writing to disk, ensuring that syntax remains valid and only the intended port publication was modified.
Atomic Replacement: Writes changes to a temporary file in the target directory, calls
syncto flush data to disk, and replaces the target file via atomic filesystemrename.Post-Fix Verification: Re-reads the modified file from disk after writing and re-parses it with the Compose parser to verify that the port is bound to
127.0.0.1. If verification fails, the original backup is preserved and the error is reported.
Privacy Guarantee: Lantern performs zero external network telemetry, zero analytics tracking, and runs no background daemons.
10. Architecture & Development
For an in-depth explanation of Lantern's internal layering, package boundaries, data flows, and design decisions:
ARCHITECTURE.md— Layered architecture, domain purity, and data pipeline.Why Docker Silently Binds to 0.0.0.0 — DEV Community technical deep dive on port causality and exposure detection.
CONTRIBUTING.md— Local development workflow, code style, and PR guidelines.SECURITY.md— Security policy and vulnerability disclosure procedures.CHANGELOG.md— Version history and release notes.
Verification Suite
All contributions must pass the verification suite:
# Run unit and hermetic integration tests
go test -count=1 ./...
# Run race condition detector
go test -race ./...
# Run static analysis and formatting checks
go vet ./...
gofmt -s -l .
# Multi-platform compilation check
GOOS=linux GOARCH=amd64 go build ./cmd/lantern
GOOS=linux GOARCH=arm64 go build ./cmd/lantern
GOOS=windows GOARCH=amd64 go build ./cmd/lantern
GOOS=darwin GOARCH=arm64 go build ./cmd/lanternContributing
Contributions of all skill levels are welcome! Check out CONTRIBUTING.md for local environment setup, architecture guidelines, and our open Good First Issues.
11. License
Lantern is licensed under the MIT License.
Available Tools
4 toolslantern_doctorA
Run diagnostic environment checks for socket collection, Docker access, and system tools.
Inputs: no named parameters.
lantern_freeA
Safely reclaims an occupied TCP port. Checks whether the port is held by a Docker container or host process and terminates it cleanly without breaking Docker networking.
Inputs: port (required), force.
lantern_scanB
Discover active TCP listening services on the host machine, including process attribution, Docker container correlation, and network reachability classification (localhost, LAN, VPN).
Inputs: no named parameters.
lantern_whyA
Explain why a specific network service or port is reachable. Traces the socket back to its process, Docker container, source docker-compose.yml file and line, and network interface reachability.
Inputs: port (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
Each tool has a clearly distinct role: scan discovers services, why explains reachability for a specific service/port, free reclaims a port, and doctor checks environment health. The boundaries between discovery, explanation, remediation, and diagnostics are easy to distinguish.
All names use the same lantern_ prefix and short, predictable suffixes. The suffixes scan, why, free, and doctor are concise and consistently styled, making the set easy to remember.
Four tools is well-scoped for a focused network-port diagnostic and remediation server. Each tool covers a necessary part of the workflow without redundant surface area.
The set covers the core lifecycle: discover services, explain reachability, reclaim a port, and diagnose environment issues. Minor gaps exist around continuous monitoring or more targeted container/process inspection, but agents can work around them.
Maintenance
Related MCP Connectors
IaC, CI and dependency security review for coding agents: local scan CLI plus hosted OAuth MCP.
Security audit for docker-compose.yml — 25 checks: secrets, privileges, network, volumes, images.
MCP deployment checks: required tools, schema drift and verifiable receipts. Free preflight.
Capability-routed CLI/MCP: signed provenance exports, WCAG-validated themes, sovereign deploy modes.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceDefensive credential-exposure auditor for GKE that inventories workload identity, service account tokens, and RBAC posture, exposing findings via an MCP server at /mcp.Apache 2.0
- FlicenseAqualityDmaintenanceSafety-first local MCP tool gate with control plane, runtime security, and observability for managing MCP backends.4-
- AlicenseBqualityDmaintenanceA local, evidence-driven MCP runtime and control plane for open-source maintainers that provides workspace-bounded tools including controlled file operations, command execution, validation primitives, durable execution records, and human review workflows via stdio and Streamable HTTP transports.33MIT
- AlicenseAqualityBmaintenanceA secure, local-first MCP server for read-only inspection and troubleshooting of development environments, exposing narrow, typed, auditable capabilities for repository inspection, log summarization, Docker review, and security scanning without granting unrestricted machine access.8MIT