Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8829

EC2でReactをhttpsでnpm startして外部からアクセスする

$
0
0

EC2上でReactアプリをhttpsでホストすることがあったので備忘録です。

AWSならACMとかELBとかRoute53とか使えるわけですが、
ちょこっとテスト的に動かしてみたいだけなのでできるだけ簡単にSSL化したいと思います。

結論から言うと
HTTPS=trueにしたnpm startでlocalhostでhttpsサーバーを立てて、
EC2外部からのアクセスはnginxでlocalhostにリダイレクトします。

環境

  • EC2 (Amazon Linux 2)
  • React
  • nginx
  • Node.js

1. EC2を立てる

EC2立てます。
http, httpsのポートをあけておきます。

2. nginxインストール・設定

インストール

nginxインストールしますが、Amazon Linux 2ではnginxがyumでサポートされていないらしいので
以下のコマンドでインストールします。

$ sudo amazon-linux-extras install nginx1.12

SSL化設定

SSL化するにあたって証明書を作ります。

$ cd ~ 
$ openssl genrsa 2048 > server.key
$ openssl req -new -key server.key > server.csr
$ openssl x509 -days 365 -req -signkey server.key < server.csr > server.crt
$ sudo mv server.* /etc/nginx/conf.d/
$ cd /etc/nginx/conf.d
$ sudo chown root:root server.*

nginx用の設定ファイルを新規に作成して、
localhostへのリダイレクトを設定します。

$ cd /etc/nginx/conf.d
$ touch ssl_redirect.conf

新規に作成したファイルに以下の内容を記述します。

ssl_redirect.conf
server {
    listen       443 ssl;
    server_name  localhost;
    ssl_certificate      /etc/nginx/conf.d/server.crt;
    ssl_certificate_key  /etc/nginx/conf.d/server.key;
    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

これでnginxの設定が完了です。
nginxを起動、または再起動します。

$ sudo service nginx start
または $ sudo nginx -s reload

3. Node.js, Gitのインストール

$ sudo yum -y install git
$ vim ~/.ssh/id_rsa (gitクローン用に鍵の内容をコピーしときます)
$ chmod 400 ~/.ssh/id_rsa
$ git clone https://github.com/~
node.jsインストール
$ sudo su - root
$ curl -sL https://rpm.nodesource.com/setup_current.x | bash -
$ yum install -y nodejs

4. npm startでhttpsのlocalhostサーバをたてる

npm install
HTTPS=true npm start

以上で設定完了です。
EC2の外部からEC2のパブリックIPにアクセスすると、
EC2のlocalhostにリダイレクトされてhttpsでホストされたReactアプリの確認ができます。


Viewing all articles
Browse latest Browse all 8829

Trending Articles