Deployment

Because it's a bummer when your laptop runs out of battery and makes your server inaccessible.

Running code locally is all well and good, but how about actually running it on a server somewhere in the cloud? Not many people want to (or have the capability to!) run an always-on home server, so most code is deployed elsewhere. This can be an arduous and annoying process, especially for such a simple server.

Luckily for us, we're writing in rust and have a service called shuttle.rs at our disposal! We'll be able to run our code with very minor changes, in the cloud, easy peasy.

Start off by installing shuttle if you haven't already

cargo install cargo-shuttle

Next, let's add some extra dependencies for shuttle, namely these two:

shuttle-aws-rds = { version = "0.7", features = ["postgres"] }
shuttle-service = { version = "0.7", features = ["web-thruster"] }

These will allow shuttle to hook into our service. It'll also provide a cloud database for us. Integrating with our existing app is super simple, we just add another entrypoint in lib.rs

// Had to add a bunch of dependencies for below
use app::{Ctx, ServerConfig};
use shuttle_service::error::CustomError;
use sqlx::{Executor, PgPool};
use thruster::{HyperServer, ThrusterServer};

pub mod app;
pub mod controllers;
pub mod models;

// New bit here!
#[shuttle_service::main]
async fn shuttle(
    #[shuttle_aws_rds::Postgres] pool: PgPool,
) -> shuttle_service::ShuttleThruster<HyperServer<Ctx, ServerConfig>> {
    pool.execute(include_str!("../schema.sql"))
        .await
        .map_err(CustomError::new)?;

    let app = app::app(pool).await.expect("Could not create app");
    Ok(HyperServer::new(app))
}

Believe it or not, that's all the additional setup we need! We just need to run a few shuttle commands now. If you haven't signed in yet, you'll need to run

cargo shuttle login

Then setup a new shuttle project

cargo shuttle project new

Finally, run (you might need --allow-dirty if you haven't been committing using git as you go along!)

cargo shuttle deploy

That's it! You're deployed! Try running the curl commands from earlier and see if they still work (they should! Congrats!)

Next up we'll be making a quick little CLI to automate the generation and retrieval of secrets.

Last updated