listen address field

Learn what the listen_address field holds, how a socket address is parsed from text, and how changing the value moves the server to a different port or interface

The listen_address field is the AppConfig field that says where the server listens. It holds a socket address, which is an IP address plus a port number, such as 127.0.0.1:3000. The program reads the field at startup, binds a network listener to it, and every request the server answers arrives through that address. Change the value and the server moves: a different port, a different interface, or both.

Where This Fits

The struct page built the whole AppConfig and the database page followed the first field to the pool. This page follows the second field to the network. The field is the only place the bind address is decided, which means main never contains a fixed address string, and the same server binary listens wherever the environment tells it to. The value arrives as text from the LISTEN_ADDRESS variable, and the loader turns it into a SocketAddr before anything else sees it, so a malformed address fails at startup instead of at the bind call.

Think of the address as the street address of a shop. The IP address is the street, and the port is the door number. A shop on the local street with door number 3000 is reachable only by people already in the building, while a shop on every street with door number 8080 is reachable by anyone who can find the building. The field is the sign on the door, and the server is the shop behind it.

The Smallest Working Version

Start with the struct, the loader line for this field, and a main that binds to the loaded address and serves one route. The only dependency beyond the config is Axum itself.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
dotenvy = "=0.15.7"
src/config.rs
use std::net::SocketAddr;

#[derive(Clone)]
pub struct AppConfig {
    pub database_url: String,
    pub listen_address: SocketAddr,
    pub rust_log: String,
    pub jwt_secret: String,
}

impl AppConfig {
    pub fn from_env() -> Result<AppConfig, String> {
        let database_url = std::env::var("DATABASE_URL").map_err(|_| {
            "DATABASE_URL must be set, for example \
             postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"
                .to_string()
        })?;
        let listen_address = std::env::var("LISTEN_ADDRESS")
            .unwrap_or_else(|_| "127.0.0.1:3000".to_string())
            .parse::<SocketAddr>()
            .map_err(|_| {
                "LISTEN_ADDRESS must be an address like 127.0.0.1:3000".to_string()
            })?;
        let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
        let jwt_secret =
            std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set".to_string())?;
        Ok(AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        })
    }
}
src/lib.rs
pub mod config;
src/main.rs
use axum::{routing::get, Router};
use axum_project::config::AppConfig;

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let config = match AppConfig::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("Configuration error: {error}");
            std::process::exit(1);
        }
    };
    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}
.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=127.0.0.1:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development

Run it with cargo run and the server prints where it is listening. Request the route and the greeting comes back.

Listening on http://127.0.0.1:3000
curl http://127.0.0.1:3000/
Hello, world!

Working Setup:

If the greeting comes back, the field works. The address was read from the environment, parsed into a socket address, bound by the operating system, and the server is answering on it. Everything later on this page is a variation on that one chain.

What a Socket Address Is

A socket address has two parts, and both are numbers the operating system understands. The IP address picks the network interface, which is the network connection the traffic arrives on. The port picks the channel on that interface, a number from 0 to 65535 that tells the operating system which program the traffic belongs to. Many programs can share one machine because each one listens on a different port.

The three addresses a beginner meets most often are these. 127.0.0.1 is the loopback address, which always means the machine the program itself runs on. Traffic sent to it never leaves the machine, so only programs on the same computer can reach the server. 0.0.0.0 means every interface at once: the server accepts traffic on the loopback address, on the local network address, and on any other interface the machine has. [::1] is the IPv6 form of the loopback address, written with brackets because the colons inside an IPv6 address would otherwise clash with the colon before the port.

The port in the default value, 3000, is a convention for development servers. It has no special meaning to the operating system; it is simply a port that is usually free and easy to remember. Ports below 1024 are privileged on Linux and macOS, which means binding to them needs administrator rights, so development servers stay above that range. Port 80 is the standard HTTP port and 443 is the standard HTTPS port, and a server that listens on either one is reached without a port in the URL.

How the Text Becomes an Address

The loader line does three things, and each one is visible in the code. std::env::var("LISTEN_ADDRESS") reads the variable. .unwrap_or_else(|_| "127.0.0.1:3000".to_string()) supplies the default when the variable is not set. .parse::<SocketAddr>() turns the string into a socket address, and .map_err(...) turns a parse failure into a readable message.

The parse step is strict, and its strictness was checked by parsing a list of strings and recording what each one does. The results are the rules a beginner needs, with no guessing.

TextResult
127.0.0.1:3000Parses, the usual loopback address
0.0.0.0:8080Parses, every interface on port 8080
[::1]:3000Parses, the IPv6 loopback address
localhost:3000Fails, hostnames are not resolved here
3000Fails, an address needs an IP and a port
127.0.0.1:99999Fails, the port is out of range
127.0.0.1:0Parses, and the operating system picks a port

The localhost failure is the one that catches the most people. Parsing a socket address does not look up hostnames: it reads the text as numbers and dots, and localhost is a name, not numbers. The fix is the numeric form, 127.0.0.1:3000. A program that needs hostname lookup resolves the name first with a different call and then builds the address from the result, but this field takes the numeric form directly, and the loader rejects anything else.

Port 0 is a special case worth knowing. It parses fine, and binding to it asks the operating system to pick a free port. That is useful in tests, where the test does not care which port it gets, and harmful in a server a human needs to find, because the port changes on every run. The validation page rejects port 0 for the server for exactly that reason, and the test below shows how to read the chosen port back.

Parsing Does Not Resolve Names:

SocketAddr parsing accepts IP addresses only. A hostname such as localhost or db.example.com is rejected with invalid socket address syntax, and the fix is the numeric address. If a value that looks right fails to parse, check whether it contains a name instead of numbers before changing anything else.

The Concept Behind Binding

Binding is the act of asking the operating system to reserve an address and a port for one program. TcpListener::bind makes that request, and the operating system answers in one of two ways: the listener is created, and the port is reserved, or the bind fails because something else already holds that address and port. Two programs cannot listen on the same address and port at the same time, and the second one fails with Address already in use.

The listener does not serve anything by itself. It only accepts incoming connections and queues them. axum::serve takes the listener and the router and does the serving: accepting each connection, reading the request, routing it, and writing the response. The field's job ends at the bind call. Everything after that is the listener and the server doing their work with the address the field supplied.

A useful way to think about it is a phone number. The IP address is the area code, the port is the extension, and binding is plugging the phone in. Until the phone is plugged in, nobody can call, and the number on the bill is just text. After binding, the number is live, and calls arrive at the program that plugged the phone in.

Why the Field Is a SocketAddr and Not a String

The bind call takes anything that can be turned into socket addresses, including a string, so storing the field as a String would compile. The struct stores a SocketAddr anyway, for two reasons.

The first is that a bad address fails once, at load time, instead of at every use. A string field would carry the typo all the way to the bind call, and a handler that formats the address for a response would carry it there too. A parsed field carries only valid addresses, because an invalid one never gets into the struct.

The second is that the parts are available separately. A SocketAddr has .ip() and .port() methods, so code that needs just the port, or just the address, reads it without splitting a string by hand. Splitting by hand is where bugs hide: an IPv6 address contains colons, so splitting on : gives the wrong pieces, while the parsed type handles both address families correctly.

Moving the Server with the Environment

The point of the field is that the server moves without a code change. Start the server with a different value for LISTEN_ADDRESS and it listens somewhere else. The .env file stays untouched, because a variable set in the shell wins over the file for that one run.

LISTEN_ADDRESS=127.0.0.1:4001 cargo run

The server prints its new address, and the route answers there.

Listening on http://127.0.0.1:4001
curl http://127.0.0.1:4001/
Hello, world!

A request to the old port fails, because nothing is listening there any more. That was checked by running the server on 4001 and requesting port 3000: the connection was refused. The old port is not forwarded or redirected; it is simply empty, and the failure is the proof that the value, not the code, decides where the server lives.

The same mechanism moves the server onto every interface. With the value 0.0.0.0:8080 in the .env file, the server prints Listening on http://0.0.0.0:8080 and answers requests sent to 127.0.0.1:8080, because the loopback interface is one of the interfaces 0.0.0.0 covers. That run was checked directly, and the route answered on 8080 while port 3000 stayed silent.

A Variable Set in the Shell Wins for One Run:

A value written before the command, such as LISTEN_ADDRESS=127.0.0.1:4001 cargo run, sets the variable for that one run only, and it beats the .env file. The file is unchanged, and the next plain cargo run listens on the file's value again. That is how a developer tries a different port for one run without editing anything.

Listening on Every Interface

The difference between 127.0.0.1 and 0.0.0.0 is who can reach the server. On 127.0.0.1, only the same machine can connect. That is the safe default for development: the server is reachable from the developer's own browser and from nothing else. On 0.0.0.0, any machine that can reach this machine over the network can connect, including other devices on the same Wi-Fi and, when the machine is exposed, the wider internet.

That reach is sometimes exactly what is needed, such as testing the server from a phone on the same network, or running it in a container where the traffic arrives on the container's network interface rather than the loopback. It is also a risk when it is set by accident, because a development server with no login suddenly answers the whole network. The rule is to use 127.0.0.1 unless there is a concrete reason to use 0.0.0.0, and to know which one is in the file before starting the server.

# Development, same machine only
LISTEN_ADDRESS=127.0.0.1:3000

# Reachable from the local network, use only when needed
LISTEN_ADDRESS=0.0.0.0:8080

The port can change at the same time as the interface, and the two choices are independent: 127.0.0.1:8080 listens on the loopback on port 8080, and 0.0.0.0:3000 listens everywhere on port 3000. The field holds both choices in one value, and the parse step checks both at once.

A Port the Operating System Picks

Tests do not want a fixed port, because two test runs on the same machine would collide, and a fixed port might already be in use. Port 0 solves that: the operating system picks a free port, and the test reads it back from the listener with local_addr, which returns the address the listener actually bound to.

#[tokio::test]
async fn port_zero_gets_an_os_assigned_port() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .unwrap();
    let address = listener.local_addr().unwrap();
    assert_ne!(address.port(), 0);
    assert_eq!(address.ip().to_string(), "127.0.0.1");
}

The test binds, asks the listener for its own address, and checks that the port is no longer zero and the IP is still the loopback. That pattern is the right one for a test that starts a real server: bind to port 0, read the address back, and send requests to the address that came back. A server meant for humans never uses port 0, because the port changes on every run and nobody would know where to find it.

How the Value Flows

The value travels from the environment to the operating system in four steps, and the field is the only place it is stored.

LISTEN_ADDRESS in the environment or .env
        |
        v
parse into SocketAddr in from_env
        |
        v
listen_address field in AppConfig
        |
        v
TcpListener::bind reserves the address and port
        |
        v
axum::serve answers requests on that address

A failure in the first two steps is a configuration error with a message from the loader. A failure at the bind step is an operating system error, usually Address already in use, which means the value parsed fine but the port is taken. The two failures look different, and they are fixed differently: one by correcting the text, the other by stopping the other program or picking a different port.

Testing the Field

The field is tested in two ways: parsing checks that run with no network, and a bind check that opens a real listener on a port the operating system picks.

tests/listen_address_test.rs
use std::net::SocketAddr;

use axum_project::config::AppConfig;

#[test]
fn listen_address_parse_rules() {
    assert!("127.0.0.1:3000".parse::<SocketAddr>().is_ok());
    assert!("localhost:3000".parse::<SocketAddr>().is_err());
    assert!("[::1]:3000".parse::<SocketAddr>().is_ok());
    assert!("3000".parse::<SocketAddr>().is_err());
    assert!("127.0.0.1:99999".parse::<SocketAddr>().is_err());
    assert!("0.0.0.0:8080".parse::<SocketAddr>().is_ok());
}

#[test]
fn loader_applies_the_default_address() {
    std::env::set_var(
        "DATABASE_URL",
        "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config",
    );
    std::env::remove_var("LISTEN_ADDRESS");
    std::env::set_var("RUST_LOG", "info");
    std::env::set_var("JWT_SECRET", "test-secret-only-for-local-development");
    let config = AppConfig::from_env().unwrap();
    assert_eq!(config.listen_address.to_string(), "127.0.0.1:3000");
}

#[test]
fn loader_rejects_a_hostname_address() {
    std::env::set_var(
        "DATABASE_URL",
        "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config",
    );
    std::env::set_var("LISTEN_ADDRESS", "localhost:3000");
    std::env::set_var("RUST_LOG", "info");
    std::env::set_var("JWT_SECRET", "test-secret-only-for-local-development");
    let error = match AppConfig::from_env() {
        Ok(_) => panic!("expected from_env to fail with a hostname address"),
        Err(error) => error,
    };
    assert!(error.contains("LISTEN_ADDRESS"), "{error}");
}

#[tokio::test]
async fn port_zero_gets_an_os_assigned_port() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .unwrap();
    let address = listener.local_addr().unwrap();
    assert_ne!(address.port(), 0);
    assert_eq!(address.ip().to_string(), "127.0.0.1");
}

Run them with:

cargo test --test listen_address_test -- --test-threads=1

All four pass. The first proves the parse rules, the second proves the default, the third proves a hostname value fails in the loader with a message naming the field, and the fourth proves a port 0 bind receives a real port. The --test-threads=1 flag matters here for the same reason as before: the loader tests set process-wide variables, and parallel tests would read each other's values.

Common Beginner Mistakes

Writing localhost instead of the numeric address

# Wrong - the parser does not resolve hostnames
LISTEN_ADDRESS=localhost:3000

The loader fails with LISTEN_ADDRESS must be an address like 127.0.0.1:3000. The fix is the numeric form, 127.0.0.1:3000, which means the same machine and parses cleanly.

Writing only the port

# Wrong - an address needs an IP and a port
LISTEN_ADDRESS=3000

The parse fails for the same reason: a socket address is two parts, and a bare number is only one of them. The fix is the full form, 127.0.0.1:3000.

Starting a second server on the same port

# The first server is still running on port 3000, and the second fails
cargo run

The second server panics at the bind call with Address already in use. The fix is to stop the first server, or to start the second on a different port with LISTEN_ADDRESS=127.0.0.1:4001 cargo run.

Binding to 0.0.0.0 Exposes the Server to the Network:

A server on 0.0.0.0 answers any machine that can reach it, and a development server usually has no login. Check the value in the file before starting the server, and keep 127.0.0.1 as the default unless the server genuinely needs to be reachable from another machine.

Requesting the old port after moving the server

# Wrong - the server moved to 4001, and nothing listens on 3000 any more
curl http://127.0.0.1:3000/

The connection is refused, and the error looks like the server is broken, when the server is fine and listening somewhere else. The fix is to read the Listening on line the server printed at startup and request that address.

Final Complete Example

Everything on this page put together is one project: the config module, the server that binds to the loaded address, the .env file that sets it, and the tests that prove the parse rules and the default.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
dotenvy = "=0.15.7"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=127.0.0.1:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development
src/config.rs
use std::net::SocketAddr;

#[derive(Clone)]
pub struct AppConfig {
    pub database_url: String,
    pub listen_address: SocketAddr,
    pub rust_log: String,
    pub jwt_secret: String,
}

impl AppConfig {
    pub fn from_env() -> Result<AppConfig, String> {
        let database_url = std::env::var("DATABASE_URL").map_err(|_| {
            "DATABASE_URL must be set, for example \
             postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"
                .to_string()
        })?;
        let listen_address = std::env::var("LISTEN_ADDRESS")
            .unwrap_or_else(|_| "127.0.0.1:3000".to_string())
            .parse::<SocketAddr>()
            .map_err(|_| {
                "LISTEN_ADDRESS must be an address like 127.0.0.1:3000".to_string()
            })?;
        let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
        let jwt_secret =
            std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set".to_string())?;
        Ok(AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        })
    }
}
src/lib.rs
pub mod config;
src/main.rs
use axum::{routing::get, Router};
use axum_project::config::AppConfig;

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let config = match AppConfig::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("Configuration error: {error}");
            std::process::exit(1);
        }
    };
    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}

Run the checks with these commands:

cargo check
cargo test --test listen_address_test -- --test-threads=1
cargo run

Then move the server without touching the code:

LISTEN_ADDRESS=127.0.0.1:4001 cargo run
curl http://127.0.0.1:4001/

The greeting comes back from the new port, and the old port answers nothing.

Summary

The field is the server's address in typed form, parsed once at startup and used once at the bind call, and that narrow job is what makes it reliable. A string would carry typos forward to the bind; a parsed socket address cannot, because the typo fails in the loader. The two choices the value carries, which interface and which port, are independent, and the defaults make the common case work with no configuration at all.

The decision framework is about reach. Use 127.0.0.1 when only the same machine should connect, which is the default and the safe choice for development. Use 0.0.0.0 when another machine genuinely needs to reach the server, and check the value before starting, because that choice is also a decision about who the server trusts. And when the port is taken or the address is wrong, read the startup line first: it says exactly where the server is, and the difference between that line and the address being requested is usually the whole problem.