LoginSignup
5
7

More than 5 years have passed since last update.

nginxをデフォルトport以外で起動してnode.jsのAPIを動かすまで

Last updated at Posted at 2019-05-06

nodeでREST-APIを作ってnginxで動かすまでのメモ書き
以前からさくらVPSを使用しており。既にApacheが80番portを使用。
Apacheは設定を結構いじってしまっていたり、すでに複数サービス運用していることから、
この際、お試し用のWEBサーバとしてnginxを立ててみようという経緯

前提

  • port80はすでにapacheで使用している
  • node.jsのExpressを利用してREST-APIを作成
  • 環境はさくらVPS
  • 将来的には複数ドメインでの運用を検討

node.jsのアプリを起動

バックグラウンド実行。
ここら辺は任意の起動法で

$ nohup npm start &

! note
外部に公開する場合はエラー時のブラウザ表示内容に注意!
NODE_ENVがdevelopのままで起動していないか注意してください。
けっこうな情報量を晒すことになります。
対処などはこちらが参考になります

nginxの設定

nginx.conf修正

portをデフォルトの80から81に変更

/etc/nginx/nginx.conf
...
    server {
        listen       81 default_server;
        listen       [::]:81 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

devt-api.conf作成

node.jsのアプリはport3000を使って起動。
外部に公開するportとして4999とする。

/etc/nginx/conf.d/devt-api.conf
upstream sampleAPP {
    server localhost:3000;
}
server {
    listen       4999;
    server_name  {{YOUR_DOMAIN}};
    index        index.php;
    access_log   /var/log/nginx/{{APP_NAME}}.access.log;
    location / {
        proxy_pass http://sampleAPP/;
    }
}

nginxの起動

自動起動設定
$ sudo systemctl enable nginx
起動
$ sudo systemctl start nginx

port 4999開放

このままだと、外部から呼び出せないため、portを開放

port4999を許可
$ firewall-cmd --zone=public --add-port=4999/tcp --permanent
設定を反映
$ firewall-cmd --reload

ブラウザからアクセス

以下のURLでアクセス可能なはず
http://{{YOUR_DOMAIN}}:4999/

SSLの設定

証明書の取得

SSL証明書(Let’s Encrypt)を導入
手順とかは省略
ここらへんがわかりやすかったです。

devt-api.confの編集

証明書と中間証明書のfullchain.pemと秘密鍵のprivkey.pemを追記してあげる

...
server {
    listen       4999 ssl;
    server_name  {{YOUR_DOMAIN}}
    ssl_certificate     /etc/letsencrypt/live/{{YOUR_DOMAIN}}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/{{YOUR_DOMAIN}}/privkey.pem;
...

nginx再起動

再起動
$ sudo nginx -s reload

ブラウザからアクセス

httpsでのアクセス可能になるはず
https://{{YOUR_DOMAIN}}:4999/

5
7
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
5
7