Bạn có chắc chắn muốn xóa bài viết này không ?
Bạn có chắc chắn muốn xóa bình luận này không ?
Deploy Rust thế nào ?
Hôm nay mình viết một demo nhỏ về deploy một rust project bằng Systemd
1. Start project
Khơi tạo một server bằng cargo
cargo new --bin server
Server này mình sẽ dùng hyper bản mới nhất đông nghĩa với nó đã support tokio rồi nhé. Tokio là một cái tên khá hot trong những tháng vừa qua của Rust :v.
Edit lại file Cargo.toml
[package]
name = "server"
version = "0.1.0"
authors = ["Giang Nguyen <hngnaig@gmail.com>"]
[dependencies]
redis = "0.5.3"
hyper = { git="https://github.com/hyperium/hyper", brand="master" }
futures = "0.1"
Implement một Service mới
extern crate futures;
extern crate hyper;
use self::hyper::server::{Request, Response, Http, Service};
use self::hyper::error::Error;
use self::hyper::status::StatusCode;
use self::hyper::header::{ContentType, ContentLength};
use self::futures::future;
const BODY: &'static str = "Hello!, world";
struct Server;
impl Service for Server {
type Request = Request;
type Response = Response;
type Error = Error;
type Future = future::FutureResult<Response, Error>;
fn call(&self, req: Request) -> Self::Future {
println!("{:?}", req);
future::ok(Response::new()
.with_status(StatusCode::Ok)
.with_header(ContentType::plaintext())
.with_header(ContentLength(BODY.len() as u64))
.with_body(BODY))
}
}
pub fn run() {
let address = "127.0.0.1:3000".parse().unwrap();
let server = Http::new().bind(&address, || Ok(Server)).unwrap();
server.run().unwrap();
}
không được dùng unwrap đối với production, nhưng ở đây mình test nên cố ý cho nó panic
main.rs
mod server;
fn main() {
server::run();
}
Server của ta được start với địa chỉ 127.0.0.1:3000
nhưng làm thế nào để cho nó chạy daemon. Như nodejs thì dùng pm2, đối với loại này chúng ta dùng gì được hiện tại mình thấy có cách là dùng systemd
.
2. Setup systemd
Tạo mới systemd
sudo vi /etc/systemd/system/rust.service
[Unit]
Description=Server Rust
[Service]
Type=simple
ExecStart=/path/server
WorkingDirectory=/projects/server
User=nobody
Group=nogroup
# Allow many incoming connections
LimitNOFILE=infinity
# Allow core dumps for debugging
LimitCORE=infinity
StandardInput=null
StandardOutput=syslog
StandardError=syslog
Restart=always
[Install]
WantedBy=multi-user.target
Install service
sudo systemctl daemon reload
Active service
sudo systemctl enable rust
Vì nó là service nên bạn có thể dùng command service để quản lý xem status, enable hoặc disable service đó.






