axum::serve - Starting the HTTP Server
Learn how axum::serve connects a bound TCP listener to your Router and starts accepting HTTP requests in an Axum application
At this point in building your Axum application, you have a Router with routes and a TcpListener bound to an address. What you still need is the final piece that makes the whole thing actually respond to HTTP requests. That piece is axum::serve.
axum::serve is a function that takes two things you already have - a bound listener and a router - and starts an HTTP server that listens for incoming connections and routes them to your handlers. Once you call this function and await its result, your program stops being a collection of setup code and becomes a live web server.
The Complete Minimal Example
Before diving into details, here is the complete src/main.rs file, including axum::serve.
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The last line is what this page is about. Everything before it sets up the pieces. The axum::serve(listener, app) call takes those pieces and makes the server run.
When you execute this program with cargo run, nothing visible happens in the terminal at first. The program simply keeps running without printing anything. That silence is the server working - it is waiting for a browser or another program to send an HTTP request. If you open http://127.0.0.1:3000 in a browser, you will see Hello, World! appear. The server is alive because axum::serve is running.
What serve Actually Connects
To understand axum::serve, you need to see the two objects it receives as inputs.
The first input is the TcpListener. Think of a TCP listener as a reception desk at a building. The listener has already been bound to an address (like 127.0.0.1:3000) and is capable of accepting new connections. But a listener by itself does not know what to do with the connections it accepts. It just accepts them and hands them off to whoever is listening.
The second input is the Router. A router is like a map of your application. It knows that a GET request to / should go to a specific handler function that returns "Hello, World!". But the router by itself has no way to receive connections. It is just a set of rules waiting to be applied.
axum::serve bridges these two objects. It tells the listener: "Whenever a new connection arrives, take the HTTP request from that connection and send it through this router." The router then figures out which handler to call, the handler produces a response, and serve sends that response back over the connection.
Breaking Down the serve Call
The line axum::serve(listener, app).await.unwrap() does several things at once. Let us look at each piece separately.
Passing the Listener
The first argument is listener. This must be a bound tokio::net::TcpListener. The word "bound" means the listener has already been attached to an address using TcpListener::bind. You cannot pass an unbound listener to serve because there would be no address for the server to listen on.
The listener is moved into the serve call. After calling axum::serve(listener, app), you can no longer use the listener variable. This is Rust's ownership system at work: the listener now belongs to the server that serve creates. That makes sense because the server needs exclusive control over accepting connections.
Passing the Router
The second argument is app, which is your Router. Just like the listener, the router is moved into serve. This means you cannot use app after calling serve. Again, this is correct behavior: the router's job is to handle incoming requests, and the server needs exclusive access to it.
The Future Returned by serve
axum::serve(listener, app) does not immediately start the server. Instead, it returns a special value called a future. A future in Rust is a value that represents work that will happen later, when the future is polled or awaited. Think of it like a movie ticket: the ticket is not the movie itself, but it gives you access to the movie when you show up at the theater.
The future returned by serve is the server. When you call .await on that future, you are telling the Rust runtime: "Run this server now, and keep running it until it stops." The runtime polls the future repeatedly, and each poll allows the server to accept new connections, read requests, call handlers, and send responses.
Serve is Lazy:
Until you call .await on the future returned by axum::serve, no server is running. Creating the future is just preparation. The actual work of listening for connections and responding to requests begins only when the future is awaited.
The unwrap Call
The .await on the serve future produces a Result. If the server runs forever without an error, the Result is Ok(()). If something goes wrong - for example, the listener encounters a fatal error - the Result is an Err containing the error.
Calling .unwrap() on that result tells Rust: "If the server returns an error, crash the program with a panic." For a beginner's Hello World application, this is acceptable because there is nothing meaningful to do if the server fails to start. In a real production application, you would typically log the error and exit gracefully instead of panicking.
unwrap Can Hide Useful Errors:
Using .unwrap() on the serve result means that if the server fails, you get a panic message and a stack trace, but you lose the ability to handle the error in a controlled way. For learning purposes this is fine. For real applications, consider using a match or ? operator (though ? in main requires a return type of Result).
What Happens During the await
When the serve future is awaited, the following sequence takes place:
- The server begins polling the listener for incoming TCP connections.
- When a connection arrives, the server reads the HTTP request from it.
- The server converts the raw request into an Axum request object.
- The request is passed to the router.
- The router matches the request against its registered routes.
- If a match is found, the corresponding handler is called.
- The handler returns a response.
- The server serializes the response into HTTP format and writes it back over the connection.
- The connection is closed (or kept alive for reuse).
- The server goes back to step 1 and waits for the next connection.
This loop continues indefinitely. The serve future only completes if the listener fails with an unrecoverable error, or if the server is shut down gracefully - which does not happen on its own. Pressing Ctrl-C in the terminal sends an interrupt signal (SIGINT) that kills the process outright: the shell reports it as killed by signal 2, any request in progress simply loses its connection, and the serve future never gets a chance to complete. If you want Ctrl-C to shut the server down cleanly - finishing in-flight requests before exiting - you must opt in with .with_graceful_shutdown(...), passing it a future that completes when the signal arrives (usually built with tokio::signal::ctrl_c()). For now, just know that a plain axum::serve(listener, app).await has no graceful shutdown of its own.
Two Ways to Write the serve Call
There are two common styles for writing the serve call. Both do exactly the same thing. Which one you choose is a matter of personal preference or project convention.
Style 1: Single Line with unwrap
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This is the most compact form. Everything happens on one line. It is common in tutorials and small examples because it keeps the code short. The downside is that if the server fails, the panic message does not tell you much about what went wrong beyond the error value.
Style 2: Matching on the Result
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
match axum::serve(listener, app).await {
Ok(()) => println!("Server shut down cleanly."),
Err(err) => eprintln!("Server error: {}", err),
}
}
This version gives you more control. If the server finishes normally (which only happens on shutdown), it prints a clean message. If it fails, it prints the error to standard error without panicking. The program still exits, but it does so with a proper message instead of a panic trace.
For a beginner just learning Axum, the first style is perfectly fine. As you build more complex applications, the second style becomes more useful because it lets you log errors properly.
Common Mistakes with serve
Forgetting to await
The most common beginner mistake with axum::serve is forgetting the .await. If you write:
// This is WRONG - do not do this
axum::serve(listener, app);
Rust will give you a warning that the future is unused, and the server will never actually run. The program will set up the listener and router, create the server future, and then immediately exit because main reaches its end. No requests will ever be served. Always remember the .await.
Using an unbound listener
Another mistake is trying to pass a listener to serve that was never bound. This cannot really happen with tokio::net::TcpListener::bind, because that call always binds the address as part of creating the listener - there is no way to create an unbound Tokio listener in the first place. If you come across TcpListener::from_std, which converts a standard-library listener into a Tokio one, note that it only accepts a std listener whose socket has already been set to non-blocking. Converting an ordinary blocking std listener panics at runtime with a message like Registering a blocking socket with the tokio runtime is unsupported. The normal path is simply to use tokio::net::TcpListener::bind, as in all the examples on this page.
Trying to use the router after serve
Since serve takes ownership of the router, any attempt to use the router afterward will cause a compile error:
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
axum::serve(listener, app).await.unwrap();
// This will not compile - app has been moved into serve
// let another_route = app.route("/foo", get(|| async { "Bar" }));
This is Rust protecting you from a real problem: if you could still modify the router after giving it to the server, the server would have an inconsistent view of the routes. Once the server starts, the router must be immutable (or at least under exclusive control of the server).
Moved Values Cannot Be Reused:
Both listener and app are moved into axum::serve. If you try to use either variable after calling serve, the Rust compiler will refuse to compile your code. This is a compile-time error, not a runtime error, so you will see it immediately when you run cargo check or cargo build. If you need a copy of the router elsewhere, clone it before passing it to serve - Router implements Clone. The listener cannot be cloned or reused after serve takes it, so any setup that needs the listener must happen before the serve call.
serve Without Explicit Imports
The serve function is available directly from the axum crate root. You do not need to import it from any submodule. In your code, you can use it as either axum::serve(listener, app) or import it explicitly:
// src/main.rs
use axum::{routing::get, serve, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
serve(listener, app).await.unwrap();
}
Both forms are identical. Using axum::serve without importing is often clearer in small examples because it makes the function's origin explicit. Importing it directly makes the line shorter and is preferred when you use serve multiple times or want cleaner code.
What serve Is Not
To avoid confusion, it helps to know what axum::serve does not do.
serve does not bind the listener to an address. That job belongs to TcpListener::bind, which you called earlier. serve expects the listener to already be bound. With tokio::net::TcpListener::bind, binding always happens as part of creating the listener, so there is no separate unbound state to worry about - the listener you pass is always ready to accept connections.
serve does not create the router or define routes. That is Router::new and .route. serve just consumes the router you already built.
serve does not parse HTTP requests by itself. The actual HTTP parsing is done by the hyper library, which Axum builds on top of. serve is a thin wrapper that connects hyper's HTTP server to your Axum router.
serve does not handle individual request routing. The router does that. serve just passes requests to the router and takes responses back from it.
Understanding this separation of responsibilities makes the whole Axum flow clearer. Each piece has one job, and serve is the piece that glues the networking side (the listener) to the application logic side (the router).
You Have All the Pieces:
If your main function contains a bound TcpListener, a Router with at least one route, and an axum::serve(listener, app).await.unwrap() call, then you have a complete, working Axum application. When you run it with cargo run and open http://127.0.0.1:3000 in a browser, you will see your handler's response. This is the moment everything comes together.
Handling Multiple Connections
One question beginners often ask is: "Does axum::serve handle multiple connections at once, or do requests have to wait in line?"
The answer is that axum::serve handles many connections concurrently. When a new connection arrives, the server does not block waiting for that connection's request to be fully processed before accepting the next one. Instead, each connection is handled in its own task within the Tokio runtime. The runtime schedules these tasks across available threads, allowing many requests to be processed at the same time.
This is why you need #[tokio::main] at the top of your main function. That macro sets up the Tokio runtime, which is the engine that schedules and runs all these concurrent tasks. Without the runtime, axum::serve would not have the infrastructure to handle multiple connections.
You do not need to write any special code to enable concurrency. It happens automatically because of how Axum and Tokio are designed. The serve future internally spawns a new task for each connection.
serve in Context of the Full Program
Let us look at the complete src/main.rs one more time, with comments explaining the role of each line. This will help you see where axum::serve fits in the overall structure.
// src/main.rs
// Import the pieces we need from axum
use axum::{routing::get, Router};
// This macro sets up the Tokio async runtime
#[tokio::main]
async fn main() {
// Create a router with one route: GET / returns "Hello, World!"
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
// Bind a TCP listener to localhost on port 3000
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
// Start the server: connect the listener to the router
// and run forever until the program is stopped
axum::serve(listener, app).await.unwrap();
}
Each part of this program has a clear job. The import brings in the router and routing utilities. The macro sets up the runtime. The router defines your application's behavior. The listener provides the network connection point. And serve makes the whole thing operational.
What You Will See When the Server Runs
When you run this program with cargo run, you will see something like this in your terminal:
$ cargo run
Compiling my-axum-app v0.1.0
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.23s
Running `target/debug/my-axum-app`
After the Running line, nothing more is printed. The cursor just sits there on a new line. This is the server running. It is waiting for requests.
If you open a web browser and go to http://127.0.0.1:3000, you will see Hello, World! displayed on the page. In your terminal, nothing new will appear. Axum does not print log messages for each request by default.
To stop the server, press Ctrl+C in the terminal where you ran cargo run. The program will terminate, and you will be returned to your shell prompt.
No Output Means the Server Is Working:
Beginners often worry when they see no output after running the server. That silence is normal. The server does not print anything unless you add logging or tracing to your application. If you open the URL in a browser and see your handler's response, the server is working correctly.
Summary
axum::serve is the function that transforms your prepared pieces - a bound listener and a configured router - into a running HTTP server. It takes ownership of both inputs, returns a future that runs forever, and only completes when the server shuts down or encounters a fatal error.
The key insight is that serve is a connector, not a builder. It does not create the listener, define the routes, or parse requests. It simply connects the networking layer (the listener) to the application layer (the router) and keeps that connection running. Once you understand that separation, the role of every line in your minimal main.rs becomes clear.
For the complete beginner, the most important takeaway is this: when you write axum::serve(listener, app).await.unwrap(); as the last line of your main function, you have a working web server. Everything before that line is setup. That line is where the server actually begins.