5
8

More than 3 years have passed since last update.

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

Posted at

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アプリの確認ができます。

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