FreeBSD14 + Nginx + GeoIP2の設定とIPアドレスを自動更新

NginxをHTTP_GEOIP2ビルドオプションを有効にしてビルド後、設定しているときの覚書。
Gemini 2.5 Proと対話。

環境: FreeBSD 14.3-RELEASE-p2


1. IPアドレスを自動更新

MaxMind公式が配布しているgeoipupdateをインストール。
参考: Updating GeoIP and GeoLite Databases | MaxMind Developer Portal
# pkg search geoip
# pkg install geoipupdate

MaxMindにログインして
左メニューのManage license keysを選択。
参考: MaxMind GeoIP® Databases | MaxMind

Generate new license keyをクリック。
License key description: geoipupdate

Account IDとLicense Keyを設定ファイルに記述。
国別データベースの場合は GeoLite2-Countryを指定。
# less /usr/local/etc/GeoIP.conf

AccountID 1234567
LicenseKey 08MzPb....pe_mmk

EditionIDs GeoLite2-Country

動作確認。
# geoipupdate -v

geoipupdate version v7.1.0 (freebsd-arm64)
Using config file /usr/local/etc/GeoIP.conf
Using database directory /usr/local/share/GeoIP
Initializing file lock at /usr/local/share/GeoIP/.geoipupdate.lock
Acquired lock file at /usr/local/share/GeoIP/.geoipupdate.lock
Database does not exist, returning zeroed hash
Updates available for GeoLite2-Country
Database GeoLite2-Country successfully updated: bab75...5efd
Lock file /usr/local/share/GeoIP/.geoipupdate.lock successfully released

保存場所確認。
# ls -l /usr/local/share/GeoIP


2. GeoLite2-Country.mmdbのメタデータを確認

Gemini先生がmmdbファイルのメタデータを確認するスクリプトを作ってくれた。
python用ライブラリをインストール。
# pkg install py311-maxminddb

スクリプトはGistを参照。
Gist: Check metadata of mmdb file. Generate by Gemini 2.5 Pro
# cd /home/software/server-utility/
# vim check_mmdb_meta.py

実行。
# python3.11 ./check_mmdb_meta.py

■■■ GeoIPデータベース メタデータ情報 ■■■
データベースファイル: /usr/local/share/GeoIP/GeoLite2-Country.mmdb
--------------------------------------------------
【ビルド日時】
  ビルドエポックタイム: 1756201338
  ビルド日時 (UTC):   2025-08-26 09:42:18 UTC
  ビルド日時 (ローカル): 2025-08-26 18:42:18 JST

【データベース仕様】
  データベース種別:   GeoLite2-Country
  説明:             GeoLite2 Country database
  対応IPバージョン:   IPv6
  ノード数:         1,585,231
  レコードサイズ:     24 bits


3. cronで定期実行

cronに登録する。
# cd /etc/cron.d/
# vim update_geoip

# 毎週日曜日の朝3時にGeoIPデータベースを更新し、Nginxをリロードする
# -vオプションを付けると詳細なログが表示
# systemctl reload nginx や service nginx reload は、内部的に nginx -s reload を呼び出している
0 3 * * 0 /usr/local/bin/geoipupdate -v && /usr/local/sbin/nginx -s reload && /usr/local/bin/python3 /home/software/server-utility/check_mmdb_meta.py



▼ 関連記事