main calls app

Learn how the Rust main function starts an Axum server by calling the app function and passing the Router to axum::serve.

The entry point of every Rust program is a function named main. When you run cargo run, the Rust compiler looks for this function and starts executing code from its first line. In an Axum web server, main has one specific responsibility: build the application, create a network listener, and hand both to Axum's server runtime so it can accept incoming HTTP requests.

Where This Fits in the Project Structure

Before this page, the app function was created to hold the Router that defines all routes. The main function lives in a separate file and calls app to get that Router back. This separation means route definitions stay in one place while server startup logic lives in another.

Think of it like a restaurant. The app function is the menu - it lists everything the kitchen can make. The main function is the host who opens the front door, turns on the lights, and directs customers to the kitchen. The kitchen doesn't need to know how the door works, and the host doesn't need to know every recipe.

The Simplest Possible Main Function

Let's start with the smallest working version. Create a project with these two files:

// src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "Hello from the app function!" }))
}
// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let app = app();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The Cargo.toml file needs these dependencies:

[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }

When you run cargo run, the terminal displays the message and then waits. Open a browser to http://127.0.0.1:3000 and you'll see the greeting text. The server keeps running until you press Ctrl+C.

Working Setup:

If you see "Server running at http://127.0.0.1:3000" in your terminal and the browser displays the greeting, the main function successfully called the app function and started the server.

Understanding What Happens Line by Line

The main function contains four distinct actions, and each one matters. Let's examine them in the order they execute.

1. Building the application

let app = app();

This line calls the app function from lib.rs and stores the returned Router in a variable. The variable name app on the left of the equals sign is different from the function name app() on the right. Rust allows this because one is a variable and the other is a function call. The variable holds a value - the Router - while the function call produces that value.

The Router itself is nothing more than a data structure. It doesn't run anything or listen for connections. It's a map that says "when a request arrives for this path and method, run this handler."

2. Creating the network listener

let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
    .await
    .unwrap();

A TcpListener is a network socket bound to a specific address and port. The address 127.0.0.1 means "this computer only," and port 3000 is the specific channel on that address. When the listener binds successfully, the operating system reserves that port for your program. Any incoming connection to that address and port gets queued for your server to accept.

The .await keyword pauses execution until the binding completes. The .unwrap() extracts the successful result. If binding fails - for example, another program already uses port 3000 - the program panics and stops with an error message.

Port Already in Use:

If you see an error like "Address already in use" when running cargo run, another process is already using port 3000. Stop that process or change the port in the bind address. This is the most common startup failure for beginners.

3. Printing the startup message

println!("Server running at http://127.0.0.1:3000");

This line gives visual confirmation that binding succeeded and the server is about to start. It's a convention, not a requirement. Many production servers log this message with timestamps and log levels, but a plain println! is enough for learning.

4. Serving the application

axum::serve(listener, app).await.unwrap();

This is the line that actually starts the server. axum::serve takes two arguments: the listener (which knows how to accept connections) and the app (which knows how to respond to requests). It runs forever - or until something stops it - accepting every incoming connection, parsing the HTTP request, routing it to the correct handler, and sending back the response.

The .await after axum::serve means the main function pauses here. The server runs in an endless loop, handling request after request. The .unwrap() handles the case where the server itself crashes. Note that without graceful shutdown (covered below), pressing Ctrl+C does not produce a clean exit: the signal kills the process immediately and the .await never completes. Only .with_graceful_shutdown(...) makes serve return normally on Ctrl+C.

The Async Runtime Explained

Notice the attribute above main:

#[tokio::main]
async fn main() {

Rust's standard main function is synchronous - it runs line by line without pausing. But Axum and Tokio need to pause at .await points and resume later when an operation completes. This ability to pause and resume is called asynchronous execution, and it requires a runtime to manage it.

#[tokio::main] is a macro that transforms the async fn main into a regular main function that starts the Tokio runtime. Tokio is the asynchronous runtime that Axum is built on top of. It manages tasks, schedules work across CPU cores, and handles the low-level event loop that notices when network data arrives.

Beginners can think of it this way: the #[tokio::main] attribute is the engine that makes async code actually run. Without it, an async fn main would not compile.

Why main Calls app Instead of Building Routes Directly

You might wonder why the routes aren't built directly inside main. The app function exists for a reason: testability and organization.

When routes live in main, you can only test them by starting the full server and making real HTTP requests. When routes live in a separate app function, you can call that function in a test, send mock requests directly to the Router without any network connection, and check responses. The main function becomes a thin shell that only handles startup concerns.

This pattern - thin main, richer library code - is standard across Rust projects. The lib.rs file contains reusable logic. The main.rs file contains just enough code to launch the application.

Complete Working Example with Multiple Routes

Let's expand the example to show how a more realistic project passes a multi-route application to the server.

// src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(home))
        .route("/about", get(about))
        .route("/health", get(health))
}
async fn home() -> &'static str {
    "Welcome to the home page!"
}
async fn about() -> &'static str {
    "This server demonstrates main calling app."
}
async fn health() -> &'static str {
    "OK"
}
// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let router = app();
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    println!("Listening on http://0.0.0.0:3000");
    axum::serve(listener, router).await.unwrap();
}

The only difference in main is the variable name - router instead of app - and the bind address. Using 0.0.0.0 instead of 127.0.0.1 makes the server accessible from other devices on the same network. For local development, 127.0.0.1 is safer because it restricts access to your machine only.

Handler Visibility:

The handler functions home, about, and health are private to lib.rs. They don't need to be pub because they're only used inside the app function. Only app itself needs to be public so main.rs can call it.

Binding to a Port That May Be Unavailable

The unwrap() on TcpListener::bind causes a panic if the port is taken. A panic terminates the program with an error message, which is acceptable for a beginner project but not graceful. Here's how to handle binding errors more politely:

// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let router = app();
    let listener = match tokio::net::TcpListener::bind("127.0.0.1:3000").await {
        Ok(listener) => listener,
        Err(error) => {
            eprintln!("Failed to bind to port 3000: {}", error);
            eprintln!("Is another server already running on this port?");
            std::process::exit(1);
        }
    };
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, router).await.unwrap();
}

The match expression checks the result of binding. If binding succeeds, the listener is stored and execution continues. If binding fails, an error message goes to stderr (the terminal's error stream) and std::process::exit(1) stops the program with exit code 1, which signals failure to any scripts or tools watching the process.

This version doesn't change the happy path - when the port is free, behavior is identical. It only changes what happens when something goes wrong.

Don't Ignore Bind Errors Silently:

Skipping error handling on bind and letting unwrap panic is fine for learning, but silently continuing after a failed bind is impossible - there's no listener to serve with. Always either panic, exit, or log the error.

Verifying the Server Connection Without a Browser

You don't need a browser to confirm the server works. The curl command, available on macOS, Linux, and modern Windows, makes HTTP requests from the terminal.

With the server running in one terminal, open a second terminal and run:

curl http://127.0.0.1:3000

The response body prints directly in the terminal:

Welcome to the home page!

Try the other routes too:

curl http://127.0.0.1:3000/about
curl http://127.0.0.1:3000/health

Each returns its corresponding text. Seeing these responses proves the whole chain works: main called app, app returned the Router, the listener accepted the connection, and Axum routed the request to the correct handler.

The Order of Operations Matters

There's a specific sequence that must be followed in main. You cannot serve before binding. You cannot bind after serving. Here's the correct order as a checklist:

1

Step 1: Build the Router

Call the app function to get the Router that maps paths to handlers. This is a pure data structure with no side effects.

let app = app();
2

Step 2: Bind the listener

Create a TcpListener bound to an address and port. This reserves the port with the operating system.

let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
    .await
    .unwrap();
3

Step 3: Print the startup message

Confirm to the user that the server is about to start and where to reach it.

println!("Server running at http://127.0.0.1:3000");
4

Step 4: Serve the application

Hand the listener and Router to axum::serve, which accepts connections and dispatches requests until the process stops.

axum::serve(listener, app).await.unwrap();

Skipping step 2 does not even typecheck: there is no "unbound listener" value to pass - TcpListener::bind is an async call that returns a bound listener, and serve requires a type that implements the Listener trait, which the bound TcpListener satisfies. You must await the bind first. Skipping step 1 and building the Router inline inside serve works, but defeats the separation between building the application and starting the server.

Accessing the Router Inside main Without Moving It

Sometimes you want to inspect or log information about the Router before serving it. A Router in Axum implements Clone, so you can duplicate it cheaply:

// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let router = app();
    let router_clone = router.clone();
    println!("Router has been built. Type: {}", std::any::type_name_of_val(&router_clone));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, router).await.unwrap();
}

Cloning a Router is inexpensive because the internal route table uses reference-counted pointers. The clone and the original share the same underlying data. This is useful when you want to pass the same Router to multiple server instances or to a test harness while still serving it.

Changing the Port Without Editing Code

Hardcoding port 3000 works for development but becomes annoying when the port is taken. Environment variables let you change the port at runtime:

// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let router = app();
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    let address = format!("127.0.0.1:{}", port);
    let listener = tokio::net::TcpListener::bind(&address)
        .await
        .unwrap();
    println!("Server running at http://{}", address);
    axum::serve(listener, router).await.unwrap();
}

Run the server on port 8080 without changing any code:

PORT=8080 cargo run

On Windows PowerShell, the syntax differs slightly:

$env:PORT="8080"; cargo run

The std::env::var function reads the environment variable. If it doesn't exist, the unwrap_or_else fallback supplies "3000". The format! macro builds the address string dynamically. This is a common pattern in real applications where deployment platforms set the port through environment configuration.

Binding to a Dynamic String:

TcpListener::bind accepts anything that implements ToSocketAddrs, including &str and String. Passing &address works because &String dereferences to &str.

Running the Server with Multiple Tokio Worker Threads

The #[tokio::main] macro by default starts a multi-threaded runtime. This means Tokio spawns several worker threads - one for each CPU core on the machine - and distributes incoming connections and asynchronous tasks across them.

For most Axum servers, this default is ideal. You don't need to configure anything. But understanding that it's happening helps explain why one async fn main can juggle many connections at once: the runtime schedules work across threads while the main function itself only waits at .await points.

If you need to control the number of threads, the attribute accepts arguments:

// src/main.rs
use axum_project::app;
#[tokio::main(worker_threads = 2)]
async fn main() {
    let router = app();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, router).await.unwrap();
}

Setting worker_threads = 2 forces Tokio to use exactly two threads regardless of CPU count. This is rarely necessary for beginners and usually only relevant in constrained environments or when benchmarking. The default is fine.

Graceful Shutdown with Ctrl+C

Pressing Ctrl+C while the server runs sends a signal that, on its own, would simply kill the process (as above). With .with_graceful_shutdown(...), Axum instead catches that signal, stops the accept loop, drops connections only after in-flight requests finish, and lets the .await after serve complete so main returns normally.

The tokio::signal module provides a way to await the shutdown signal explicitly. That also gives you a place to run cleanup after the server stops, like logging a shutdown message, flushing buffers, or closing database connections:

// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let router = app();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    println!("Press Ctrl+C to shut down");
    axum::serve(listener, router)
        .with_graceful_shutdown(shutdown_signal())
        .await
        .unwrap();
    println!("Server stopped cleanly.");
}
async fn shutdown_signal() {
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install Ctrl+C handler");
}

The with_graceful_shutdown method takes an async function that resolves when shutdown should begin. The shutdown_signal function waits for the Ctrl+C signal. When you press Ctrl+C, the signal fires, shutdown_signal returns, and Axum stops accepting new connections while allowing in-flight requests to finish.

After the server stops, the final println! executes, giving visual confirmation of a clean shutdown. This pattern matters in production where clean shutdown prevents data loss and allows load balancers to drain traffic properly.

What Happens When a Request Arrives

Here's the full sequence of events when a client makes a request to your server:

Client sends HTTP request
        |
        v
TcpListener accepts TCP connection
        |
        v
axum::serve reads raw bytes from the socket
        |
        v
HTTP parser interprets method, path, headers, body
        |
        v
Router matches path and method against route table
        |
        v
Handler function is called with extracted data
        |
        v
Handler returns a response
        |
        v
axum::serve writes response bytes to the socket
        |
        v
Client receives HTTP response

Every step except the handler is handled by Axum and Tokio automatically. The main function's only job in this flow is starting the whole pipeline - it calls app to get the Router, binds the listener, and passes both to serve. After that, main mostly waits.

Testing the Main Function's Wiring

While testing main directly is awkward because it starts a real network server, you can test that main's wiring is correct by testing the app function and confirming that the Router responds correctly:

// tests/app_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
#[tokio::test]
async fn test_home_route() {
    let router = app();
    let response = router
        .oneshot(
            Request::builder()
                .uri("/")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

This test calls the same app function that main calls. It builds a mock HTTP request and sends it directly through the Router without any network connection. The tower::ServiceExt trait provides the oneshot method for making a single request. The test verifies the route returns status 200.

The tower crate is needed as a dev dependency:

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

This test gives confidence that when main calls app and serves it, requests will actually work.

Common Beginner Mistakes

Forgetting the Async Attribute

// Wrong - won't compile
fn main() {
    let app = app();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The .await keyword can only appear inside an async function. Without #[tokio::main] and async fn main, the compiler rejects this code with an error about .await outside an async context. The fix is always to add the attribute and async keyword.

Async Without Runtime:

An async fn main without the #[tokio::main] attribute also won't work - Rust needs to know which runtime to use. The attribute converts the async main into a regular main that starts Tokio.

Wrapping the Router in a Layer Before Serving

Some middleware patterns require applying a layer to the Router before serving. If you forget to apply the layer in app and try to apply it in main, make sure the types line up:

// src/main.rs
use axum_project::app;
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
    let router = app().layer(TraceLayer::new_for_http());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, router).await.unwrap();
}

The layer method wraps the entire Router with middleware. This works because Router provides a .layer() method that applies a Tower Layer to it. The Layer trait itself is implemented by the middleware (for example TraceLayer), not by Router. The key point here is that main can modify the Router before serving it.

Calling app Twice

// Wrong - builds two separate Routers
let router1 = app();
let router2 = app();

There's no harm in calling app twice - each call builds a fresh Router. But beginners sometimes do this accidentally when they mean to clone. If you need the same Router in two places, call app once and use clone() to duplicate it.

Serving the Wrong Variable

let app_function = app;   // function pointer
let app_value = app();    // Router

The name app refers to the function itself. The name app() calls the function and produces a Router. Passing app (without parentheses) to axum::serve won't compile because serve expects a Router, not a function. Always include the parentheses.

Handling the Serve Future Correctly

axum::serve returns a future - an async value that produces a result when awaited. If you don't await it, the future is dropped and the server never starts:

// Wrong - server never runs
axum::serve(listener, app); // missing .await

The compiler warns about unused futures. Always await the result of serve. The same applies to TcpListener::bind - it returns a future that must be awaited to produce the actual listener.

Checking That Everything Compiles

Before running cargo run, run cargo check. This verifies the code compiles without producing an executable, which is faster:

cargo check

If the output ends with a Finished line and no errors, there are no type errors. Then run cargo run to actually start the server.

For a more verbose view of what's happening during compilation, run:

cargo run --verbose

This prints every compilation step, which can help beginners understand the build process, though it's usually too detailed for daily use.

Final Complete Example

Here is everything put together: the library with the app function, the main entry point with graceful shutdown and environment-based ports, and the test that verifies the wiring.

// src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(home))
        .route("/about", get(about))
}
async fn home() -> &'static str {
    "Welcome!"
}
async fn about() -> &'static str {
    "About this server."
}
// src/main.rs
use axum_project::app;
#[tokio::main]
async fn main() {
    let router = app();
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    let address = format!("127.0.0.1:{}", port);
    let listener = match tokio::net::TcpListener::bind(&address).await {
        Ok(listener) => listener,
        Err(error) => {
            eprintln!("Failed to bind to {}: {}", address, error);
            std::process::exit(1);
        }
    };
    println!("Server running at http://{}", address);
    println!("Press Ctrl+C to shut down");
    axum::serve(listener, router)
        .with_graceful_shutdown(shutdown_signal())
        .await
        .unwrap();
    println!("Server stopped cleanly.");
}
async fn shutdown_signal() {
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install Ctrl+C handler");
}
// tests/app_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
#[tokio::test]
async fn test_home_route_returns_ok() {
    let router = app();
    let response = router
        .oneshot(
            Request::builder()
                .uri("/")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_about_route_returns_ok() {
    let router = app();
    let response = router
        .oneshot(
            Request::builder()
                .uri("/about")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the tests with:

cargo test

Run the server with:

cargo run

Or on a custom port:

PORT=8080 cargo run

The key relationship here is that main never builds routes directly. It calls app, receives a fully configured Router, and then focuses exclusively on server startup concerns: binding, logging, and serving. This separation is what makes the project scalable as routes and features grow.

Summary

The main function and the app function work together as a pair. app knows what the server should do - which paths map to which handlers. main knows how to make that available over the network. It creates the listener, binds to an address, prints startup information, and passes the Router to axum::serve, which does the heavy lifting of accepting connections and dispatching requests.

The most important insight is the separation of concerns: main is deliberately thin. All application logic lives in app and the modules it uses. main only knows how to start, serve, and shut down cleanly. This pattern holds across projects of every size, from a two-route learning example to a production API with hundreds of routes.

A useful mental model: think of main as the ignition switch of a car and app as the engine. The ignition switch starts the engine, but it doesn't know how the cylinders fire or the fuel injects. That's the engine's job. Once this split is in place, the thing to check is that running the server still behaves exactly like the single-file version did.