0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EC2でnginxを使おうと思っている過去の自分へ

Last updated at Posted at 2025-03-23

0. はじめに

どうも、絶賛インフラ勉強中の筆者です。
苦戦したEC2へのnginxの導入を未来の自分がここに残すので、過去の自分はこれを見てスムーズに構築してください。

1. 筆者の環境

EC2
プラットフォーム:Linux/UNIX
AMI:Amazon Linux 2 Kernel 5.10 AMI 2.0.20250305.0 x86_64 HVM gp2

2. 導入方法

2-1. install

sudo yum update
sudo amazon-linux-extras install nginx1 -y

2-2. confファイルの設定

sudo nano /etc/nginx/nginx.conf

参考程度に筆者が使用しているconfファイル

# nginxの設定ファイル
user nginx;
worker_processes auto;
pid /run/nginx.pid;

# ログ設定
error_log ログを置いておきたい場所/error.log warn;

# 動的モジュールの読み込み
include /usr/share/nginx/modules/*.conf;

# イベント設定
events {
    worker_connections 1024;
}

# HTTPセクション
http {
    # ログフォーマット
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                   '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for"';

    # 基本設定
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 4096;

    include /etc/nginx/mime.types;  # MIMEタイプの設定
    default_type application/octet-stream;
    

    # サーバーブロック
    server {
        listen 80;
        listen [::]:80;
        server_name [ここにあなたのpublicIP or ALBのURI];
        root /home/ec2-user/〇〇〇;  # ドキュメントルート

        # エラーページ設定
        error_page 404 /404.html;
        location = /404.html {
        }

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

        # SPAのためのルーティング設定
        location / {
            index index.html;
            try_files $uri $uri/ /index.html;
        }

        location /signin {
            proxy_pass $backendのURI;
        }
    }
}

グローバル設定

user nginx;
worker_processes auto;
pid /run/nginx.pid;

user:nginxが動作するユーザーを指定
worker_process:同時に処理できるワーカープロセスの数を指定。autoはCPUコア数に基づいて自動的に設定される
pid:nginxプロセスのPIDを保存するファイルパスを指定する

ログ設定

error_log ログを置いておきたい場所/error.log warn;
access_log ログを置いておきたい場所/access.log main;

error_log:エラーログの出力先とログレベルを指定する。warnがついているため、ここでは警告レベル以上のエラーが記録される
access_log:アクセスログの出力先とフォーマットを指定する。mainというログフォーマットが使用される。
例)
error_log /var/log/nginx/error.log warn;

動的モジュールの読み込み

include /usr/share/nginx/modules/*.conf;

nginxの動的モジュール設定ファイルを読み込む。追加機能や設定を別ファイルとして保存して読み込みたいときはここに記載したパスに.confファイルを置くといい。

イベント設定

events {
    worker_connections 1024;
}

woker_connections:各ワーカープロセスが同時に処理できる接続数を指定。

HTTPセクション

http {
    ...
}

この中でHTTP関連の設定を書き込む。

ログフォーマット

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" "$http_x_forwarded_for"';

アクセスログのフォーマットを定義している。

基本設定

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;

sendfile:ファイルの送信を最適化
tcp_nopush:TCPパケットの送信を最適化する
tcp_nodelay:小さなデータパケットをすぐに送信
keepalive_timeout:クライアントとの接続を維持する時間を設定する
types_hash_max_size:MIMEタイプのハッシュサイズを設定

MIMEタイプ

include /etc/nginx/mime.types;  # MIMEタイプの設定
default_type application/octet-stream;

MiMEタイプの設定ファイルを読み込む。
MIMEタイプ:インターネット上でデータの種類を示す方法。
例)
text/html: html文書
image/png
application/json

サーバーブロック

server {
    ...
}

サーバーに関しての設定をこの中に記載する

リッスンポート

listen 80;
listen [::]:80;

IPv4:listen 80;
IPv6:listen [::]:80;

サーバー名とドキュメントルート

server_name [ここにあなたのpublicIP or ALBのURI];
root /home/ec2-user/〇〇〇;  # ドキュメントルート

server_name:このサーバーブロックが応答するドメインを指定。
PublicIP(ElasticIP推奨)アドレスか、アプリケーションロードバランサー(ALB)のURIを記載。
root:ウェブコンテンツのドキュメントルートを指定。

エラーページ設定

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

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

特定のエラーコードに対するカスタムエラーページを指定。

シングルアプリケーション(SPA)とプロキシの設定

location / {
    index index.html
    try_files $uri $uri/ /index.html;
}
location /signin {
    proxy_pass $backendのURL;
}

ルートパスへのリクエストを処理。リクエストされたURIが存在しない場合は、index.htmlを返す。
location:特定のパスに対するリクエストをバックエンドサーバーに転送する。proxy_passで指定されたURLにリクエストを転送する。

2-3. nginxの起動

confファイルのテスト

sudo nginx -t

起動

sudo systemctl start nginx

ステータスの確認

sudo systemctl status nginx

3. 躓いたエラー

nginxを起動したにもかかわらず、画面が表示されなかったため、エラーログを確認。
~/index.html" failed (13: Permission denied),~
なんだか、権限がないとのこと..

3-1. 権限の確認

ls -ld /home/ec2-user/権限がないと思われるファイルのパス

[ec2-user@ip-〇〇〇 ~]$ ls -ld /home/ec2-user
drwx------ 8 ec2-user ec2-user 241 Mar 11 01:12 /home/ec2-user

そもそも所有者はec2-user(当たり前)
今回描画したいファイルが含まれているディレクトリに権限がないと思われる。また、親ディレクトリにも権限が付与されていないようなので、ディレクトリ全体の権限を変更。(皆様は適切な対応をお願いします。)

3-2. 所有者を変更して権限を付与

sudo chown -R nginx:nginx /home/ec2-user
sudo chmod -R 755 /home/ec2-user
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?