» Rust: Build a REST API with Rocket » 3. Deployment » 3.1 Standalone

Standalone Deployment

Tune address and port

Add address config item in infrastructure/config/mod.rs:

@@ -24,6 +24,7 @@ pub struct CacheConfig {
 
 #[derive(Debug, Deserialize, Serialize)]
 pub struct ApplicationConfig {
+    pub address: String,
     pub port: i32,
     pub page_size: u32,
     pub token_secret: String,

Put its value in config.toml:

@@ -1,4 +1,5 @@
 [app]
+address = "127.0.0.1"
 port = 8000
 page_size = 5
 token_secret = "I_Love_LiteRank"

Apply these config items in main.rs:

@@ -17,7 +17,11 @@ fn rocket() -> _ {
     let wire_helper = application::WireHelper::new(&c).expect("Failed to create WireHelper");
     let r = adapter::make_router(&wire_helper);
     rocket::build()
-        .configure(rocket::Config::figment().merge(("port", c.app.port)))
+        .configure(
+            rocket::Config::figment()
+                .merge(("port", c.app.port))
+                .merge(("address", c.app.address)),
+        )
         .manage(r)
         .mount(
             "/",

Build Steps

Add Makefile:

# Binary name
BINARY_NAME=lrbooks

.PHONY: lint

lint:
	@echo "Linting..."
	cargo clippy

build:
	@echo "Building $(BINARY_NAME)..."
	cargo build --release --bin $(BINARY_NAME)

Clippy is a well-known linting tool for the Rust.

Update Cargo.toml to include the bin:

@@ -3,6 +3,10 @@ name = "lr_rest_books_rust"
 version = "0.1.0"
 edition = "2021"
 
+[[bin]]
+name = "lrbooks"
+path = "src/main.rs"
+

Run make build to build a binary:

make build

This is equivalent to cargo build --release --bin lrbooks. It will create a binary file named lrbooks in your project’s target/release folder.

Make sure you have the config.toml config file in your project root directory, and all yours databases are ready to serve.

Then, you can just run it as a standalone server:

./target/release/lrbooks

You will see the start message like this:

🚀 Rocket has launched from http://127.0.0.1:8000

Send some requests with curl, you should be able to see some success responses.

It works like a charm! ⭐️