0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Docker + nginx + cloudflareでNext.jsのサーバーを立ててみた

Last updated at Posted at 2023-10-22

目次

はじめに

1. コンテナを生成
2. nginxのインストール
3. nginxの設定
4. CloudflareTunnelを設定

おわりに

はじめに

前回は自宅サーバでRootless Dockerを使えるようにしました。
https://qiita.com/piny940/items/729e52a80724754daa99

今回は自宅サーバー上でNext.jsサーバーを立てて一般公開していこうと思います。

前提:

  • 動くDockerfile・docker-composeがある
  • サーバー上でDockerが動作する
  • cloudflareをDNSサーバーとする独自ドメインを持っている

環境:

  • Ubuntu22.04 server

1. コンテナを生成

次のコマンドでサーバーを立てます

docker compose up -d

2. nginxのインストール

公式に従ってインストールをしていきます

必要なパッケージをインストール

sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring

キーを取得

curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

キーがダウンロードできていることを確認

gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg

出力が次のようになっていたらOKです

pub   rsa2048 2011-08-19 [SC] [expires: 2024-06-14]
      573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62
uid                      nginx signing key <signing-key@nginx.com>

レポジトリをセットアップ

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

インストール

sudo apt update
sudo apt install nginx

インストールできたことを確認

$ nginx -v
nginx version: nginx/1.24.0

3. nginxの設定

/etc/nginx/conf.d/内に設定ファイルtest.confを作成して次のように記述します。

server {
        listen 80;
        server_name www.example.com; # サーバーのアドレス

        location / {
                proxy_pass http://localhost:{package.jsonに書いたポート};
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
}

次のコマンドで設定を適用します。

sudo systemctl restart nginx

正常に動作していることを確認

sudo systemctl status nginx

4. CloudflareTunnelを設定

サーバーとのトンネルがまだできていない場合はcloudflareのコンソールから設定をしてください。

Public Hostnameから指定したサーバーのアドレスを登録します。
image.png

これでサーバーにアクセスできるようになります。

おわりに

今回はcloudflare tunnelを使ってNext.jsのサーバーを公開しました。
次回はサーバー上にデータベースサーバーを立ててRailsサーバーを公開していこうと思います。

参考資料

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?