Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Build and deploy a Rust backend with Shuttle
Roberto Huertas
Roberto Huertas

Posted on • Originally published atrobertohuertas.com on

     

Build and deploy a Rust backend with Shuttle

Learn how to build and deploy a Rust backend withShuttle.

Value proposition

What if I told you that you couldwrite a Rust backend and deploy it for free in the cloud?

What if I told you that you couldget a Postgres database for free, too?

What if I told you that youwouldn’t have to worry about setting the whole infrastructure up? Nor even have to deal with connection strings?

Finally, what if I told you that you coulduse some of the most popular web frameworks available in the Rust ecosystem?

To be honest, I couldn’t believe it myself when I first learnt aboutShuttle, but I can say that they live up to their promise!

And on top of all that, their code is totallyopen-source!

How to use it

Check out thisAxum’sHello World example:

useaxum::{routing::get,Router};usesync_wrapper::SyncWrapper;#[shuttle_service::main]asyncfnaxum()->shuttle_service::ShuttleAxum{letrouter=build_router();letsync_wrapper=SyncWrapper::new(router);Ok(sync_wrapper)}fnbuild_router()->Router{Router::new().route("/",get(hello_world))}asyncfnhello_world()->&'staticstr{"Hello, world!"}
Enter fullscreen modeExit fullscreen mode

And now, let’s compare it to the code that you would write by not usingShuttle at all:

useaxum::{routing::get,Router};#[tokio::main]asyncfnmain(){letrouter=build_router();axum::Server::bind(&"0.0.0.0:8000".parse().unwrap()).serve(router.into_make_service()).await.unwrap();}fnbuild_router()->Router{Router::new().route("/",get(hello_world))}asyncfnhello_world()->&'staticstr{"Hello, world!"}
Enter fullscreen modeExit fullscreen mode

As you can see, both examples arepretty similar.

The only part of code that is different is theentry point of your app. The rest is the same. So, you could potentiallyreuse the same code to deploy it in your own infrastructure if you ever want to get away ofShuttle, thus avoiding thevendor lock-in.

Adding a Postgres database

Adding a database is a piece of cake!

Forget about having to set up a user, dealing with connection strings and all that jazz.Shuttle will inject asqlx pool that you can use right away from your main function to work with your database.

But in order for this to happen, you will have to add a couple of dependencies to yourCargo.toml first:

shuttle-shared-db={version="0.8.0",features=["postgres"]}sqlx={version="0.6.2",features=["runtime-tokio-native-tls","postgres"]}
Enter fullscreen modeExit fullscreen mode

Finally, go to your previous code and add a parameter to your entry point function (note that it is annotated with a macro):

#[shuttle_service::main]asyncfnaxum(#[shuttle_shared_db::Postgres]pool:PgPool)->shuttle_service::ShuttleAxum{// ...}
Enter fullscreen modeExit fullscreen mode

That’s it! You can now start working withsqlx to deal with your new Postgres database.

For the moment,PostgreSQL andMongoDB are the only supported databases.

Initializing the database

Let’s say we want to create a simple table.

Create a file in the root of your project calleddb/schema.sql and add these lines to it:

CREATETABLEIFNOTEXISTStest(idserialPRIMARYKEY,txtvarchar(255)NOTNULL);
Enter fullscreen modeExit fullscreen mode

Now, let’s add a few lines to theaxum function:

#[shuttle_service::main]asyncfnaxum(#[shuttle_shared_db::Postgres]pool:PgPool)->shuttle_service::ShuttleAxum{pool.execute(include_str!("../db/schema.sql")).await.map_err(CustomError::new)?;}
Enter fullscreen modeExit fullscreen mode

With that, every time our service starts, it will try to create thetest table if it doesn’t already exist.

The Shuttle CLI

But, wait a moment!

You may be wondering: “_What if I want to connect to my database with another client (i.e.DBeaver) to inspect its contents or make a custom query?”.

Well, you can. I didn’t mention so far one of themost importantShuttle parts: itsCLI.

Basically, in order to run your code locally and deploy it to the cloud, you’ll need to use a CLI tool calledcargo-shuttle.

In order to install it, just run:

cargo install cargo-shuttle
Enter fullscreen modeExit fullscreen mode

It has lots ofsubcommands to help youset up a project from scratch andmanage it.

Just by runningcargo shuttle init, the CLI will guide you through a set of options that will let you choose, amongst other things, the name and location of your project, and the framework that you want to use.

cli

Just to name a few of the available frameworks:

And no, I didn’t forget about the connection string 😉. Whenever yourun ordeploy your project, ifcargo-shuttle detects you are using a database, it will let you know the connection string, so you can use it on your own.

shuttle axum db

Infrastructure from Code

This is the way they have chosen to describe how they provision all the resources for you (databases, caches, subdomains, static folder…).

As you already saw, they’re usingannotations in your code to understand if you are going to need a database or not, and just depending on that, they will provision that for you.

The idea is that you don’t need to defineinfrastructure as code but thatyour code itself implicitly defines your infrastructure. Pretty cool and impressive, IMHO!

Many more things

There are many more things to discover.

Check out their amazingset of examples, which will get you up to speed in a blink of an eye.

On the other hand, I have prepared asmall GitHub repository showcasing asimple Axum Rest API that uses aPostgres database.

This example is live,here. Feel free to usePostman to play with it. You have the request file availablehere.

Disclaimer

Note that I’m not in any way related toShuttle and this is not a “marketing” post of something like that.

I was so amazed when I discovered their service that I immediately felt the need to share my excitement with the rest of the world 😉

In any case, bear in mind thatthey’re inpublic alpha so the service is not really that stable, and they may change things or even disrupt the service at any time.

Concluding thoughts

I thinkShuttle is agreat project and it’s definitelygood news for the Rust community.

It not only allows us todeploy Rust backends easily for free , but alsoenables lots of web developers coming from other languages toapproach the Rust web development ecosystem and realize thatit’s not as intimidating as one could think in the first place.

Let’s leverage this great opportunity toget involved and be part of this interesting project!

Cheers!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Just a humble software developer wandering through cyberspace. Organizer of @bcnrust. Currently working at @Datadog.
  • Location
    Barcelona
  • Work
    Software Engineer at Datadog
  • Joined

More fromRoberto Huertas

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp