From 10225c3a856dab1a99b35f9620e6091bc8b32e45 Mon Sep 17 00:00:00 2001 From: Prosper Otemuyiwa Date: Tue, 29 Oct 2024 15:11:25 +0100 Subject: [PATCH] Add Rust Rocket & Axum Guide (#588) * Add rust rocket * Add axum and replace dockerfile content with cargo-chef * Add docs to set PORT * Update to use cargo add * Update to use cargo add * indentation --- src/data/sidebar.ts | 2 + src/docs/guides/axum.md | 203 ++++++++++++++++++++++++ src/docs/guides/languages-frameworks.md | 3 + src/docs/guides/rocket.md | 194 ++++++++++++++++++++++ src/docs/guides/spring-boot.md | 2 +- 5 files changed, 403 insertions(+), 1 deletion(-) create mode 100644 src/docs/guides/axum.md create mode 100644 src/docs/guides/rocket.md diff --git a/src/data/sidebar.ts b/src/data/sidebar.ts index 17840bf6b..6880dda86 100644 --- a/src/data/sidebar.ts +++ b/src/data/sidebar.ts @@ -48,6 +48,8 @@ export const sidebarContent: ISidebarContent = [ makePage("FastAPI", "guides"), makePage("Gin", "guides"), makePage("Rails", "guides"), + makePage("Axum", "guides"), + makePage("Rocket", "guides"), makePage("Laravel", "guides"), makePage("Sails", "guides"), makePage("Django", "guides"), diff --git a/src/docs/guides/axum.md b/src/docs/guides/axum.md new file mode 100644 index 000000000..010001a64 --- /dev/null +++ b/src/docs/guides/axum.md @@ -0,0 +1,203 @@ +--- +title: Deploy a Rust Axum App +--- + +[Axum](https://docs.rs/axum/latest/axum) is a web framework for Rust that focuses on ergonomics and modularity. It is designed to work with [tokio](https://docs.rs/tokio/1.40.0/x86_64-unknown-linux-gnu/tokio/index.html) and [hyper](https://docs.rs/hyper/1.4.1/x86_64-unknown-linux-gnu/hyper/index.html). + +This guide covers how to deploy an Axum app to Railway in four ways: + +1. [One-click deploy from a template](#one-click-deploy-from-a-template). +2. [From a GitHub repository](#deploy-from-a-github-repo). +3. [Using the CLI](#deploy-from-the-cli). +4. [Using a Dockerfile](#use-a-dockerfile). + +Now, let's create an Axum app! 🚀 + +## Create an Axum App + +**Note:** If you already have an Axum app locally or on GitHub, you can skip this step and go straight to the [Deploy Axum App to Railway](#deploy-the-axum-app-to-railway). + +To create a new Axum app, ensure that you have [Rust](https://www.rust-lang.org/tools/install) installed on your machine. + +Run the following command in your terminal to create a new Axum app: + +```bash +cargo new helloworld --bin +``` + +The command creates a new binary-based Cargo project in a `helloworld` directory. + +Next, `cd` into the directory and add `axum` and `tokio` as dependencies by running the following command: + +```bash +cargo add axum +cargo add tokio --features full +``` + +This will add `axum` and `tokio` as dependencies, with `tokio` configured to use the "full" feature, which includes its complete set of capabilities. You’ll find both dependencies listed in your `Cargo.toml` file. + +These dependencies are required to create a bare minimum axum application. + +### Modify the Application File + +Next, open the app in your IDE and navigate to the `src/main.rs` file. + +Replace the content with the code below: + +```rust +use axum::{ + routing::get, + Router, +}; + +#[tokio::main] +async fn main() { + // build our application with a single route + let app = Router::new().route("/", get(root)); + + // Get the port number from the environment, default to 3000 + let port: u16 = std::env::var("PORT") + .unwrap_or_else(|_| "3000".to_string()) // Get the port as a string or default to "3000" + .parse() // Parse the port string into a u16 + .expect("Failed to parse PORT"); + + // Create a socket address (IPv6 binding) + let address = SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 0], port)); + let listener = tokio::net::TcpListener::bind(&address).await.unwrap(); + + // Run the app with hyper, listening on the specified address + axum::serve(listener, app).await.unwrap(); +} + +// basic handler that responds with a static string +async fn root() -> &'static str { + "Hello World, from Axum!" +} +``` + +The code above sets up a simple web server using the Axum framework and the Tokio async runtime. The server listens on the port gotten from the environment variable, `PORT` and defaults to `3000` if there's none set. + +It defines one route, `/`, which is mapped to a handler function called `root`. When a GET request is made to the root path, the handler responds with the static string "Hello World, from Axum!". + +The Router from Axum is used to configure the route, and `tokio::net::TcpListener` binds the server to listen for connections on all available network interfaces (address `0.0.0.0`). + +The asynchronous runtime, provided by the `#[tokio::main]` macro, ensures the server can handle requests efficiently. The `axum::serve` function integrates with the Hyper server to actually process requests. + +### Run the Axum App locally + +Run the following command in the `helloworld` directory via the terminal: + +```bash +cargo run +``` + +All the dependencies will be installed and your app will be launched. + +Open your browser and go to `http://localhost:3000` to see your app. + +## Deploy the Axum App to Railway + +Railway offers multiple ways to deploy your Axum app, depending on your setup and preference. + +### One-Click Deploy from a Template + +If you’re looking for the fastest way to get started, the one-click deploy option is ideal. + +Click the button below to begin: + +[![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/new/template/5HAMxu) + +We highly recommend that [you eject from the template after deployment](/guides/deploy#eject-from-template-repository) to create a copy of the repo on your GitHub account. + +**Note:** You can also choose from a variety of Axum templates created by the community. + +### Deploy from the CLI + +1. **Install the Railway CLI**: + - Install the CLI and authenticate it using your Railway account. +2. **Initialize a Railway Project**: + - Run the command below in your Axum app directory. + ```bash + railway init + ``` + - Follow the prompts to name your project. + - After the project is created, click the provided link to view it in your browser. +3. **Deploy the Application**: + - Use the command below to deploy your app: + ```bash + railway up + ``` + - This command will scan, compress and upload your app's files to Railway. You’ll see real-time deployment logs in your terminal. +4. **Verify the Deployment**: + - Once the deployment completes, go to **View logs** to check if the server is running successfully. + + **Note:** During the deployment process, Railway will automatically [detect that it’s a Rust app](https://nixpacks.com/docs/providers/rust). +5. **Set Up a Public URL**: + - Navigate to the **Networking** section under the [Settings](/overview/the-basics#service-settings) tab of your new service. + - Click [Generate Domain](/guides/public-networking#railway-provided-domain) to create a public URL for your app. + + + +### Deploy from a GitHub Repo + +To deploy an Axum app to Railway directly from GitHub, follow the steps below: + +1. **Create a New Project on Railway**: + - Go to Railway to create a new project. +2. **Deploy from GitHub**: + - Select **Deploy from GitHub repo** and choose your repository. + - If your Railway account isn’t linked to GitHub yet, you’ll be prompted to do so. +3. **Deploy the App**: + - Click **Deploy** to start the deployment process. + - Once the deployed, a Railway [service](/guides/services) will be created for your app, but it won’t be publicly accessible by default. +4. **Verify the Deployment**: + - Once the deployment completes, go to **View logs** to check if the server is running successfully. + + **Note:** During the deployment process, Railway will automatically [detect that it’s a Rust app](https://nixpacks.com/docs/providers/rust). +5. **Set Up a Public URL**: + - Navigate to the **Networking** section under the [Settings](/overview/the-basics#service-settings) tab of your new service. + - Click [Generate Domain](/guides/public-networking#railway-provided-domain) to create a public URL for your app. + +### Use a Dockerfile + +1. Create a `Dockerfile` in the `helloworld` or Axum app's root directory. +2. Add the content below to the `Dockerfile`: + ```bash + FROM lukemathwalker/cargo-chef:latest-rust-1 AS chef + + # Create and change to the app directory. + WORKDIR /app + + FROM chef AS planner + COPY . ./ + RUN cargo chef prepare --recipe-path recipe.json + + FROM chef AS builder + COPY --from=planner /app/recipe.json recipe.json + + # Build dependencies - this is the caching Docker layer! + RUN cargo chef cook --release --recipe-path recipe.json + + # Build application + COPY . ./ + RUN cargo build --release + + CMD ["./target/release/helloworld"] + ``` +4. Either deploy via the CLI or from GitHub. + +Railway automatically detects the `Dockerfile`, [and uses it to build and deploy the app.](/guides/dockerfiles) + +**Note:** Railway supports also deployment from public and private Docker images. + +This guide covers the main deployment options on Railway. Choose the approach that suits your setup, and start deploying your Axum apps seamlessly! + +## Next Steps + +Explore these resources to learn how you can maximize your experience with Railway: + +- [Add a Database Service](/guides/build-a-database-service) +- [Monitor your app](/guides/monitoring) \ No newline at end of file diff --git a/src/docs/guides/languages-frameworks.md b/src/docs/guides/languages-frameworks.md index 576bef373..cb00f065b 100644 --- a/src/docs/guides/languages-frameworks.md +++ b/src/docs/guides/languages-frameworks.md @@ -24,4 +24,7 @@ Learn how to deploy your apps quickly on Railway using your preferred languages - [Gin](/guides/gin) ### Ruby - [Rails](/guides/rails) +### Rust + - [Axum](/guides/axum) + - [Rocket](/guides/rocket) diff --git a/src/docs/guides/rocket.md b/src/docs/guides/rocket.md new file mode 100644 index 000000000..fb45d9d36 --- /dev/null +++ b/src/docs/guides/rocket.md @@ -0,0 +1,194 @@ +--- +title: Deploy a Rust Rocket App +--- + +[Rocket](https://rocket.rs) is a web framework for Rust that makes it simple to write fast, type-safe, secure web applications with incredible usability, productivity and performance. + +This guide covers how to deploy a Rocket app to Railway in four ways: + +1. [One-click deploy from a template](#one-click-deploy-from-a-template). +2. [From a GitHub repository](#deploy-from-a-github-repo). +3. [Using the CLI](#deploy-from-the-cli). +4. [Using a Dockerfile](#use-a-dockerfile). + +Now, let's create a Rocket app! 🚀 + +## Create a Rocket App + +**Note:** If you already have a Rocket app locally or on GitHub, you can skip this step and go straight to the [Deploy Rocket App to Railway](#deploy-the-rocket-app-to-railway). + +To create a new Rocket app, ensure that you have [Rust](https://www.rust-lang.org/tools/install) installed on your machine. + +Run the following command in your terminal to create a new Rust app: + +```bash +cargo new helloworld --bin +``` + +The command creates a new binary-based Cargo project in a `helloworld` directory. + +Next, `cd` into the directory and add Rocket as a dependency by running the following command: + +```bash +cargo add rocket +``` + +This will add Rocket as a dependency, and you’ll see it listed in your `Cargo.toml` file. + +### Modify the Application File + +Next, open the app in your IDE and navigate to the `src/main.rs` file. + +Replace the content with the code below: + +```rust +#[macro_use] +extern crate rocket; + +#[get("/")] +fn index() -> &'static str { + "Hello world, Rocket!" +} + +#[launch] +fn rocket() -> _ { + rocket::build().mount("/", routes![index]) +} +``` + +The code above uses the Rocket framework to create a basic web server that responds to HTTP requests. It defines a simple route using the `#[get("/")]` macro, which tells Rocket to handle GET requests to the root URL `(/)`. + +The `index()` function is the handler for this route and returns a static string, **"Hello world, Rocket!"**, which will be sent as the response when the root URL is accessed. + +The `#[launch]` attribute on the `rocket()` function marks it as the entry point to launch the application. Inside `rocket()`, the server is built with `rocket::build()` and the index route is mounted to the root path `/` using `mount()`. + +When the application runs, it listens for incoming requests and serves the "Hello world, Rocket!" response for requests made to the root URL, demonstrating a simple routing and response mechanism in Rocket. + +### Run the Rocket App locally + +Run the following command in the `helloworld` directory via the terminal: + +```bash +cargo run +``` + +All the dependencies will be installed and your app will be launched. + +Open your browser and go to `http://localhost:8000` to see your app. + +## Deploy the Rocket App to Railway + +Railway offers multiple ways to deploy your Rocket app, depending on your setup and preference. + +### One-Click Deploy from a Template + +If you’re looking for the fastest way to get started, the one-click deploy option is ideal. + +Click the button below to begin: + +[![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/new/template/FkW8oU) + +We highly recommend that [you eject from the template after deployment](/guides/deploy#eject-from-template-repository) to create a copy of the repo on your GitHub account. + +**Note:** You can also choose from a variety of Rocket templates created by the community. + +### Deploy from the CLI + +1. **Install the Railway CLI**: + - Install the CLI and authenticate it using your Railway account. +2. **Initialize a Railway Project**: + - Run the command below in your Rocket app directory. + ```bash + railway init + ``` + - Follow the prompts to name your project. + - After the project is created, click the provided link to view it in your browser. +3. **Deploy the Application**: + - Use the command below to deploy your app: + ```bash + railway up + ``` + - This command will scan, compress and upload your app's files to Railway. You’ll see real-time deployment logs in your terminal. +4. **Set Up a Public URL**: + - Navigate to the **Networking** section under the [Settings](/overview/the-basics#service-settings) tab of your new service. + - Click [Generate Domain](/guides/public-networking#railway-provided-domain) to create a public URL for your app. + + **Note:** You'll come across a 502 error where your application doesn't respond. We'll fix that in the next step. +5. **Configure Rocket app to accept non-local connections**: + - Rocket apps need to be configured to accept external connections by listening on the correct address, which is typically `0.0.0.0`. You can easily do this by setting the address through the environment variable. + Run the following command to set the Rocket address to `0.0.0.0`: + ```bash + railway variables --set "ROCKET_ADDRESS=0.0.0.0" + ``` +6. **Redeploy the Service**: + - Run `railway up` again to trigger a redeployment of the service. +7. **Verify the Deployment**: + - Once the deployment completes, go to **View logs** to check if the server is running successfully. Access your public URL again and you should see your app working well. + + + +### Deploy from a GitHub Repo + +To deploy a Rocket app to Railway directly from GitHub, follow the steps below: + +1. **Create a New Project on Railway**: + - Go to Railway to create a new project. +2. **Deploy from GitHub**: + - Select **Deploy from GitHub repo** and choose your repository. + - If your Railway account isn’t linked to GitHub yet, you’ll be prompted to do so. +3. **Add Environment Variables**: + - Click **Add Variables**, then add `ROCKET_ADDRESS` with the value `0.0.0.0`. This allows your Rocket app to accept external connections by listening on `0.0.0.0`. +3. **Deploy the App**: + - Click **Deploy** to start the deployment process. + - Once the deployed, a Railway [service](/guides/services) will be created for your app, but it won’t be publicly accessible by default. +4. **Verify the Deployment**: + - Once the deployment completes, go to **View logs** to check if the server is running successfully. + + **Note:** During the deployment process, Railway will automatically [detect that it’s a Rust app](https://nixpacks.com/docs/providers/rust). +5. **Set Up a Public URL**: + - Navigate to the **Networking** section under the [Settings](/overview/the-basics#service-settings) tab of your new service. + - Click [Generate Domain](/guides/public-networking#railway-provided-domain) to create a public URL for your app. + +### Use a Dockerfile + +1. Create a `Dockerfile` in the `helloworld` or Rocket app's root directory. +2. Add the content below to the `Dockerfile`: + ```bash + FROM lukemathwalker/cargo-chef:latest-rust-1 AS chef + + # Create and change to the app directory. + WORKDIR /app + + FROM chef AS planner + COPY . ./ + RUN cargo chef prepare --recipe-path recipe.json + + FROM chef AS builder + COPY --from=planner /app/recipe.json recipe.json + + # Build dependencies - this is the caching Docker layer! + RUN cargo chef cook --release --recipe-path recipe.json + + # Build application + COPY . ./ + RUN cargo build --release + + CMD ["./target/release/helloworld"] + ``` +4. Either deploy via the CLI or from GitHub. + +Railway automatically detects the `Dockerfile`, [and uses it to build and deploy the app.](/guides/dockerfiles) + +**Note:** Railway supports also deployment from public and private Docker images. + +This guide covers the main deployment options on Railway. Choose the approach that suits your setup, and start deploying your Rocket apps seamlessly! + +## Next Steps + +Explore these resources to learn how you can maximize your experience with Railway: + +- [Add a Database Service](/guides/build-a-database-service) +- [Monitor your app](/guides/monitoring) \ No newline at end of file diff --git a/src/docs/guides/spring-boot.md b/src/docs/guides/spring-boot.md index 7f301c71e..a4b06426f 100644 --- a/src/docs/guides/spring-boot.md +++ b/src/docs/guides/spring-boot.md @@ -154,7 +154,7 @@ To deploy a Spring Boot app to Railway directly from GitHub, follow the steps be 1. Create a `Dockerfile` in the `helloworld` or Spring Boot app's root directory. 2. Add the content below to the `Dockerfile`: ```bash - # Use the Node alpine official image + # Use the Eclipse temurin alpine official image # https://hub.docker.com/_/eclipse-temurin FROM eclipse-temurin:21-jdk-alpine