LoginSignup
644
642

More than 5 years have passed since last update.

スマホアプリ開発時にさくっと叩けるAPIサーバをnginx・Let’s encrypt・JSON Serverで構築する

Last updated at Posted at 2016-05-17

目的

スマホアプリ開発の初期段階でまだAPIの仕様等がフワっとしているような状況で、さくっと試験用のAPIサーバーを立てて、APIをちょこちょこいじってみながらアプリ開発をしたい。
ローカルマシンにJSON ServerでAPIサーバ立てるのが一番早そうだったけど、どうせならネットワーク上に置いてHTTPSでAPI叩いてみたいよね、ってことで構築してみた。

完成予定図

スマホアプリ開発用PC
↓↑
HTTPS(Let’s encrypt)
↓↑
Nginx(:443)
↓↑
JSON Server(:3000)
※ サーバはEC2使ってますがお好みに合わせてどうぞ

構築手順

1. AWSとドメインの準備

1. 管理コンソール等からEC2インスタンスを立ち上げる

  • 今回はOSは Amazon Linux AMI 2016.03.1 (HVM) を選択
  • インスタンスタイプはt2.microを選択
  • Security groupで22番ポートと443番ポートは開けておく

2. ElasticIPを1個払い出す

  • 払い出したElasticIPを立ち上げたインスタンスにassociateする
  • 払い出したElasticIPとAPI用のドメイン名をDNSに登録する(適当なドメイン名がない場合には要取得)

2 .Node.jsのインストール

# nvmをインストールする
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.1/install.sh | bash

# Node.jsのLTSバージョンをインストールする(ここはお好みで)
$ nvm install v4.4.4

# インストールしたNode.jsの設定 + デフォルトver.として指定する
$ nvm use 4.4.4
$ nvm alias default 4.4.4

# インストールされたNode.jsのver.を確認する
$ node -v

3. json-serverのインストール

$ npm install -g json-server

でOK

APIの内容を定義(db.json)

db.json
{
  "users": [],
  "keywords": [
    {
      "id": 1,
      "text": "hoge"
    },
    {
      "id": 2,
      "text": "fuga"
    },
    {
      "id": 3,
      "text": "piyo"
    }
  ],
  "articles": []
}

json-serverにdb.jsonを与えて起動
立ち上げ時にルーティング内容が出力される。

$ json-server db.json

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/users
  http://localhost:3000/keywords
  http://localhost:3000/articles

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database

エンドポイントにアクセスしてみる

$ curl http://localhost:3000/keywords
[
  {
    "id": 1,
    "text": "hoge"
  },
  {
    "id": 2,
    "text": "fuga"
  },
  {
    "id": 3,
    "text": "piyo"
  }

OK

4. Let’s encryptで無料のSSL証明書を取得

Let’s encryptのインストール

# install
sudo yum install git
git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt
# confirm
./letsencrypt-auto --help

# 証明書の発行
sudo ./letsencrypt-auto certonly -a standalone -d ドメイン名 --debug

# 発行に成功した場合下記パスに秘密鍵とサーバ証明書と中間証明書が結合されたファイルが出力されているのでnginxのSSL設定時に利用
# /etc/letsencrypt/live/ドメイン名/privkey.pem
# /etc/letsencrypt/live/ドメイン名/fullchain.pem

5. nginx(443番ポート)でリクエストを受けてjson-server(3000番ポート)にアクセスを流す

# nginxのインストール
$ yum install -y nginx

# nginxの設定
$ vim /etc/nginx/nginx.conf

設定ファイルの中の # Settings for a TLS enabled server. 以下のコメントアウトを外して設定

    server {
        listen       443 ssl;
        listen       [::]:443 ssl;
        server_name  ドメイン名;  # 修正1
        root         /usr/share/nginx/html;

        ssl_certificate "/etc/letsencrypt/live/ドメイン名/fullchain.pem”; # 修正2
        ssl_certificate_key "/etc/letsencrypt/live/ドメイン名/privkey.pem”; # 修3
        # It is *strongly* recommended to generate unique DH parameters
        # Generate them with: openssl dhparam -out /etc/pki/nginx/dhparams.pem 2048
        #ssl_dhparam "/etc/pki/nginx/dhparams.pem";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP;
        ssl_prefer_server_ciphers on;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
                proxy_pass http://localhost:3000; # 修正4
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

nginxの起動

$ service nginx start

6. HTTPSでAPIサーバにアクセスしてみる

スクリーンショット 2016-05-17 16.11.50.png

ふむふむ、良さそうですね。

スクリーンショット 2016-05-17 16.12.19.png

よすよす。

あとは JSON Serverのドキュメントを見ながらAPIKit等でガシガシAPI叩きましょう!

7. まとめ

nginx・Let’s encrypt・JSON Serverを使って、さくっと叩けるAPIサーバを構築してみた。
ドメイン周りの設定さえ終わっていれば、10分前後でHTTPSでAPIを叩ける状態までイケると思います。

参考

Amazon Linuxに Node.js と npm を入れる
【個人メモ】JSON Serverを使って手っ取り早くWebAPIのモックアップを作る
JSON Server

644
642
2

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
644
642