Run Actix web, ~~Rocket~~, ~~Warp~~ on AWS Lambda
Cargo.toml
```toml [[bin]] name = "bootstrap" path = "src/main.rs"
[dependencies] lambda-web = { version = "0.1.0", features=["actix4"] } ```
main.rs
```rust use lambdaweb::actixweb::{self, get, App, HttpServer, Responder}; use lambdaweb::{isrunningonlambda, runactixon_lambda, LambdaError};
async fn hello() -> impl Responder { format!("Hello") }
async fn main() -> Result<(),LambdaError> { let factory = move || { App::new().service(hello) };
if is_running_on_lambda() {
// Run on AWS Lambda
run_actix_on_lambda(factory).await?;
} else {
// Local server
HttpServer::new(factory)
.bind("127.0.0.1:8080")?
.run()
.await?;
}
Ok(())
} ```
Currentry (Jun 2021), we have two options to run Rust on AWS Lambda: Amazon Linux 2 custom runtime or Docker container image.
I recommend Amazon Linux 2 custom runtime deploy because it's faster cold start time than container image.
To build Amazon Linux 2 compatible binary, it's better to build inside container. First, build Amazon Linux 2 container with Rust toolchain. This repository contains sample Dockerfile .
```console $ git clone https://github.com/hanabu/lambda-web ... $ docker build -t lambda_builder lambda-web/docker ...
or $ buildah bud -t lambda_builder lambda-web/docker ... ```
Once you get lambda_builder image, then build your code with Amazon Linux.
```console $ cd yourappcratedir $ docker run -it --rm -v ~/.cargo/registry:/root/.cargo/registry:z -v .:/build:z lambdabuilder ...
or $ podman run -it --rm -v ~/.cargo/registry:/root/.cargo/registry:z -v .:/build:z lambda_builder ... ```
Then, you get deploy ZIP package in yourappcratedir/targetlambda/deploy.zip .
Make sure, your Cargo.toml has bootstrap
binary name.
toml
[[bin]]
name = "bootstrap"
path = "src/main.rs"
provided.al2
custom runtime. Choose "Provide your own bootstrap on Amazon Linux 2" .