How to run a Rust web application on Platform.sh

Goal

This guide shows how to deploy a simple Rust web app on Platform.sh.

Assumptions

To complete this, you will need:

Problems

Platform.sh does not provide a dedicated Rust runtime container. It will thus be necessary to install Rust as the project is built.

Steps

1. Create a Rust application

Create a new Rust project:

cargo new platform_howto && cd platform_howto

Set the platform remote:

platform project:set-remote <project id>

Add the following under [dependencies] in Cargo.toml:

warp = "0.1"
clap = "2.32.0"

Replace src/main.rs with:

#[macro_use]
extern crate clap;
use clap::{Arg, App};

use warp::Filter;

fn main() {
    let args = App::new("HOWTO")
        .version("1.0")
        .author("Platform.sh <sayhello@platform.sh>")
        .about("How to run a Rust app on Platform.sh")
        .arg(Arg::with_name("port")
             .short("p")
             .long("port")
             .value_name("PORT")
             .help("Sets a custom port")
             .takes_value(true)
             .required(true))
        .get_matches();


    // Get port from command-line arguments
    let port = value_t!(args, "port", u16).unwrap_or_else(|e| e.exit());

    // Match any request and return hello world!
    let routes = warp::any().map(|| "Hello, World!");

    warp::serve(routes)
        .run(([127, 0, 0, 1], port));
}

2. Configure the application to run on Platform.sh:

Add the following to .platform.app.yaml:

name: app

# Any type will work here
type: "php:7.3"

hooks:
    build: |
      set -e
      curl https://sh.rustup.rs > rustup.sh
      sh rustup.sh -y --default-toolchain stable
      rm rustup.sh
      . "$HOME/.cargo/env"
      cargo build --release

web:
    upstream:
        socket_family: tcp
        protocol: http

    commands:
        start: |
          target/release/platform_howto --port $PORT

disk: 1024

Define a route in .platform/routes.yaml:

"https://{default}/":
    type: upstream
    upstream: "app:http"

Add an empty .platform/services.yaml file:

touch .platform/services.yaml

3. Add, commit and push:

git add .
git commit -m "Rust on Platform.sh"
git push platform master

4. Test by visiting the URL of your project:

platform url

Which should open a browser tab showing Hello, World!

Conclusion

Even without a dedicated runtime, running a Rust application on Platform.sh can be done by leveraging the build hook and the PORT variable.

1 Like