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?

ミドルウェア構築

Posted at

概要

gitをパッケージ管理システムの最新にする

  • パッケージリストを最新にする
sudo apt update
  • システムのパッケージを最新の状態にアップデート
sudo apt upgrade -y
  • 必要な基本ツール(Gitを含む)のインストール
sudo apt install -y curl wget git build-essntial vim nano libssl-dev libreadline-dev zlibig-dev libsqlite3-dev libpq-dev libmysqlclient-dev libffi-dev libyaml-dev
  • インストールされているバージョンの確認
apt-cache policy git

Nginxのインストール

  • Nginxインストールに必要なパッケージをインストール
sudo apt install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring
  • Nginx公式リポジトリの追加
# 1. Nginxの署名鍵を取得して保存
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg

# 2. リポジトリを追加(安定版:nginx stable)
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

# 3. パッケージリストを更新
sudo apt update

# 4. Nginxをインストール
sudo apt install -y nginx
  • 起動と確認
sudo systemctl start nginx
sudo systemctl status nginx

active (running) と表示されればOK

sudo nginx -t

サーバーの外部IPアドレスを確認

curl ifconfig.me
http://[外部IPアドレス]/

上記のアドレスでアクセスし、
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working.
というページが表示される

  • プロジェクトファイルを格納するディレクトリを作成
mkdir -p ~/projects
  • ポートフォリオ用のディレクトリ作成
mkdir -p /home/[ユーザー名]/projects/portfolio_html
  • ディレクトリを作成する
sudo mkdir -p /etc/[ユーザー名]/projects/portfolio_html
  • HTMLファイルを作成
STF_ID="〇〇"
vim /home/[ユーザー名]/projects/portfolio_html/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>My Portfolio</title>
</head>
<body>
  <h1>こんにちは、私は [〇〇] です</h1>
  <p>これは自分のポートフォリオページです。</p>
</body>
</html>
  • 入力が完了したら Esc を押す。次に :wq と入力して Enter → 保存&終了
  • nginx設定ファイルの作成と有効化
    portfolio.confファイルの作成
sudo touch /etc/nginx/sites-available/portfolio.conf
server {
    listen 80;
    server_name _;

    root /home/[ユーザー名]/projects/portfolio_html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    access_log /var/log/nginx/portfolio_access.log;
    error_log /var/log/nginx/portfolio_error.log warn;
}
  • rails.app.confファイルの作成
sudo touch /etc/nginx/sites-available/rails_app.conf
server {
    listen 80;
    server_name _;

    root /home/[ユーザー名]/[アプリ名]/public;

    access_log /var/log/nginx/rails_app.access.log;
    error_log  /var/log/nginx/rails_app.error.log;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ ^/assets/ {
        gzip_static on;
        expires max;
        add_header Cache-Control public;
    }
}
  • /etc/nginx/sites-enabled/ ディレクトリを作成する
sudo mkdir -p /etc/nginx/sites-enabled/
  • 古いリンクを削除してから新しいシンボリックリンクを作成
sudo ls -ln -s /etc/nginx/sites-available/portfolio.conf /etc/nginx/site-enabled/
sudo ls -ln -s /etc/nginx/sites-available/rails_app.conf /etc/nginx/site-enabled/
  • nginx.confの中身を追加
sudo vim /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    ##
    # Basic Settings
    ##

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

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
  • userに権限を与える
sudo chmod o+x /home/[ユーザー名]/
sudo chmod o+x /home/[ユーザー名]/projects/
sudo chmod o+rx /home/[ユーザー名]/projects/portfolio_html
sudo chmod o+x /home/[ユーザー名]/projects/portfolio_html/index.html
  • nginx設定の有効化と再起動
sudo nginx -t
sudo systemctl reload nginx
sudo systemctl status nginx
  • ローカルPCのhostsファイルを編集
sudo vim /etc/hosts

実行するとmacOSのログインパスワードを求められる

[外部IP] [ユーザー名].local
[外部IP] rails.local
  • http://[ユーザー名].localで自身のポートフォリオを表示

DBサーバー(MySQL)の構築

  • MySQLのインストール
  • パッケージリストの更新
sudo apt update
  • MySQL のインストール
sudo apt install -y mysql-server
  • vimでMySQL設定ファイルを開く
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
  • [mysqld]セクション内にskip-grant-tablesを追加
sudo mysql -u root 
-- データベース作成(例: myapp_production)
CREATE DATABASE myapp_production DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- ユーザー作成(例: myuser@localhost)
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'yourpassword';

-- 権限付与
GRANT ALL PRIVILEGES ON myapp_production.* TO 'myuser'@'localhost';

-- 変更を反映
FLUSH PRIVILEGES;
# 新しいrootパスワード設定
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '新しいパスワード';

FLUSH PRIVILEGES;
EXIT;
# MySQL を停止
sudo systemctl stop mysql
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
# skip-grant-tables
  • MySQL を再起動
sudo systemctl start mysql
  • MySQLサービスを再起動する
sudo systemctl restart musql
sudo systemctl status mysql
  • MySQLクライアントにrootでログインする。プロンプトが表示されたら、MySQLのrootパスワードを入力('新しいパスワード')

  • mysql> プロンプトが表示されたら、以下のSQLコマンドを1行ずつ実行

  • 作成したユーザーに全てのデータベース(*)に対する権限を付与

GRANT ALL PRIVILEGES ON *.* TO '[ユーザー名]'@'localhost';
FLUSH PRIVILGES;
EXIT;

Railsのインストールと構築(自動的にpumaもインストール)

  • Rubyのビルドに必要な追加ツールをインストール
sudo apt install -y libssl-dev libreadline-dev zlib1g-dev libsqlite3-dev \ libpq-dev libmysqlclient-dev
  • miseバージョンマネージャのインストール
curl https://mise.run | sh
echo 'eval "$(~/.local/bin/mise activate)"' >> ~/.bashrc
  • bashrcの変更を現在のシェルに適用
source ~/.bashrc
  • miseが正しくインストールされたか確認
mise --version
  • Rubyのインストール
mise rescan
  • Ruby3.4.4をインストールし、グローバルに設定
mise use -g ruby@3.4.4
ruby -v
  • Bundlerのインストール
gem install bundler
  • Railsのインストールとアプリケーションの作成
gem install rails -v "~> 8.0.0"

# Railsが正しくインストールされたか確認
rails -v
  • プロジェクトディレクトリに移動
cd ~/projects
  • Railsアプリケーションの作成(データベースとしてMySQLを指定)
rails new hello_rails -d mysql

# 作成したRailsプロジェクトのディレクトリに移動
cd hello_rails
  • mise WARNが発生した場合、以下のコマンドで解消
mise setting add idiomatic_version_file_enable_tools ruby

# Railsアプリケーションの依存関係(gem)をインストール
bundle install

MySQLとRailsを接続

vim config/database.yml
# MySQL. Versiond 5.6.4 and up are supported
##

①usernameとpasswardの行を編集する
②socketの行をコメントアウトし、host: localhostを追加

  • DB設定とプリコンパイル
# DB作成とマイグレーション
rails db:create
rails db:migrate

# アセットプリコンパイル
rails assets:precompile RAILS_ENV=production

ポートフォリオとRailsのデフォルト画面の表示

  • Rails Hello Worldページ準備&Puma設定
cd ~/projects/hello_rails
vim confing/routes.rb
Rails.application.routes.draw do
  # トップページ
  root "home#index"

  # ヘルスチェック用エンドポイント
  # /up にアクセスするとステータス200を返す(監視ツールなどに利用)
  get "up", to: proc { [200, {}, ["OK"]] }

  # 静的ページ
  get "about", to: "home#about"
  get "contact", to: "home#contact"

  # ブログ記事などのリソース
  resources :posts

  # ユーザー登録・ログイン関連(必要に応じて)
  resources :users, only: [:new, :create, :show]
  resource :session, only: [:new, :create, :destroy]

  # 管理者パネル(例: /admin/posts)
  namespace :admin do
    resources :posts
    resources :users
  end
end
  • Railsアセットプリコンパイル
rails assets:precompile RAILS_ENV=production
  • Pumaをフォアグラウンドで軌道
bundle exec puma -e production -b tcp://0.0.0.0:3000
  • Railsプロジェクトの親ディレクトリの実行権限を追加
sudo chmod o+x /home/[ユーザ名]/
sudo chmod o+x /home/[ユーザ名]/projects/
sudo chmod o+x /home/[ユーザ名]/projects/hello_rails/
  • nginxを再起動
sudo nginx -t
sudo systemctl restart nginx
  • もう1度Railsアプリケーション(Puma)を起動
bundle exec puma -e production -b tcp://0.0.0.0:3000

[外部IPアドレス] rails.localを表示

- Pumaの設定ファイルを生成

bundle exec puma -C confing/puma.rb
  • PumaのSystemdサービスファイルを作成
sudo vim /etc/systemd/system/hello_rails.service
[Unit]
Description=Hello Rails Puma Server
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/hello_rails
Environment=RAILS_ENV=production
ExecStart=/home/ubuntu/.rbenv/shims/bundle exec puma -C config/puma.rb
Restart=always

[Install]
WantedBy=multi-user.target
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?