LoginSignup
39
23

More than 5 years have passed since last update.

Dockerを使ってHerokuにデプロイする

Last updated at Posted at 2017-12-02

 初投稿です。Rust で書いたウェブアプリケーションが Heroku で動くと嬉しい、という話をします。

ローカルで動かす

 これは、GET /hello-heroku と叩くと "Hello, Heroku!" と喋るアプリケーションです。

Cargo.toml
[package]
name = "hello-heroku"
version = "0.1.0"
authors = []

[dependencies]
shio = "0.2.0"
structopt = "0.1.6"
structopt-derive = "0.1.6"
src/main.rs
extern crate shio;
extern crate structopt;
#[macro_use]
extern crate structopt_derive;

use shio::prelude::*;
use structopt::StructOpt;

#[derive(StructOpt)]
#[structopt(name = "hello-heroku", about = "Hello, Heroku!")]
struct Options {
  #[structopt(short = "p", long = "port", default_value = "7878")]
  port: u16,
}

fn hello_heroku(_: Context) -> Response {
  Response::with("Hello, Heroku!")
}

fn main() {
  let options = Options::from_args();

  Shio::default()
    .route((Method::Get, "/hello-heroku", hello_heroku))
    .run(format!(":{}", options.port))
    .unwrap()
}

structopt という crate が便利なので使うと良いと思います。

$ cargo run -- -p 8000
$ curl localhost:8000/hello-heroku
Hello, Heroku!

楽しい!₍₍ (ง╹◡╹)ว ⁾⁾

Docker で動かす

 これは、アプリケーションを乗せたイメージです。Heroku で動かす場合、公開するポート番号は環境変数 PORT に渡される1ので、そのようにします。

Dockerfile
FROM rust:1.22.1

RUN mkdir /app
COPY ./Cargo.toml /app/Cargo.toml
COPY ./src /app/src
WORKDIR /app
RUN cargo build --release

CMD cargo run --release -- -p $PORT

ビルドにわりと時間かかるのが最高です。私のマシンが非力すぎるという説もある。

$ docker build -t hello-heroku .
$ docker run -it --rm -e "PORT=8000" -p 8000:8000 hello-heroku
$ curl localhost:8000/hello-heroku
Hello, Heroku!

楽しい!₍₍ (ง╹◡╹)ว ⁾⁾

Heroku で動かす

 イメージをプッシュし、アプリケーションをデプロイします。

$ heroku container:push --app YOUR_APP_NAME web

やりました。

$ curl https://YOUR_APP_NAME.herokuapp.com/hello-heroku
Hello, Heroku!

楽しい!₍₍ (ง╹◡╹)ว ⁾⁾

やっていく

 Docker を使うと Heroku にシュッとデプロイできて最高です。SSR (Server-Side Rust) をやっていきましょう。

参考

39
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
23