# How should a Rust web server choose its port and address?
Source: https://ruststudio.org/community/t/13/how-should-a-rust-web-server-choose-its-port-and-address
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: web, deployment, configuration | Views: 0

## Short answer
Read the address from configuration, not from the source code. Accept a full LISTEN_ADDR, else a PORT bound to loopback, else a default. Behind a reverse proxy listen on 127.0.0.1 so only the proxy can reach the app; listen on 0.0.0.0 only when the app must accept outside connections itself.

## Answer
## Answer
A server that hard-codes `0.0.0.0:8080` cannot move to another port without a rebuild, and it is reachable from the whole network whether you meant it or not. Read the address from the environment instead, and choose a safe default.

```rust title=src/main.rs
use std::net::SocketAddr;

/// The address to listen on: LISTEN_ADDR, else a port from PORT (on loopback), else a default.
fn listen_addr(get: impl Fn(&str) -> Option<String>) -> SocketAddr {
    if let Some(a) = get("LISTEN_ADDR").and_then(|a| a.parse().ok()) {
        return a;
    }
    if let Some(p) = get("PORT").and_then(|p| p.trim().parse::<u16>().ok()) {
        return SocketAddr::from(([127, 0, 0, 1], p)); // behind a web server, loopback only
    }
    SocketAddr::from(([127, 0, 0, 1], 8080))
}

fn main() {
    println!("{}", listen_addr(|k| std::env::var(k).ok()));
    println!("{}", listen_addr(|k| (k == "PORT").then(|| "5000".to_string())));
    println!("{}", listen_addr(|k| (k == "PORT").then(|| "not a port".to_string())));
    println!("{}", listen_addr(|k| (k == "LISTEN_ADDR").then(|| "0.0.0.0:9000".to_string())));
}
```

```text
127.0.0.1:8080
127.0.0.1:5000
127.0.0.1:8080
0.0.0.0:9000
```

The environment is passed in as a function so the code can be tested without changing real environment variables.

| Address | Reachable from | Use when |
|---|---|---|
| `127.0.0.1:PORT` | the same machine only | a reverse proxy (IIS, nginx, Caddy) forwards requests to the app |
| `0.0.0.0:PORT` | every network interface | the app itself accepts outside connections (a container, a simple host) |
| `[::1]:PORT` / `[::]:PORT` | the IPv6 equivalents | IPv6 setups |

## Common mistakes
- Binding `0.0.0.0` on a development machine and leaving a debug server open to the network.
- Treating a bad `PORT` value as a crash. Fall back, or print the value you rejected so the mistake is visible.
- Two programs on one port: the second fails to start with "address already in use". Pick a different port or stop the first.

## Related questions
### Does the host's firewall matter?
Yes. Listening on `0.0.0.0` still needs the firewall to allow the port for outside access.

## Sources
- Standard library, `std::net::SocketAddr`: https://doc.rust-lang.org/std/net/enum.SocketAddr.html
