【VirtualBox】UbuntuサーバにWEB開発環境構築【Linux】
こんにちは、なかだ(@newNakata)です。
前回の投稿(【VirtualBox】Ubuntuインストール【Linux】)で VirtualBox(以下、VM)で仮想環境に Ubuntu をインストールしました。
今回は Ubuntu が入った仮想サーバにApache、PHP、MySQL、PostgreSQLを入れたいと思います。
要所で過去の投稿のリンクを貼って飛びやすくなっていると思いますが、本稿は【ゼロから】WEB環境構築まとめ【すぐできる】を前提にしています。
もちろん本稿だけでも設定可能です。
また、コマンドは全て root ユーザーで行います。
目次
apt コマンド
apt コマンドでよく使いそうな一覧を記載します。
コマンド | 内容 |
apt update | パッケージリストを更新する。 |
apt upgrade | インストール済みパッケージを最新のバージョンに アップグレードする。 |
apt dist-upgrade | ディストリビューションのアップグレードを行う。 |
apt full-upgrade | 同上 |
apt install <package> | パッケージをインストールする。 |
apt remove <package> | パッケージをアンインストールする。 |
apt autoremove | 不要になったパッケージを自動的にアンインストールする。 |
apt search <package> | パッケージを検索する。 |
apt show <package> | パッケージの詳細情報を表示する。 |
apt list | 利用可能な全てのパッケージが表示され、それに対してインストール済み かどうかを表示する。 |
apt list ‐‐installed | 実際にインストールされているパッケージのリストを表示する。 特定のパッケージのみの場合は | grep <package> をつける。 |
apt info <package> | 指定されたパッケージに関する情報をレポジトリから取得し表示します。 |
apt clean | ダウンロードされたパッケージのキャッシュをクリアする。 |
apt autoclean | 使用されなくなったパッケージをクリーンアップする。 |
apt check | パッケージの依存関係を確認する。 |
Apache
Ubuntu ではサービス名が apache2 のようです。
設定ファイルを格納するディレクトリ名も同様 (/etc/apache2)です。
インストール
apt list --installed | grep apache
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
何も表示されないため、現在 apache はインストールされていません。
WARNING について
結論から言うと無視します。
apt list にパイプ(|)を渡すと warning が表示されます。
スクリプトにおける利用は apt-get、apt-cache コマンドなどの利用が推奨されているようです。
ただ apt list コマンドと同じ動作をするコマンドが apt-get、apt-cache に見当たらないです。
apt のレポジトリにパッケージがあるか調べてみます。
apt list | grep apache2
↓
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
apache2-bin/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 amd64
apache2-data/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 all
apache2-dev/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 amd64
apache2-doc/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 all
apache2-ssl-dev/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 amd64
apache2-suexec-custom/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 amd64
apache2-suexec-pristine/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 amd64
apache2-utils/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 amd64
apache2/jammy-updates,jammy-security 2.4.52-1ubuntu4.7 amd64
dehydrated-apache2/jammy 0.7.0-3 all
kopano-webapp-apache2/jammy 3.5.14+dfsg1.orig-1 all
~~~~ 略 ~~~~~
apt のレポジトリには apache2 が存在しているようです。
apache2 の情報を確認してみます。
apt info apache2
↓
Package: apache2
Version: 2.4.52-1ubuntu4.7
Priority: optional
Section: web
Origin: Ubuntu
~~~~ 略 ~~~~~
レポジトリに登録されている apache のバージョンは 2.4 系ですね。
apache2 をインストールします。
apt -y install apache2
↓
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています... 完了
状態情報を読み取っています... 完了
以下の追加パッケージがインストールされます:
apache2-bin apache2-data apache2-utils bzip2 libapr1 libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap
liblua5.3-0 mailcap mime-support ssl-cert
提案パッケージ:
apache2-doc apache2-suexec-pristine | apache2-suexec-custom www-browser bzip2-doc
~~~~ 中略 ~~~~~
Scanning linux images...
Running kernel seems to be up-to-date.
No services need to be restarted.
No containers need to be restarted.
No user sessions are running outdated binaries.
No VM guests are running outdated hypervisor (qemu) binaries on this host.
root@nakadalog:~#
-y を付与する事でインストール確認をスキップ(事前に”はい”を選択)しています。
上記が表示され、入力が返ってくればインストール完了です。
再度確認してみます。
apt list --installed | grep apache2
↓
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
apache2-bin/jammy-updates,jammy-security,now 2.4.52-1ubuntu4.7 amd64 [インストール済み、自動]
apache2-data/jammy-updates,jammy-security,now 2.4.52-1ubuntu4.7 all [インストール済み、自動]
apache2-utils/jammy-updates,jammy-security,now 2.4.52-1ubuntu4.7 amd64 [インストール済み、自動]
apache2/jammy-updates,jammy-security,now 2.4.52-1ubuntu4.7 amd64 [インストール済み]
または
root@nakadalog:~# apache2 -v
Server version: Apache/2.4.52 (Ubuntu)
Server built: 2023-10-26T13:44:44
インストールされていることが確認できました。
インストール後の状態を確認してみます。
systemctl status apache2
↓
● apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2023-12-11 16:26:46 JST; 38min ago
Docs: https://httpd.apache.org/docs/2.4/
Main PID: 2416 (apache2)
Tasks: 55 (limit: 2221)
Memory: 5.2M
CPU: 255ms
CGroup: /system.slice/apache2.service
tq2416 /usr/sbin/apache2 -k start
tq2418 /usr/sbin/apache2 -k start
mq2419 /usr/sbin/apache2 -k start
~~~~ 略 ~~~~~
インストール完了後、サービスは実行中になっているようです。
自動起動の設定はどのようになっているか確認してみます。
systemctl list-unit-files | grep apache2
↓
apache2.service enabled enabled
apache2@.service disabled enabled
自動起動も登録されているようなので次回 vm 起動時は一緒に apache2 も起動します。
ブラウザから確認してみます。
http://192.168.56.104
※各々の環境でインストール時に指定したものに置き換えてください。

上の画像の様に表示されればアクセスもできています。
以上でインストールは完了です。
設定
virtualhost の設定、windows の hosts ファイルなど詳しくは【VirtualBox】開発環境を作る – Apache設定編 【CentOS】で公開しています。
apache2 の初期設定は /etc/apache2/sites-available/000-default.conf なので vi で展開します。
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
↓編集
ServerName ubt-nakadalog.local
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog /var/log/apache2/nakadalog.local-error_log
SetEnvIf Request_URI "\.(gif)|(jpeg)|(jpg)|(png)|(ico)$" no_log
CustomLog /var/log/apache2/nakadalog.local-access_log combined env=!no_log
<Directory "/var/www/html">
AllowOverride FileInfo AuthConfig Limit Options
Options -Indexes +ExecCGI +FollowSymLinks
Require all granted
</Directory>
apachectl コマンドで変更した virtualhost の記述を確認します。
apachectl configtest
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Syntax OK
Syntax OK なので設定した内容は大丈夫そうですが、何かメッセージが出ています。
これは /etc/hosts に先ほど設定した servername が無いと言うメッセージです。
無視しても構いません。
修正する場合は以下の通りです。
vi /etc/hosts
↓
127.0.0.1 localhost
#127.0.1.1 nakadalog ← 初期設定をコメントアウト(または編集)
127.0.1.1 ubt-nakadalog.local ← virtualhostで指定した名前に変更(または追記)
10.0.2.15 ubt-nakadalog.local ← 同じメッセージが出たら都度追記(各環境でIPアドレスは違います)
apache2 を再起動します。
systemctl restart apache2
標準出力には何も結果は返ってきません。
次に Windows 側の hosts ファイルにこの度の IPアドレスと virtualhost で設定したドメインを追記します。
192.168.56.104 ubt-nakadalog.local
これでブラウザから以下のURLでアクセスします。
http://ubt-nakadalog.local
上記の Ubuntu apache2 defalt page が表示されれば設定完了です。
PHP
インストール
以降は apache2 で行ったような apt コマンドを使ってのパッケージ確認などは割愛します。
それでは早速 PHP をインストールしていきます。
PHP の関連モジュールは必要そうなものを一緒にしていますが、不要であれば記述を削除してからコマンドを実行してください。
apt -y install php php-mysql php-pgsql php-mbstring php-gd php-xml php-zip php-intl php-curl
↓
~~~~~ 中略 ~~~~~
No containers need to be restarted.
No user sessions are running outdated binaries.
No VM guests are running outdated hypervisor (qemu) binaries on this host.
root@nakadalog:~#
ubuntu 特有の確認画面が立ち上がる場合は都度 [Enter] キーを押下してください。
上記が表示され、入力が返ってくればインストール完了です。
確認してみます。
php -v
↓
PHP 8.1.2-1ubuntu2.14 (cli) (built: Aug 18 2023 11:41:11) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
with Zend OPcache v8.1.2-1ubuntu2.14, Copyright (c), by Zend Technologies
php8.1 がインストールされている事が確認できました。
次はブラウザから動作確認をします。
以下のコマンドを実行します。
echo '<?php phpinfo();' > /var/www/html/index.php
コマンドを実行するディレクトリはどこでも構いません。
echo で ’’ 内の文字列を標準出力しつつ > で /var/www/html/index.php に書き込んでいます。
ちなみに /var/www/html に index.php が存在していない場合はファイルを作成(今回はこっち)します。
/var/www/html は apache2 で指定されていた DocumentRoot です。
以下のURLでブラウザからアクセスします。
http://ubt-nakadalog.local/index.php

phpinfo が表示され、PHPの動作が確認できました。
これでインストールは完了です。
その他
必要かどうかわからないけど、都度入れる前にわかってるならとりあえず入れておこうかなと思うモジュールです。
apt -y install composer libpq-dev libonig-dev libfreetype6-dev libjpeg-dev libpng-dev imagemagick libmagickwand-dev
compoer は必須な気もします。
その他、mcrypt が必要だったり、pear が使いたい場合は以下が必要です。
apt -y install php-dev libmcrypt-dev php-pear
あくまでも準備で、実際のインストールはここでは割愛します。
MySQL
流れは少々違いますが全般的に詳しく説明した類似情報を【VirtualBox】開発環境を作る – MySQL編 【CentOS】で公開していますので、不明点などあれば覗いてみてください。
インストール
apt -y install mysql-server
↓
~~~~~ 中略 ~~~~~
No services need to be restarted.
No containers need to be restarted.
No user sessions are running outdated binaries.
No VM guests are running outdated hypervisor (qemu) binaries on this host.
root@nakadalog:~#
上記が表示され、入力が返ってくればインストール完了です。
確認してみます。
mysql --version
↓
mysql Ver 8.0.35-0ubuntu0.22.04.1 for Linux on x86_64 ((Ubuntu))
MySQL8.0 がインストールされている事が確認できました。
apache 同様にインストール後の状態を確認してみます。
systemctl status mysql
↓
● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2023-12-14 14:13:16 JST; 17min ago
Process: 2599 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
Main PID: 2607 (mysqld)
Status: "Server is operational"
Tasks: 38 (limit: 2221)
Memory: 366.5M
CPU: 15.031s
CGroup: /system.slice/mysql.service
mq2607 /usr/sbin/mysqld
~~~~ 略 ~~~~~
インストール完了後、サービスは実行中になっているようです。
自動起動の設定はどのようになっているか確認してみます。
systemctl list-unit-files | grep mysql
↓
mysql.service enabled enabled
自動起動も登録されているようなので次回 vm 起動時は mysql も起動します。
設定
mysql_secure_installation の実行
root ユーザーパスワードの設定やセキュリティの設定を行います。
mysql_secure_installation
↓
Securing the MySQL server deployment.
Connecting to MySQL using a blank password.
VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?
Press y|Y for Yes, any other key for No: y
“VALIDATE PASSWORD コンポーネントをセットアップしますか?” と言う事なので y を入力して [Enter] キーを押下します。
There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0
“パスワードの検証ポリシーには3つのレベルがあります” と言う事で、個人開発環境もあり一番簡単(パスワードの文字数8文字以上のみ)な 0(ゼロ)を入力して [Enter] キーを押下します。
Skipping password set for root as authentication with auth_socket is used by default.
If you would like to use password authentication instead, this can be done with the "ALTER_USER" command.
See https://dev.mysql.com/doc/refman/8.0/en/alter-user.html#alter-user-password-management for more information.
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
Remove anonymous users? (Press y|Y for Yes, any other key for No) :
何か出てますね。
Skipping password set for root as authentication with auth_socket is used by default.
If you would like to use password authentication instead, this can be done with the "ALTER_USER" command.
See https://dev.mysql.com/doc/refman/8.0/en/alter-user.html#alter-user-password-management for more information.
”デフォルトでは auth_socket による認証が使用されるため、root に設定されたパスワードをスキップします。” とのことです。
「ん?」って思いますよね。僕もです。
MySQL8.0 から認証ソケットプラグイン(auth_socket)がデフォルトで有効になっているようです。
これは Linux ユーザーの OS レベルの認証を使用して MySQL にアクセスすることを可能にしているものです。
つまり、サーバにログインする時に使用するユーザーとパスワードで mysql へもログインが可能と言う事になります。
root ユーザーにはパスワードが必要ない場合がある、と言う記述を見たので、そのまま mysql コマンド実行したらパスワード無しで mysql にログインできました。
ここでは飛ばされているため後で操作する(後述※1)として、設定を続けます。
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
”MySQLインストール時に作成される匿名ユーザーを削除しますか?” 的な内容で、不要なので削除のため y を入力し [Enter] キーを押下します。
Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
“リモートからの root ログインを禁止しますか?” 的な内容なので y を入力し [Enter] キーを押下します。
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
“インストール時に作成されるテスト データベースを削除してアクセスしますか?” 的な内容なので y を入力し [Enter] キーを押下します。
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
“全ての変更をただちに反映しますか?” 的な内容なので y を入力し [Enter] キーを押下します。
All done!
これで設定は完了です。
ルートユーザーの認証プラグイン変更(※1)
パスワード無しは個人開発環境ならなくてもいいですが、それでも落ち着かないので設定を変更します。
root@nakadalog:~# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.35-0ubuntu0.22.04.1 (Ubuntu)
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select host,user,plugin from mysql.user;
+-----------+------------------+-----------------------+
| host | user | plugin |
+-----------+------------------+-----------------------+
| localhost | debian-sys-maint | caching_sha2_password |
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session | caching_sha2_password |
| localhost | mysql.sys | caching_sha2_password |
| localhost | root | auth_socket |
+-----------+------------------+-----------------------+
5 rows in set (0.00 sec)
上記通り、パスワード無しでのログインおよび現在の設定が auth_socket になっている事が確認できます。
それでは変更します。
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '新しいパスワード';
Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
mysql> select host,user,plugin from mysql.user;
+-----------+------------------+-----------------------+
| host | user | plugin |
+-----------+------------------+-----------------------+
| localhost | debian-sys-maint | caching_sha2_password |
| localhost | mysql.infoschema | caching_sha2_password |
| localhost | mysql.session | caching_sha2_password |
| localhost | mysql.sys | caching_sha2_password |
| localhost | root | mysql_native_password |
+-----------+------------------+-----------------------+
5 rows in set (0.00 sec)
ALTER USER コマンドで認証方法を変更、かつ新しいパスワードを設定(上記”新しいパスワード”部分にパスワードを記載)します。
FLUSH PRIVILEGES は変更した設定を反映するコマンドです。
反映後、認証方法も変更されているのが確認できます。
mysql> \q
Bye
root@nakadalog:~# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
root@nakadalog:~# mysql -p
Enter password: ← 設定したパスワードを入力
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 8.0.35-0ubuntu0.22.04.1 (Ubuntu)
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
¥q でログアウト後、 パスワード無しで mysql コマンドからログインしようとするとエラーになりました。
次に -p を付与してパスワード入力を行う事で正しくログインできる事が確認できました。
以上でパスワード無しでのログインはできなくなり、設定は完了です。
外部(クライアントツールなど)からの接続設定
クライアントツール(僕はいつも A5:SQL Mk-2)を使って接続するためには設定が必要です。
対象ファイルは /etc/mysql/mysql.conf.d/mysqld.conf になります。
vi /etc/mysql/mysql.conf.d/mysqld.conf
↓
#
# The MySQL database server configuration file.
#
# One can use all long options that the program supports.
~~~~~ 中略 ~~~~~
#bind-address = 127.0.0.1 ← コメントアウトまたは編集
bind-address = 0.0.0.0
~~~~~ 略 ~~~~~
初期設定は自端末(127.0.0.1)からの接続のみ許可されています。
今回はどこからでも接続可(0.0.0.0)としました。
設定の反映は mysql の再起動(systemctl restart mysql)が必要です。
接続ユーザー作成
クライトンツールから接続できるユーザーを作っておきます。
詳細は上記 MySQL 項目の最初にお伝えした投稿にありますので、ここでは割愛します。
ただし、MySQL8.0 から1度ユーザーを作成し、その後で権限の付与をするように変更されています。
mysql にログインし以下を実行します。
mysql> create user 'mysql'@'localhost' identified by 'mysqlmysql';
mysql> grant all on *.* to mysql@localhost;
mysql> create user 'mysql'@'192.168.56.%' identified by 'mysqlmysql';
mysql> grant all on *.* to mysql@'192.168.56.%';
mysql> flush privileges;
mysql ユーザーが自端末(localhost)と、IPアドレスが 192.168.56.1~255 までのアクセスを許可する設定です。
これで接続ユーザーの作成は完了です。
PostgreSQL
流れやバージョンは違いますが全般的に詳しく説明した類似情報を【VirtualBox】開発環境を作る – PostgreSQL編 【CentOS】で公開していますので、不明点などあれば覗いてみてください。
インストール
apt -y install postgresql postgresql-contrib
↓
~~~~~ 中略 ~~~~~
No services need to be restarted.
No containers need to be restarted.
No user sessions are running outdated binaries.
No VM guests are running outdated hypervisor (qemu) binaries on this host.
root@nakadalog:~#
上記が表示され、入力が返ってくればインストール完了です。
確認してみます。
root@nakadalog:~# psql --version
psql (PostgreSQL) 14.10 (Ubuntu 14.10-0ubuntu0.22.04.1)
PostgreSQL 14.10 がインストールされている事が確認できました。
インストール後の状態を確認してみます。
root@nakadalog:~# systemctl status postgresql
● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
Active: active (exited) since Fri 2023-12-15 01:52:45 JST; 6min ago
Process: 3154 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 3154 (code=exited, status=0/SUCCESS)
CPU: 2ms
~~~~~ 略 ~~~~~
インストール完了後、サービスは実行中になっているようです。
自動起動の設定はどのようになっているか確認してみます。
systemctl list-unit-files | grep postgresql
↓
postgresql.service enabled enabled
postgresql@.service indirect enabled
自動起動も登録されているようなので次回 vm 起動時は postgres も起動します。
設定
この度はインストール時に OS(Linux) に追加される postgres ユーザーのパスワードの設定は割愛します。
initdb について
データベースクラスタを個別に作成する必要は無いようです。
postgres ユーザーのパスワード設定
インストール時に作成される postgres の接続ユーザー(名がpostgres)はパスワード無しで作成されています。
パスワード設定を行います。
root@nakadalog:~# su - postgres
postgres@nakadalog:~$ psql
psql (14.10 (Ubuntu 14.10-0ubuntu0.22.04.1))
Type "help" for help.
postgres=# alter role postgres with password 'ここにパスワードを記載';
ALTER ROLE
postgres=#
su で postgres ユーザーになり psql で postgres にログインを行った後、alter role コマンドで psotgres ユーザーにパスワードを設定しています。
外部(クライアントツールなど)からの接続設定
クライアントツール(僕はいつも A5:SQL Mk-2)を使って接続するためには設定が必要です。
設定を行うファイルは2つあります。
まず1つ目の対象ファイルは /etc/postgresql/14/main/postgresql.conf になります。
対象ファイルのパスはバージョンによってディレクトリが違います。
今回はバージョンが14ですが例えば12の場合であれば postgresql/12/main になります。
vi /etc/postgresql/14/main/postgresql.conf
↓
~~~~~ 中略 ~~~~~
#listen_addresses = 'localhost' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost'; use '*' for all
# (change requires restart)
port = 5432 # (change requires restart)
~~~~~ 中略 ~~~~~
↑を↓に変更
listen_addresses = '*' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost'; use '*' for all
# (change requires restart)
port = 5432 # (change requires restart)
60行目付近の上記 listen_address は初期設定はコメントアウトされています。
ここのコメントを削除し、且つ localhost を *(アスタリスク)に変更し、保存します。
2つ目の対象ファイルは /etc/postgresql/14/main/pg_hba.conf になります。
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 scram-sha-256
host all all 192.168.56.0/24 md5 ← これを追記
# IPv6 local connections:
97行目あたりにの下に 192.168.56.0/24 を追記します。
これで 192.168.56.1~255 の IP アドレスからの接続が可能となり、設定は完了です。
設定の反映は postgres の再起動(systemctl restart postgresql)が必要です。
その他
ufw(Uncomplicated FireWall)について
ufw は ubuntu やその他の Linux ディストリビューションで利用できる iptables(Linux の標準的なファイアウォール管理ツール)をより簡潔に扱えるようにしたものです。
ufw を利用することでネットワークセキュリティの設定を格段に少ない操作で実現できます。
ufw はインストール時の初期設定では無効になっています。
これにより初期状態(以降設定しない限り)では全てのトラフィックが許可されているため、apacheなどをインストールした直後から問題無くネットワークに接続できていました。
個人の開発環境で考えると余計な設定が不要なので有難いですね。
ファイアウォールについては【VirtualBox】開発環境を作る – Apache編 【CentOS】の準備とその他に類似情報がありますので、良かったら覗いてみてください。
使用例
ufw enable | ファイアウォールを有効化します。 |
ufw disable | ファイアウォールを無効化します。 |
ufw status | ファイアウォールのステータスを表示します。 |
ufw allow [port|サービス名] | 指定したポートを許可します。 |
ufw deny [port|サービス名] | 指定したポートを拒否します。 |
ufw app list | 利用可能なアプリケーションプロファイルの一覧を表示します。 |
設定
それでは実際に確認しながらいくつか設定してみます。
まず ufw サービスの状態から確認します。
root@nakadalog:~# systemctl status ufw
● ufw.service - Uncomplicated firewall
Loaded: loaded (/lib/systemd/system/ufw.service; enabled; vendor preset: enabled)
Active: active (exited) since Fri 2023-12-15 14:54:56 JST; 1min 57s ago
Docs: man:ufw(8)
Process: 568 ExecStart=/lib/ufw/ufw-init start quiet (code=exited, status=0/SUCCESS)
Main PID: 568 (code=exited, status=0/SUCCESS)
CPU: 3ms
~~~~~ 略 ~~~~~
起動はしているようです。
ufw の設定を確認します。
root@nakadalog:~# ufw status
状態: 非アクティブ
起動はしていますが、無効になっています。
早速有効にします。
root@nakadalog:~# ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
ファイアウォールはアクティブかつシステムの起動時に有効化されます。
root@nakadalog:~# ufw status
状態: アクティブ
root@nakadalog:~#
enable コマンドを実行すると “既存の ssh 接続が中断される可能性があります。” と表示されますが、有効化される前から確立している通信は遮断されないため、構わず y を入力して [Enter] キーを押下します。
status コマンドで有効化されたのが確認できます。
ここで1度有効にすると次回以降のシステム起動時に自動で有効になります。
ちなみに、このままの状態(有効後何も設定しない)で現在確立している通信を切断すると再接続できなくなるので注意が必要です。
もう少し詳細な状態を確認します。
root@nakadalog:~# ufw status verbose
状態: アクティブ
ロギング: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
新しいプロファイル: skip
ロギングが on になっているのでufw のログが /var/log/ufw.log に出力されます。
Default 設定については以下の表にまとめました。
incoming(受信) | 自サーバへの入力。 deny になっているため、全ての通信(サーバへのアクセス)がブロックされます。 |
outgoing(送信) | 自サーバからの出力。 allow になっているた、全ての通信(サーバからの発信)が許可されます。 |
routed(転送) | 自サーバから(介して)他サーバへの転送。 サーバをルーターで動作させている場合に使用します。 ルーターとしての動作設定は行っていないため無効化されています。 |
サーバへの受信が全てブロックされているため、これまで設定した apache などのブラウザからの表示もタイムアウトで表示されません。
また上記でも少し触れましたが、teratarm などで新しく ssh 接続を試しても接続できません。
初期設定を deny にして特定の通信のみを許可する方法をホワイトリスト方式、初期設定を allow にして特定の通信のみを遮断する方法をブラックリスト方式と言ったりします。
このままではいけませんので apache(80)と ssh(22)のポートを開け(設定)ます。
まずは22番ポートから、ここではサービス名で設定します。
root@nakadalog:~# ufw allow ssh
ルールを追加しました
ルールを追加しました (v6)
root@nakadalog:~# ufw status numbered
状態: アクティブ
To Action From
-- ------ ----
[ 1] 22/tcp ALLOW IN Anywhere
[ 2] 22/tcp (v6) ALLOW IN Anywhere (v6)
ssh と指定して22番ポートが設定されました。
先ほどできなかった新しい ssh 接続が今はできるようになっているかと思います。
次は apache の使用ポートを今度はポート番号で設定します。
root@nakadalog:~# ufw allow 80
ルールを追加しました
ルールを追加しました (v6)
root@nakadalog:~# ufw status numbered
状態: アクティブ
To Action From
-- ------ ----
[ 1] 22/tcp ALLOW IN Anywhere
[ 2] 80 ALLOW IN Anywhere
[ 3] 22/tcp (v6) ALLOW IN Anywhere (v6)
[ 4] 80 (v6) ALLOW IN Anywhere (v6)
これで80番ポートが設定されました。
先ほどできなかったブラウザからのアクセスもできるようになっているかと思います。
上記確認内容をもとに、その他としては以下などがあります。
# その他の許可指定
ufw allow 22/tcp ← ポート番号/プロトコル(tcp|udp)指定
ufw allow from 192.168.56.0/24 to any port 22 ← 指定IPからの22番ポートアクセスのみ許可
# 削除
ufw delete [Action] [サービス名] ← delete allow 80 で [2]、[4]が削除される
ufw delete [番号] ← delete 1 で [1]のみが削除される
ufw については以上になります。
不要な方は忘れず ufw disable を叩いて無効化してから切断しましょう。
まとめ
本稿はここまでになります。
これで Ubuntu サーバにWEB開発環境ができました。
詳細の設定やテーブルの作成方法は過去の投稿と変わらないため割愛しています。
僕としては ubuntu に触れることが無かったのでとても勉強になりました。
もし仕事などで ubuntu に触れる機会があれば本稿をもとにできます。
また掘り下げる機会があれば都度記事にできればと思います。