Rust integration

Rust logo
⭐ Community Toolkit

The Aspire Rust hosting integration enables you to run Rust applications alongside your Aspire projects in the Aspire app host.

Note

This integration requires cargo to be installed on your system and available in your PATH. For installation instructions, see Install Rust.

Hosting integration

To get started with the Aspire Rust hosting integration, install the CommunityToolkit.Aspire.Hosting.Rust NuGet package in the app host project.

Install the NuGet package
dotnet add package CommunityToolkit.Aspire.Hosting.Rust

Add Rust app

To add a Rust application to your app host, use the AddRustApp extension method:

var builder = DistributedApplication.CreateBuilder(args);
  
var rustApp = builder.AddRustApp(
    name: "rust-api",
    workingDirectory: "../rust-app")
    .WithHttpEndpoint(port: 8080, env: "PORT");
  
builder.AddProject<Projects.ExampleProject>()
       .WithReference(rustApp);
  
// After adding all resources, run the app...

The AddRustApp method requires:

  • name: The name of the resource in the Aspire dashboard
  • workingDirectory: The path to the directory containing your Rust application

Configure endpoints

Rust applications typically use environment variables to configure the port they listen on. Use WithHttpEndpoint to configure the port and set the PORT environment variable:

var builder = DistributedApplication.CreateBuilder(args);
  
var rustApp = builder.AddRustApp("rust-api", "../rust-app")
    .WithHttpEndpoint(port: 8080, env: "PORT");
  
// After adding all resources, run the app...

Your Rust application can read the PORT environment variable to determine which port to listen on:

use std::env;
use actix_web::{web, App, HttpServer, Responder};
  
async fn greet() -> impl Responder {
    "Hello from Rust!"
}
  
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
    let addr = format!("0.0.0.0:{}", port);
  
    println!("Server listening on {}", addr);
  
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(greet))
    })
    .bind(addr)?
    .run()
    .await
}

Custom arguments

You can pass custom arguments to cargo run using the WithArgs method:

var builder = DistributedApplication.CreateBuilder(args);
  
var rustApp = builder.AddRustApp("rust-api", "../rust-app")
    .WithArgs("--release")
    .WithHttpEndpoint(port: 8080, env: "PORT");
  
// After adding all resources, run the app...

Working directory

The workingDirectory parameter specifies where the Rust application is located. The Aspire app host will run cargo run in this directory to start your Rust application.

See also