プロジェクト

全般

プロフィール

操作

line_connect サーバー構築

本番サーバー

IPアドレス: 57.180.36.199

環境

Lightsail
https://lightsail.aws.amazon.com/ls/webapp/home/instances
https://lightsail.aws.amazon.com/ls/webapp/ap-northeast-1/instances/stg-techscore/networking

サイズ

$20/month

構築手順(コマンド)

ユーザー作成

インスタンス構築時に指定した公開鍵に対応する秘密鍵を用いて ubuntu ユーザーでログインして以下を実行

$ sudo su -
# useradd -u 10011 -d /home/norifumi -s /bin/bash -m norifumi -G admin
# mkdir /home/norifumi/.ssh
# echo 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAtob29I4kjea0AHaA03nE3RJzIQYkOu4rAjNOU+nAaaDYCMczQSsxAbarV4XUbqaXwSCf0vTZL6n9eQVcYTLA5GefzD+gXTxLvOY08a/FOk2GUz+UxrKq1wLbGKE34bS87DTqLc8ScXzS4aCOxjZzOk67fiS28GyejR8ir/Do/bDA+zeVdEzWLyxEmbJwlKRioUqocErpSlxP4zhwMoCT6zdrerXBTT+plukPWeMYUMZkXfeQiX1ufWtkn2jnuqKlhBfNdjXq/ReMA91WiDvf0Wc7OAmN0mqPv6W63fZZ0EP7E5VE1b6MCI2Ij4yYqG5j1E5L5skxElE2Um3XUbJfcQ== [email protected]' > /home/norifumi/.ssh/authorized_keys
# chown -R norifumi:norifumi /home/norifumi/.ssh
# chmod 700 -R /home/norifumi/.ssh
# chmod 600 -R /home/norifumi/.ssh/*
# sed -i '/^norifumi:.*$/d' /etc/shadow
# echo 'norifumi:$6$xbAF8nuJMDDGo.n4$VYMiRTn1gQoliNU8nniUjd8vqaOb9Vqn5RTWBk9.MOvetl0oHbl0N.2EQ2UJ7nTxotLrHLfP.wXQam2atDpO01:19142:0:99999:7:::' >> /etc/shadow

以降、上記で作成した norifumi ユーザーで作業を行う
ubuntu ユーザーをログアウトし、 norifumi ユーザーで ssh 経由でログインする

NTP設定

# apt update
# apt install -y ntp net-tools

アプリ用アカウント作成

# groupadd dev -g 2000
# adduser --gid 2000 --uid 2100 deploy

途中の質問は全て Enter を押下してデフォルト値を利用する

Adding user `deploy' ...
Adding new user `deploy' (2100) with group `dev' ...
Creating home directory `/home/deploy' ...
Copying files from `/etc/skel' ...
New password: 
Retype new password: 
No password supplied
New password: 
Retype new password: 
No password supplied
New password: 
Retype new password: 
No password supplied
passwd: Authentication token manipulation error
passwd: password unchanged
Try again? [y/N] 
Changing the user information for deploy
Enter the new value, or press ENTER for the default
    Full Name []: 
    Room Number []: 
    Work Phone []: 
    Home Phone []: 
    Other []: 
Is the information correct? [Y/n] 
# visudo

最後に1行追加

%dev ALL=(ALL) ALL

パッケージのインストール

# apt -y install patch curl build-essential openssl libreadline-dev libreadline-dev git zlib1g zlib1g-dev libssl-dev libyaml-dev libxml2-dev libxslt1-dev autoconf libc6-dev libncurses-dev automake libtool bison subversion libmysqlclient-dev nginx monit nodejs fonts-takao-mincho fonts-takao

DBサーバーのインストール・設定

# apt -y install mysql-server
# mysql -u root
mysql> CREATE USER 'line_connect'@'%' IDENTIFIED WITH mysql_native_password BY 'AkcJn2xqbsPY';
mysql> GRANT ALL PRIVILEGES ON line_connect.* TO 'line_connect'@'%';
mysql> FLUSH PRIVILEGES;

Ruby のインストール

# sudo su - deploy

以下、 deploy ユーザー

$ git clone https://github.com/rbenv/rbenv.git ~/.rbenv
$ echo 'export PATH="~/.rbenv/bin:$PATH"' >> ~/.bashrc
$ ~/.rbenv/bin/rbenv init >> ~/.bashrc
$ echo 'eval "$(rbenv init - bash)"' >> ~/.bashrc
$ source ~/.bashrc
$ git clone https://github.com/rbenv/ruby-build.git "$(rbenv root)"/plugins/ruby-build
$ rbenv  install 3.2.2

アプリケーション用ディレクトリの作成

# mkdir -p /usr/local/rails_apps/line_connect/shared/tmp/sockets
# mkdir -p /usr/local/rails_apps/line_connect/shared/tmp/pids
# mkdir -p /usr/local/rails_apps/line_connect/shared/config
# mkdir -p /usr/local/rails_apps/line_connect/shared/log
# chown -R www-data:www-data /usr/local/rails_apps/
# chmod -R 2775 /usr/local/rails_apps/
# chown -R deploy /usr/local/rails_apps/line_connect/

デプロイユーザーの調整

# sudo su - deploy

以下、 deploy ユーザー

$ ssh-keygen -C ''

入力は全てデフォルトで enter キーを押下していく

Generating public/private rsa key pair.
Enter file in which to save the key (/home/deploy/.ssh/id_rsa): 
Created directory '/home/deploy/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/deploy/.ssh/id_rsa
Your public key has been saved in /home/deploy/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:679JHZ5l9D1RC1kPy9GOdnnE6GS7xVBXV4l/+lGmnQI 
The key's randomart image is:
+---[RSA 3072]----+
|             .**@|
|             +*=X|
|             +=Xo|
|           E .=+%|
|        S   o.oXB|
|         . o *+oo|
|        . . + ...|
|       . . .    .|
|        ..+.     |
+----[SHA256]-----+

自分自身にSSHできるようにする

$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

ソースコードを展開する

※事前に /home/deploy/.ssh/id_rsa.pub の公開鍵を git に登録してソースコードを取得できるようにする
以下、 deploy ユーザー

$ git clone [email protected]:init6/line_connect.git /home/deploy/line_connect
$ cd ~/line_connect
$ vi config/master.key

以下の内容を記載して保存

2f70de59a1afb1b8fe18f672d9aebea6
$ vi /usr/local/rails_apps/line_connect/shared/config/master.key

以下の内容を記載して保存

2f70de59a1afb1b8fe18f672d9aebea6
$ bundle

DBを用意する

以下、 deploy ユーザー

$ cd ~/line_connect
$ LINE_CONNECT_DATABASE_PASSWORD=AkcJn2xqbsPY RAILS_ENV=production bin/rails db:create db:migrate db:seed
$ vi /usr/local/rails_apps/line_connect/shared/config/database.yml

以下の内容を記載して保存

production:
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: localhost
  database: line_connect
  username: line_connect
  password: AkcJn2xqbsPY

試しに起動する

以下、 deploy ユーザー

$ cd ~/line_connect
$ LINE_CONNECT_DATABASE_PASSWORD=AkcJn2xqbsPY RAILS_ENV=production bin/rails assets:clean assets:precompile
$ LINE_CONNECT_DATABASE_PASSWORD=AkcJn2xqbsPY RAILS_LOG_TO_STDOUT=1 RAILS_ENV=production bin/rails s
=> Booting Puma
=> Rails 7.1.2 application starting in production 
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 6.4.0 (ruby 3.2.2-p53) ("The Eagle of Durango")
*  Min threads: 5
*  Max threads: 5
*  Environment: production
*          PID: 73011
* Listening on http://0.0.0.0:3000
Use Ctrl-C to stop

ブラウザで http://[サーバーのIPアドレス]:3000/ にアクセス
ページが表示されればOK

sudoers の調整

# visudo

以下を最後に追記

deploy ALL=(ALL) NOPASSWD: /bin/mv /tmp/*.service /etc/systemd/system/
deploy ALL=(ALL) NOPASSWD: /bin/systemctl daemon-reload
deploy ALL=(ALL) NOPASSWD: /bin/systemctl enable *
deploy ALL=(ALL) NOPASSWD: /bin/systemctl restart *

systemd

# vi /etc/systemd/system/line_connect_puma_production.service

以下のように記載

[Unit]
Description=Puma HTTP Server for line_connect (production)
After=network.target

[Service]
Type=simple
User=deploy
WorkingDirectory=/usr/local/rails_apps/line_connect/current
# Support older bundler versions where file descriptors weren't kept
# See https://github.com/rubygems/rubygems/issues/3254
ExecStart=/home/deploy/.rbenv/bin/rbenv exec bundle exec --keep-file-descriptors puma -C /usr/local/rails_apps/line_connect/shared/puma.rb
ExecReload=/bin/kill -USR1 $MAINPID
StandardOutput=append:/usr/local/rails_apps/line_connect/shared/log/puma_access.log
StandardError=append:/usr/local/rails_apps/line_connect/shared/log/puma_error.log

Restart=always
RestartSec=1

SyslogIdentifier=puma

[Install]
WantedBy=multi-user.target
# systemctl enable line_connect_puma_production.service
$ vi /usr/local/rails_apps/line_connect/shared/puma.rb
``
以下のように記載

#!/usr/bin/env puma

directory '/usr/local/rails_apps/line_connect/current'
rackup "/usr/local/rails_apps/line_connect/current/config.ru"
environment 'production'

tag ''

pidfile "/usr/local/rails_apps/line_connect/shared/tmp/pids/puma.pid"
state_path "/usr/local/rails_apps/line_connect/shared/tmp/pids/puma.state"
stdout_redirect '/usr/local/rails_apps/line_connect/shared/log/puma_access.log', '/usr/local/rails_apps/line_connect/shared/log/puma_error.log', true

threads 0,16

bind 'unix:///usr/local/rails_apps/line_connect/shared/tmp/sockets/puma.sock'

workers 0

restart_command 'bundle exec puma'

prune_bundler

on_restart do
puts 'Refreshing Gemfile'
ENV["BUNDLE_GEMFILE"] = ""
end

####  デプロイ
```shell
$ sudo su - deploy
$ cd ~/line_connect
$ bundle
$ bundle exec cap production deploy

nginxの設定

# vi /etc/nginx/sites-available/line_connect.conf

以下のように記載

upstream puma {
  server unix:///usr/local/rails_apps/line_connect/shared/tmp/sockets/puma.sock;
}

server {
  server_name mrlc.init6.co.jp;
  listen 80 default_server;
  root /usr/local/rails_apps/line_connect/current/public;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-SSL on;
    proxy_redirect off;
    proxy_pass http://puma;
  }

  try_files $uri/index.html $uri @puma;
  error_page 500 502 503 504 /500.html;
}
# ln -s /etc/nginx/sites-available/line_connect.conf /etc/nginx/sites-enabled/
# rm /etc/nginx/sites-enabled/default
# chown deploy:dev /usr/local/rails_apps/line_connect/shared/log/*
# sudo systemctl restart nginx

http://mrlc.init6.co.jp/ にアクセス

SSLの設定

# apt install -y certbot python3-certbot-nginx
# certbot --nginx -d mrlc.init6.co.jp
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): [email protected]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must
agree in order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: N
Account registered.
Requesting a certificate for mrlc.init6.co.jp

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/mrlc.init6.co.jp/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/mrlc.init6.co.jp/privkey.pem
This certificate expires on 2024-02-26.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Successfully deployed certificate for mrlc.init6.co.jp to /etc/nginx/sites-enabled/line_connect.conf
Congratulations! You have successfully enabled HTTPS on https://mrlc.init6.co.jp

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# systemctl restart nginx

https://mrlc.init6.co.jp/ にアクセス

本間 紀史 さんが約2年前に更新 · 3件の履歴