まんま!の備忘録

ソフトウェア・ファームウェア・ハードウェア関連の備忘録

Rocky LinuxでWebサーバー開発環境構築(Django)

今回はRocky LinuxでWebサーバー開発環境を構築していきます。
Rocky LinuxはVirtual MachineのUTMで動作させます。
WebサーバーはPostgreSQL + Djangoで構築していきます。

事前準備は以下を参照してください。
taogya.hatenablog.com
taogya.hatenablog.com
taogya.hatenablog.com
taogya.hatenablog.com


仮想マシンを右クリックして編集を選択します。
ネットワークネットワークモード共有ネットワークに設定し、MACアドレスを変更(ランダムを選択)します。

新規ネットワークを追加します。

ネットワークモード仮想VLANに設定し、MACアドレスを変更(ランダムを選択)します。

ポート転送新規を選択します。

ゲストポート22ホストポート2222に設定し、保存を押下します。(ポートは適宜変更してください。)

同様にゲストポート8000ホストポート8000に設定し、保存を押下します。(ポートは適宜変更してください。)

保存を押下して、仮想マシンをBootします。

MacのターミナルからSSH接続します。

# configに接続情報追加
echo -n '
Host sakura-rocky
  HostName localhost
  User admin
  Port 2222' >> ~/.ssh/config
# SSH接続
ssh sakura-rocky
[admin@localhost ~]$ 

Djangoの環境を作成していきます。

# ファイアウォール設定
[admin@localhost ~]$ sudo firewall-cmd --add-port=8000/tcp --zone=public --permanent
[admin@localhost ~]$ sudo firewall-cmd --add-service=git --zone=public --permanent
[admin@localhost ~]$ sudo firewall-cmd --reload
# Webサーバ用ユーザを作成
[admin@localhost ~]$ sudo adduser server
[admin@localhost ~]$ sudo gpasswd -a admin server
[admin@localhost ~]$ sudo chmod -R 770 /home/server
[admin@localhost ~]$ sudo chown -R server:server /home/server
# 必要モジュールインストール
[admin@localhost ~]$ sudo yum install -y postgresql-server git python3-devel gcc tar
[admin@localhost ~]$ sudo systemctl start nginx
[admin@localhost ~]$ sudo systemctl enable nginx
[admin@localhost ~]$ sudo postgresql-setup --initdb
[admin@localhost ~]$ sudo vi /var/lib/pgsql/data/pg_hba.conf
:
# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            ident md5
# IPv6 local connections:
host    all             all             ::1/128                 ident md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            ident md5
host    replication     all             ::1/128                 ident md5
[admin@localhost ~]$ sudo systemctl start postgresql.service
[admin@localhost ~]$ sudo systemctl enable postgresql.service
# DBを作成
[admin@localhost ~]$ sudo su - postgres
[postgres@localhost ~]$ psql -U postgres
postgres=# create database rocky_server_db encoding 'utf8';
postgres=# create user server with password 'server';
postgres=# alter database rocky_server_db owner to server;
postgres=# grant all on database rocky_server_db to server;
postgres=# \q
[postgres@localhost ~]$ exit
[admin@localhost ~]$
# gitの設定
[admin@localhost ~]$ git config --global user.name "xxxxx"
[admin@localhost ~]$ git config --global user.email "xxxxx@xxxxx.xxx"

GitHubリポジトリを作成します。


ブランチを作成します。

# Pythonバージョン確認
[admin@localhost ~]$ python -V
Python 3.9.14
→ 今回は3.9で進めていきます。
# 作業ディレクトリの作成
[admin@localhost ~]$ sudo su - server
[server@localhost ~]$ mkdir -p ~/app && cd app
[server@localhost app]$ git clone -b develop https://github.com/taogya/RockyServer.git
# Python実行環境作成
[server@localhost app]$ python -m venv venvRS
[server@localhost app]$ . venvRS/bin/activate activate
(venvRS) [server@localhost app]$ pip install isort flake8 autopep8 radon
(venvRS) [server@localhost app]$ pip install Django django-widget-tweaks psycopg2-binary uWSGI numpy pandas
(venvRS) [server@localhost app]$ cd RockyServer
# プロジェクトの作成
(venvRS) [server@localhost RockyServer]$ django-admin startproject rocky
(venvRS) [server@localhost RockyServer]$ cd rocky
(venvRS) [server@localhost rocky]$ vi rocky/settings.py
# 以下に置き換える
:
ALLOWED_HOSTS = ['*']
:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'rocky_server_db',
        'USER': 'server',
        'PASSWORD': 'server',
        'HOST': 'localhost',
        'PORT': '5432',
    },
}
:
(venvRS) [server@localhost rocky]$ python manage.py makemigrations
(venvRS) [server@localhost rocky]$ python manage.py migrate
(venvRS) [server@localhost rocky]$ python manage.py runserver 0.0.0.0:8000

ブラウザ上からhttp://localhost:8000/へアクセスします。
以下の画面が出れば、OKです。

最後にVisual Studio Codeで開発する環境を整えます。*1

(venvRS) [server@localhost rocky]$ cd ..
# importのソート設定
(venvRS) [server@localhost RockyServer]$ echo -n '[settings]
default_section=THIRDPARTY
force_single_line=False
known_first_party=rocky
known_django=django
sections = FUTURE,STDLIB,DJANGO,THIRDPARTY,FIRSTPARTY,LOCALFOLDER' | tee -a .isort.cfg
# workspace設定
(venvRS) [server@localhost RockyServer]$ mkdir .vscode
(venvRS) [server@localhost RockyServer]$ echo -n '{
    "python.defaultInterpreterPath": "/home/server/app/venvRS/bin/python3.9",
    "python.analysis.extraPaths": [
        "${workspaceFolder}/rocky"
    ],
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true,
    "python.linting.lintOnSave": true,
    "python.formatting.provider": "autopep8",
    "editor.formatOnSave": true,
    "python.linting.flake8Args": [
        "--ignore=E501, W503, W504",
    ],
    "python.formatting.autopep8Args": [
        "--ignore=E501, W503, W504",
    ],
    "[python]": {
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        },
    },
    "isort.check": true,
    "isort.args": [
        "--settings-file",
        "${workspaceFolder}/.isort.cfg",
    ],
}' | tee -a  .vscode/settings.json

# 実行設定
(venvRS) [server@localhost RockyServer]$ echo -n '{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Makemigrations",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/rocky/manage.py",
            "args": [
                "makemigrations"
            ],
            "django": true
        },
        {
            "name": "Migrate",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/rocky/manage.py",
            "args": [
                "migrate"
            ],
            "django": true
        },
        {
            "name": "Loaddata",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/demo/manage.py",
            "args": [
                "loaddata",
                "xxxx.json"
            ],
            "django": true
        },
        {
            "name": "Runserver",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/rocky/manage.py",
            "args": [
                "runserver",
                "0.0.0.0:8000"
            ],
            "django": true
        },
        {
            "name": "Test",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/rocky/manage.py",
            "args": [
                "test",
                "xxxxx",
            ],
            "django": true
        },
        {
            "name": "Manage",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/rocky/manage.py",
            "args": [
                "custom_command",
            ],
            "django": true
        }
    ]
}' | tee -a  .vscode/launch.json

Visual Studio Codeを開きます。
リモートエクスプローラからsakura-rockyを選択します。

パスフレーズを入力してEnterします。

エクスプローラフォルダを開くを選択します。

対象のディレクトリを入力してOKを選択します。

警告画面が出てくるので、同意する方を選びます。

実行とデバッグを選択し、Runserverで実行します。

Python拡張をインストールしてくださいの警告が出たので、インストールします。


もう一度実行してブラウザ上からhttp://localhost:8000/へアクセスします。


最後の最後にpushして完了とします。

(venvRS) [server@localhost RockyServer]$ echo -n '.DS_Store
__pycache__' >> .gitignore
(venvRS) [server@localhost RockyServer]$ git config core.filemode false
(venvRS) [server@localhost RockyServer]$ git status
(venvRS) [server@localhost RockyServer]$ git add .
(venvRS) [server@localhost RockyServer]$ git status
(venvRS) [server@localhost RockyServer]$ git commit -m "first commit" 
(venvRS) [server@localhost RockyServer]$ git push origin develop
→ パスワードはGitHubでToken発行
→ エラーが出る。。
send-pack: unexpected disconnect while reading sideband packet
# httpsでpushできなかったのでsshに切り替え
(venvRS) [server@localhost RockyServer]$ mkdir ~/.ssh
(venvRS) [server@localhost RockyServer]$ ssh-keygen -f ~/.ssh/id_rsa
(venvRS) [server@localhost RockyServer]$ eval "$(ssh-agent)"
(venvRS) [server@localhost RockyServer]$ ssh-add ~/.ssh/id_rsa
(venvRS) [server@localhost RockyServer]$ cat ~/.ssh/id_rsa.pub
→ GitHubへ登録
(venvRS) [server@localhost RockyServer]$ git remote set-url origin git@github.com:taogya/RockyServer.git
(venvRS) [server@localhost RockyServer]$ echo -n 'Host github.com
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/id_rsa
  PreferredAuthentications publickey
  TCPKeepAlive yes 
  IdentitiesOnly yes' > ~/.ssh/config
(venvRS) [server@localhost RockyServer]$ ssh -T git@github.com
(venvRS) [server@localhost RockyServer]$ git push origin develop
Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 2 threads
Compressing objects: 100% (13/13), done.
Writing objects: 100% (15/15), 8.70 KiB | 8.70 MiB/s, done.
Total 15 (delta 1), reused 0 (delta 0), pack-reused 0
← ここで止まってしまう。。。

どう頑張ってもpushできなかったので、コピーしてGitHubにあげました。

scp -r -P 2222 admin@localhost:/home/server/app/RockyServer ./
rm -rf RockyServer/.git
mv RockyServer RockyServer.bk
git clone -b develop https://github.com/taogya/RockyServer.git
cp -r  RockyServer.bk/ RockyServer/
cd RockyServer/
git status
git add .
git commit -m "first commit"
git push origin develop
→ パスワードはGitHubでToken発行

github.com

本番環境構築については、またどこかで記載します。