Package Management

Linuxパッケージ管理 完全ガイド

カテゴリ: Linux System Administration
対象レベル: 中級〜上級
最終更新: 2026-04-10


目次

  1. パッケージ管理の概要
  2. APT系パッケージ管理 (Debian/Ubuntu)
  3. YUM / DNF系パッケージ管理 (RHEL/CentOS/Fedora)
  4. Zypper (openSUSE / SLES)
  5. パッケージクエリと検索
  6. 依存関係の解決
  7. リポジトリ管理
  8. GPGキー検証
  9. ローカルリポジトリの作成
  10. Snap / Flatpak 概要
  11. ソースからのパッケージコンパイル
  12. パッケージマネージャ比較表
  13. トラブルシューティング
  14. ベストプラクティス
  15. 参考文献・リソース

1. パッケージ管理の概要

1.1 パッケージ管理とは

Linuxにおけるパッケージ管理とは、ソフトウェアのインストール・更新・削除・依存関係の解決を体系的に行う仕組みです。手動でのソースコンパイルと異なり、パッケージマネージャを使用することで以下のメリットが得られます。

メリット説明
依存関係の自動解決必要なライブラリや他パッケージを自動インストール
セキュリティ更新CVEパッチを含む更新を集中管理
整合性の保証GPG署名によりパッケージの改ざん検出
一元管理インストール済みパッケージの一覧・追跡
削除の安全性依存関係を考慮した安全なアンインストール

1.2 パッケージの構造

Linuxパッケージは大きく2つの形式に分類されます。

パッケージ形式
├── Debian系 (.deb)
│   ├── control  — メタデータ (名前, バージョン, 依存関係)
│   ├── data.tar.gz  — 実際のファイル群
│   └── md5sums  — チェックサム
└── RPM系 (.rpm)
    ├── ヘッダー (名前, バージョン, アーキテクチャ, 依存関係)
    ├── ペイロード (cpio形式のファイル群)
    └── 署名 (GPG)

.deb パッケージの内部構造確認

# .debファイルの内容確認
$ ar t vim_9.0.1378-2_amd64.deb
debian-binary
control.tar.xz
data.tar.xz

# control情報の展開・確認
$ dpkg-deb --info vim_9.0.1378-2_amd64.deb
 new Debian package, version 2.0.
 size 1740796 bytes: control archive=2124 bytes.
     851 bytes,    19 lines      control
    3879 bytes,    56 lines      md5sums
    1011 bytes,    35 lines   *  postinst             #!/bin/sh
     988 bytes,    28 lines   *  postrm               #!/bin/sh
     354 bytes,    11 lines   *  preinst              #!/bin/sh
     454 bytes,    14 lines   *  prerm                #!/bin/sh
 Package: vim
 Version: 2:9.0.1378-2
 Architecture: amd64
 Maintainer: Debian Vim Maintainers
 Installed-Size: 3847
 Depends: vim-common (= 2:9.0.1378-2), vim-runtime (= 2:9.0.1378-2), ...
 Description: Vi IMproved - enhanced vi editor

.rpm パッケージの内部構造確認

# RPMヘッダー情報確認
$ rpm -qip vim-enhanced-9.0.1378-2.fc38.x86_64.rpm
Name        : vim-enhanced
Version     : 9.0.1378
Release     : 2.fc38
Architecture: x86_64
Install Date: (not installed)
Group       : Unspecified
Size        : 3912706
License     : Vim and MIT
Signature   : RSA/SHA256, Mon 20 Mar 2023 08:14:22 AM JST, Key ID 6a2faea2352c64e5
Source RPM  : vim-9.0.1378-2.fc38.src.rpm
Build Date  : Sun 19 Mar 2023 05:21:33 AM JST
Packager    : Fedora Project
URL         : http://www.vim.org/
Summary     : A version of the VIM editor which includes recent enhancements

1.3 パッケージ管理の全体アーキテクチャ

┌─────────────────────────────────────────────────────┐
│                    ユーザーインターフェース               │
│         (apt / dnf / zypper / snap / flatpak)        │
└───────────────────────┬─────────────────────────────┘
                        │
┌───────────────────────▼─────────────────────────────┐
│               パッケージマネージャ (高レベル)             │
│  ・リポジトリメタデータのダウンロード・キャッシュ            │
│  ・依存関係の解決 (SAT Solver / GreedyAlgorithm)       │
│  ・トランザクション管理                                  │
└───────────────────────┬─────────────────────────────┘
                        │
┌───────────────────────▼─────────────────────────────┐
│           低レベルパッケージツール (dpkg / rpm)           │
│  ・個別パッケージのインストール・削除                      │
│  ・インストール済みDBの管理                              │
│  ・スクリプト実行 (preinst, postinst, prerm, postrm)   │
└───────────────────────┬─────────────────────────────┘
                        │
┌───────────────────────▼─────────────────────────────┐
│                   ファイルシステム                       │
│   /var/lib/dpkg/  または  /var/lib/rpm/               │
└─────────────────────────────────────────────────────┘

1.4 主要ディストリビューションとパッケージマネージャの対応

ディストリビューション系統低レベル高レベルパッケージ形式
Debian / UbuntuDebiandpkgapt, apt-get.deb
Linux MintDebiandpkgapt.deb
RHEL / CentOS 7Red Hatrpmyum.rpm
CentOS 8+ / Fedora / RHEL 8+Red Hatrpmdnf.rpm
openSUSE / SLESSUSErpmzypper.rpm
Arch Linux独立pacman.pkg.tar.zst
Alpine Linux独立apk.apk

2. APT系パッケージ管理 (Debian/Ubuntu)

2.1 apt / apt-get / apt-cache

APT (Advanced Package Tool) はDebian系ディストリビューションの標準パッケージマネージャです。aptapt-getapt-cacheの機能を統合した新しいフロントエンドです。

コマンド体系の関係

apt (ユーザーフレンドリーなフロントエンド)
├── apt-get  (インストール・削除・更新)
├── apt-cache (検索・情報表示)
└── apt-mark  (パッケージのマーク操作)
     └── dpkg (低レベル操作)

基本コマンド一覧

# パッケージリストの更新
$ sudo apt update
Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease
Hit:2 http://archive.ubuntu.com/ubuntu jammy-updates InRelease
Hit:3 http://archive.ubuntu.com/ubuntu jammy-backports InRelease
Get:4 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Fetched 110 kB in 2s (55.0 kB/s)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
42 packages can be upgraded. Run 'apt list --upgradable' to see them.

# 単一パッケージのインストール
$ sudo apt install nginx
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libnginx-mod-http-geoip2 libnginx-mod-http-image-filter ...
  nginx-common nginx-core
Suggested packages:
  fcgiwrap nginx-doc ssl-cert
The following NEW packages will be installed:
  libnginx-mod-http-geoip2 ... nginx nginx-common nginx-core
0 upgraded, 8 newly installed, 0 to remove and 42 not upgraded.
Need to get 609 kB of archives.
After this operation, 2,103 kB of additional disk space will be used.
Do you want to continue? [Y/n]

# 複数パッケージの同時インストール
$ sudo apt install -y curl wget git vim

# パッケージの削除 (設定ファイルを残す)
$ sudo apt remove nginx

# パッケージと設定ファイルを完全削除
$ sudo apt purge nginx

# 不要な依存パッケージの削除
$ sudo apt autoremove

# キャッシュのクリア
$ sudo apt clean        # ダウンロードキャッシュを全削除
$ sudo apt autoclean    # 古いキャッシュのみ削除

# 全パッケージの更新
$ sudo apt upgrade

# カーネルなど依存関係が変わる更新も含む完全更新
$ sudo apt full-upgrade   # 旧: apt-get dist-upgrade

# 更新可能なパッケージ一覧
$ apt list --upgradable
Listing... Done
curl/jammy-updates 7.81.0-1ubuntu1.15 amd64 [upgradable from: 7.81.0-1ubuntu1.13]
openssh-client/jammy-updates 1:8.9p1-3ubuntu0.6 amd64 [upgradable from: 1:8.9p1-3ubuntu0.4]
openssl/jammy-updates 3.0.2-0ubuntu1.15 amd64 [upgradable from: 3.0.2-0ubuntu1.13]

apt-cache によるパッケージ検索と情報表示

# パッケージ名・説明文での検索
$ apt-cache search nginx
nginx - small, powerful, scalable web/proxy server
nginx-common - small, powerful, scalable web/proxy server - common files
nginx-core - nginx web/proxy server (standard version)
nginx-doc - small, powerful, scalable web/proxy server - documentation
nginx-extras - nginx web/proxy server (extended version)
nginx-full - nginx web/proxy server (standard version)

# パッケージの詳細情報
$ apt-cache show nginx
Package: nginx
Version: 1.18.0-6ubuntu14.4
Installed-Size: 51
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Architecture: all
Depends: nginx-core (<< 1.18.0-6ubuntu14.4.1~) | nginx-full (<< 1.18.0-6ubuntu14.4.1~) | ...
Description-en: small, powerful, scalable web/proxy server
 Nginx ("engine X") is a high-performance web and reverse proxy server
 ...

# 依存関係の確認
$ apt-cache depends nginx
nginx
  Depends: nginx-core
  |Depends: nginx-full
  |Depends: nginx-extras
  |Depends: nginx-light

# 逆依存 (このパッケージに依存しているもの)
$ apt-cache rdepends --installed nginx-common
nginx-common
Reverse Depends:
  nginx-core
  nginx

# パッケージのポリシー (バージョン優先度)
$ apt-cache policy nginx
nginx:
  Installed: 1.18.0-6ubuntu14.4
  Candidate: 1.18.0-6ubuntu14.4
  Version table:
 *** 1.18.0-6ubuntu14.4 500
        500 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages
        100 /var/lib/dpkg/status
     1.18.0-0ubuntu1 500
        500 http://archive.ubuntu.com/ubuntu jammy/main amd64 Packages

apt-mark によるパッケージのマーク操作

# パッケージをホールド (自動更新から除外)
$ sudo apt-mark hold nginx
nginx set on hold.

# ホールドの解除
$ sudo apt-mark unhold nginx

# 手動インストール済みとしてマーク
$ sudo apt-mark manual nginx

# 自動インストール済みとしてマーク (autoremove対象になる)
$ sudo apt-mark auto nginx

# ホールド中のパッケージ一覧
$ apt-mark showhold
nginx
linux-image-6.2.0-26-generic

# 手動インストール済み一覧
$ apt-mark showmanual | head -10
apt
bash
curl
git
nginx
openssh-server

apt のオプションと高度な使い方

# 特定バージョンのインストール
$ sudo apt install nginx=1.18.0-0ubuntu1

# ドライラン (実際にはインストールしない)
$ sudo apt install --dry-run nginx
NOTE: This is only a simulation!
      apt needs root privileges for real execution.
      Keep also in mind that locking is deactivated,
      so don't depend on the relevance to the real current situation!
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  nginx nginx-common nginx-core
0 upgraded, 3 newly installed, 0 to remove and 42 not upgraded.
Inst nginx-common (1.18.0-6ubuntu14.4 Ubuntu:22.04/jammy-updates)
Inst nginx-core (1.18.0-6ubuntu14.4 Ubuntu:22.04/jammy-updates)
Inst nginx (1.18.0-6ubuntu14.4 Ubuntu:22.04/jammy-updates)
Conf nginx-common (1.18.0-6ubuntu14.4 Ubuntu:22.04/jammy-updates)
Conf nginx-core (1.18.0-6ubuntu14.4 Ubuntu:22.04/jammy-updates)
Conf nginx (1.18.0-6ubuntu14.4 Ubuntu:22.04/jammy-updates)

# インタラクティブなインターフェース
$ sudo apt-get -f install   # 壊れた依存関係の修正
$ sudo apt-get check        # 依存関係のチェック

2.2 dpkg — 低レベルパッケージ操作

dpkg はDebianパッケージ管理の最下層ツールです。依存関係の解決は行わず、個別パッケージの操作とデータベース管理を担います。

基本操作

# .debファイルのインストール
$ sudo dpkg -i package_name.deb
Selecting previously unselected package vim.
(Reading database ... 75432 files and directories currently installed.)
Preparing to unpack vim_9.0.1378-2_amd64.deb ...
Unpacking vim (2:9.0.1378-2) ...
Setting up vim (2:9.0.1378-2) ...
update-alternatives: using /usr/bin/vim.basic to provide /usr/bin/vim ...

# パッケージの削除
$ sudo dpkg -r vim

# パッケージと設定ファイルの完全削除
$ sudo dpkg -P vim

# インストール済みパッケージ一覧
$ dpkg -l
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                   Version          Architecture Description
+++-======================-================-============-=================================
ii  adduser                3.118ubuntu5     all          add and remove users and groups
ii  apt                    2.4.12           amd64        commandline package manager
ii  bash                   5.1-6ubuntu1.1   amd64        GNU Bourne Again SHell
ii  curl                   7.81.0-1ubuntu1  amd64        command line tool for HTTP/HTTPS
...

# 特定パッケージの状態確認
$ dpkg -l nginx
||/ Name           Version             Architecture Description
+++-==============-===================-============-====================================
ii  nginx          1.18.0-6ubuntu14.4  all          small, powerful, scalable web/proxy

# パッケージのファイル一覧
$ dpkg -L nginx
/.
/usr
/usr/share
/usr/share/doc
/usr/share/doc/nginx
/usr/share/doc/nginx/changelog.Debian.gz
/usr/share/doc/nginx/copyright

# 特定ファイルの所属パッケージを確認
$ dpkg -S /usr/bin/vim
vim: /usr/bin/vim

# パッケージ情報の表示
$ dpkg -p vim
Package: vim
Status: install ok installed
Priority: optional
Section: editors
Installed-Size: 3847
Maintainer: Debian Vim Maintainers
Architecture: amd64
Version: 2:9.0.1378-2
Depends: vim-common (= 2:9.0.1378-2), vim-runtime (= 2:9.0.1378-2)
Suggests: ctags, vim-doc, vim-scripts
Description: Vi IMproved - enhanced vi editor

# dpkgデータベースの整合性確認
$ sudo dpkg --configure -a    # 未設定パッケージの設定完了
$ sudo dpkg --audit           # 問題のあるパッケージを確認

dpkg データベースの場所

/var/lib/dpkg/
├── status          — インストール済みパッケージの状態DB
├── available       — 利用可能パッケージの情報
├── lock            — ロックファイル
├── info/
│   ├── vim.list    — vimに属するファイル一覧
│   ├── vim.md5sums — チェックサム
│   ├── vim.conffiles — 設定ファイル一覧
│   ├── vim.postinst — インストール後スクリプト
│   └── vim.prerm    — 削除前スクリプト
└── updates/        — 保留中の更新

dpkg の選択フラグの意味

フラグ (最初の列)意味
u (Unknown)不明
i (Install)インストール予定
h (Hold)ホールド
r (Remove)削除予定
p (Purge)完全削除予定
フラグ (2番目の列)意味
n (Not)未インストール
i (Installed)インストール済み
c (Config-files)設定ファイルのみ残存
U (Unpacked)展開済み (設定未完)
F (halF-configured)設定途中
H (Half-installed)インストール途中

2.3 sources.list とリポジトリ設定

/etc/apt/sources.list の基本構文

# 構文:
# deb [オプション] URI ディストリビューション [コンポーネント...]
# deb-src [オプション] URI ディストリビューション [コンポーネント...]

# Ubuntu 22.04 (Jammy) の標準 sources.list
deb http://archive.ubuntu.com/ubuntu/ jammy main restricted
deb http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted
deb http://archive.ubuntu.com/ubuntu/ jammy universe
deb http://archive.ubuntu.com/ubuntu/ jammy-updates universe
deb http://archive.ubuntu.com/ubuntu/ jammy multiverse
deb http://archive.ubuntu.com/ubuntu/ jammy-updates multiverse
deb http://archive.ubuntu.com/ubuntu/ jammy-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu jammy-security main restricted
deb http://security.ubuntu.com/ubuntu jammy-security universe
deb http://security.ubuntu.com/ubuntu jammy-security multiverse

# ソースパッケージ (オプション)
deb-src http://archive.ubuntu.com/ubuntu/ jammy main restricted

sources.list.d/ — モジュール式リポジトリ設定

# サードパーティリポジトリは /etc/apt/sources.list.d/ に個別ファイルで管理
$ ls /etc/apt/sources.list.d/
google-chrome.list
nginx.list
docker.list
microsoft-prod.list

モダンな deb822 形式 (.sources)

Ubuntu 22.04以降では新しいdeb822形式が推奨されています。

# /etc/apt/sources.list.d/ubuntu.sources (deb822形式)
Types: deb
URIs: http://archive.ubuntu.com/ubuntu/
Suites: jammy jammy-updates jammy-backports
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg

Types: deb
URIs: http://security.ubuntu.com/ubuntu/
Suites: jammy-security
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg

サードパーティリポジトリの追加例

# 方法1: add-apt-repository コマンドを使う (PPA)
$ sudo add-apt-repository ppa:ondrej/php
$ sudo apt update

# 方法2: GPGキーと一緒に手動追加 (Docker公式の例)
# GPGキーの追加
$ sudo install -m 0755 -d /etc/apt/keyrings
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
    sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
$ sudo chmod a+r /etc/apt/keyrings/docker.gpg

# リポジトリの追加
$ echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
  https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

$ sudo apt update
$ sudo apt install docker-ce docker-ce-cli containerd.io

# 方法3: .sources形式でリポジトリを追加 (モダン)
$ cat /etc/apt/sources.list.d/nginx.sources
Types: deb
URIs: https://nginx.org/packages/ubuntu/
Suites: jammy
Components: nginx
Signed-By: /usr/share/keyrings/nginx-archive-keyring.gpg

APT 優先度の設定 (/etc/apt/preferences.d/)

# /etc/apt/preferences.d/nginx
# バックポートからのnginxを優先する設定
Package: nginx
Pin: release a=jammy-backports
Pin-Priority: 900

# 特定バージョンをピン留め
Package: nginx
Pin: version 1.24.*
Pin-Priority: 1001

# 特定リポジトリを低優先に設定
Package: *
Pin: origin "ppa.launchpad.net"
Pin-Priority: 100

優先度の意味:

優先度動作
< 0インストール禁止
0〜100インストール済みより古い場合のみダウングレード対象外
100〜500インストール済みより新しい場合のみ更新
500〜990標準 (デフォルト)
990〜1000より新しいバージョンが他にあっても優先
> 1000同一バージョンへのダウングレードも実行

APT 設定ファイル (/etc/apt/apt.conf.d/)

# /etc/apt/apt.conf.d/20auto-upgrades — 自動更新設定
APT::Periodic::Update-Package-Lists "1";      // 毎日更新
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";         // 7日ごとにクリーン
APT::Periodic::Unattended-Upgrade "1";        // 自動更新有効

# /etc/apt/apt.conf.d/01proxy — プロキシ設定
Acquire::http::Proxy "http://proxy.example.com:3128/";
Acquire::https::Proxy "https://proxy.example.com:3128/";
Acquire::ftp::Proxy "ftp://proxy.example.com:3128/";

# /etc/apt/apt.conf.d/99recommends — 推奨パッケージを無効化
APT::Install-Recommends "false";
APT::Install-Suggests "false";

# /etc/apt/apt.conf.d/50unattended-upgrades — 自動更新対象の設定
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}";
    "${distro_id}:${distro_codename}-security";
    "${distro_id}ESMApps:${distro_codename}-apps-security";
    "${distro_id}ESM:${distro_codename}-infra-security";
};
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Mail "admin@example.com";

3. YUM / DNF系パッケージ管理 (RHEL/CentOS/Fedora)

3.1 yum コマンド

YUM (Yellowdog Updater Modified) はRed Hat系ディストリビューションで長年使われてきたパッケージマネージャです。CentOS 7まで標準として使用されています。

基本コマンド

# パッケージのインストール
$ sudo yum install nginx
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirror.centos.org
 * extras: mirror.centos.org
 * updates: mirror.centos.org
Resolving Dependencies
--> Running transaction check
---> Package nginx.x86_64 1:1.20.1-10.el7 will be installed
--> Processing Dependency: nginx-filesystem = 1:1.20.1-10.el7 for package: 1:nginx-1.20.1-10.el7.x86_64
--> Running transaction check
---> Package nginx-filesystem.noarch 1:1.20.1-10.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved
=======================================================================
 Package             Arch       Version              Repository    Size
=======================================================================
Installing:
 nginx               x86_64     1:1.20.1-10.el7      epel         562 k
Installing for dependencies:
 nginx-filesystem    noarch     1:1.20.1-10.el7      epel          24 k

Transaction Summary
=======================================================================
Install  1 Package (+1 Dependent package)

Total download size: 586 k
Installed size: 1.6 M
Is this ok [y/d/N]:

# パッケージの削除
$ sudo yum remove nginx

# 全パッケージの更新
$ sudo yum update

# 特定パッケージの更新
$ sudo yum update nginx

# パッケージ情報の表示
$ yum info nginx

# パッケージの検索
$ yum search nginx

# パッケージグループの操作
$ yum grouplist
$ sudo yum groupinstall "Development Tools"
$ sudo yum groupremove "Development Tools"

# インストール済みパッケージ一覧
$ yum list installed
$ yum list installed | grep nginx

# 利用可能なパッケージ一覧
$ yum list available

# トランザクション履歴
$ yum history
ID     | Login user               | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
    12 | root <root>              | 2024-01-15 10:30 | Install        |    3
    11 | root <root>              | 2024-01-14 09:15 | Update         |   15
    10 | root <root>              | 2024-01-10 14:20 | Install        |    1
...

# 特定トランザクションの詳細
$ yum history info 12

# トランザクションの取り消し (ロールバック)
$ sudo yum history undo 12

yum のキャッシュ管理

# キャッシュのクリア
$ sudo yum clean all
Loaded plugins: fastestmirror, langpacks
Cleaning repos: base epel extras updates
Cleaning up everything
Cleaning up list of fastest mirrors

# メタデータのみクリア
$ sudo yum clean metadata

# パッケージキャッシュのみクリア
$ sudo yum clean packages

# キャッシュの再構築
$ sudo yum makecache

3.2 dnf コマンド

DNF (Dandified YUM) はYUMの後継として開発されました。SAT Solverによる高精度な依存関係解決、並列ダウンロード、モジュール機能が特徴です。

基本コマンド (yumとの比較)

# インストール (yumと同じ構文)
$ sudo dnf install nginx

# 更新確認
$ dnf check-update
Last metadata expiration check: 0:05:32 ago on Thu Apr 10 09:00:00 2026.

curl.x86_64                    7.85.0-3.fc38          updates
openssl.x86_64                 3.0.9-1.fc38           updates
openssh.x86_64                 9.3p1-3.fc38           updates
vim-enhanced.x86_64            2:9.0.1678-1.fc38      updates

# セキュリティアップデートのみ適用
$ sudo dnf update --security

# 特定CVEの修正を含む更新を確認
$ dnf updateinfo list security
Last metadata expiration check: 0:05:32 ago
FEDORA-2024-abc123 Important/Sec. curl-7.85.0-3.fc38.x86_64
FEDORA-2024-def456 Moderate/Sec.  openssl-3.0.9-1.fc38.x86_64

# アドバイザリ詳細
$ dnf updateinfo info FEDORA-2024-abc123

# 全更新 (自動的にdist-upgradeに相当)
$ sudo dnf upgrade

# パッケージのダウングレード
$ sudo dnf downgrade nginx

# 特定バージョンのインストール
$ sudo dnf install 'nginx-1.24.0-1.fc38'

DNF モジュール機能 (RHEL 8+)

# 利用可能なモジュール一覧
$ dnf module list
Last metadata expiration check: 0:10:00 ago on Thu Apr 10 09:00:00 2026.
Name         Stream        Profiles     Summary
ant          1.10          common       Java build tool
httpd        2.4 [d][e]    common [d],  Apache HTTP Server
             3.0           common       Apache HTTP Server (next gen)
nodejs       14            common,      Javascript runtime
             16 [d]        common,      Javascript runtime
             18            common,      Javascript runtime
php          7.4           common,devel PHP scripting language
             8.0 [d]       common,devel PHP scripting language
             8.1           common,devel PHP scripting language

# [d] = デフォルト, [e] = 有効化済み

# モジュールストリームの有効化
$ sudo dnf module enable nodejs:18
$ sudo dnf install nodejs

# モジュールプロファイルのインストール
$ sudo dnf module install nodejs:18/common

# モジュールのリセット
$ sudo dnf module reset nodejs

# モジュール情報の表示
$ dnf module info nodejs:18
Name             : nodejs
Stream           : 18
Version          : 9020020230718135023
Context          : b2a24b77
Architecture     : x86_64
Profiles         : common, development, minimal, s2i
Default profiles : common
Repo             : appstream
Summary          : Javascript runtime

DNF プラグイン

# プラグイン一覧
$ dnf list installed 'dnf-plugin*'

# 便利なプラグイン
$ sudo dnf install dnf-plugins-core

# リポジトリ管理プラグイン (yum-config-managerと同等)
$ sudo dnf config-manager --add-repo https://nginx.org/packages/centos/nginx.repo
$ sudo dnf config-manager --enable nginx
$ sudo dnf config-manager --disable nginx

# コマンド実行を記録するプラグイン
$ sudo dnf install 'dnf-command(versionlock)'

# バージョンロック
$ sudo dnf versionlock add nginx
$ sudo dnf versionlock list
$ sudo dnf versionlock delete nginx

DNF のキャッシュと設定

# キャッシュのクリア
$ sudo dnf clean all
$ sudo dnf clean packages
$ sudo dnf clean metadata

# オフラインアップグレード (システム更新の安全な方法)
$ sudo dnf offline-upgrade download  # ダウンロードのみ
$ sudo dnf offline-upgrade reboot    # 再起動後に適用

# 自動更新 (dnf-automatic)
$ sudo dnf install dnf-automatic
$ sudo systemctl enable --now dnf-automatic-install.timer

3.3 rpm — 低レベルパッケージ操作

rpm (RPM Package Manager) はRed Hat系の低レベルパッケージツールです。

基本操作

# .rpmファイルのインストール (-v: 詳細, -h: プログレスバー)
$ sudo rpm -ivh package.rpm
Preparing...                          ################################# [100%]
Updating / installing...
   1:nginx-1:1.24.0-1.fc38           ################################# [100%]

# アップグレード (未インストールなら新規インストール)
$ sudo rpm -Uvh package.rpm

# フレッシュインストール (インストール済みの場合のみ更新)
$ sudo rpm -Fvh package.rpm

# パッケージの削除
$ sudo rpm -e nginx

# 依存関係を無視して強制インストール (非推奨)
$ sudo rpm -ivh --nodeps package.rpm

# インストール済みパッケージ一覧
$ rpm -qa
$ rpm -qa | grep nginx
nginx-1.24.0-1.fc38.x86_64

# パッケージ情報の表示
$ rpm -qi nginx
Name        : nginx
Epoch       : 1
Version     : 1.24.0
Release     : 1.fc38
Architecture: x86_64
Install Date: Thu Apr 10 09:00:00 2026
Group       : System Environment/Daemons
Size        : 1624455
License     : BSD
Signature   : RSA/SHA256, Mon 29 May 2023 09:14:22 AM JST, Key ID ...
Source RPM  : nginx-1.24.0-1.fc38.src.rpm
Build Date  : Sun 28 May 2023 12:00:00 PM JST
URL         : https://nginx.org/
Summary     : A high performance web server and reverse proxy server

# パッケージのファイル一覧
$ rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/nginx.conf
/usr/lib/systemd/system/nginx.service
/usr/sbin/nginx
/var/cache/nginx
/var/log/nginx

# 設定ファイルの確認
$ rpm -qc nginx
/etc/logrotate.d/nginx
/etc/nginx/nginx.conf

# ドキュメントファイルの確認
$ rpm -qd nginx
/usr/share/doc/nginx/CHANGES
/usr/share/doc/nginx/README

# ファイルから所属パッケージを検索
$ rpm -qf /usr/sbin/nginx
nginx-1:1.24.0-1.fc38.x86_64

# 依存関係の確認
$ rpm -qR nginx
/bin/sh
config(nginx) = 1:1.24.0-1.fc38
libcrypto.so.3()(64bit)
libssl.so.3()(64bit)
libz.so.1()(64bit)
nginx-filesystem(x86-64) = 1:1.24.0-1.fc38

# パッケージの整合性検証
$ rpm -V nginx
SM5....T.    /usr/sbin/nginx     ← 変更されている場合

# 整合性検証の出力の意味:
# S: ファイルサイズ変更
# M: パーミッション変更
# 5: MD5チェックサム変更
# D: デバイス変更
# L: シンボリックリンク変更
# U: ユーザー変更
# G: グループ変更
# T: タイムスタンプ変更
# P: ケイパビリティ変更

# GPG署名の確認
$ rpm --checksig package.rpm
package.rpm: digests signatures OK

# インポート済みGPGキーの一覧
$ rpm -qa gpg-pubkey
gpg-pubkey-fd431d51-4ae0493b
gpg-pubkey-8483c65d-4ad3ea9a

RPM データベースの管理

# RPMデータベースの場所
/var/lib/rpm/

# データベースの再構築
$ sudo rpm --rebuilddb

# データベースの整合性チェック
$ sudo rpm --verifydb

3.4 リポジトリ設定ファイル (.repo)

基本的な .repo ファイルの構文

# /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

主要な設定パラメータ

パラメータ説明デフォルト
nameリポジトリの表示名必須
baseurlリポジトリのURLbaseurl/mirrorlistのどちらか必須
mirrorlistミラーリストURL
metalinkメタリンクURL (Fedora)
enabled有効/無効 (0/1)1
gpgcheckGPG署名検証 (0/1)1
gpgkeyGPGキーのURL/パス
priority優先度 (1-99)99
exclude除外パッケージ
includepkgs含めるパッケージのみ
proxyプロキシURL
sslverifySSL検証 (0/1)1
sslcacertCA証明書パス
sslclientcertクライアント証明書
module_hotfixesモジュールフィルター無効false

変数の使用

# $releasever: ディストリビューションのバージョン
# $basearch: アーキテクチャ (x86_64, aarch64など)
# $arch: CPUアーキテクチャ
# $YUM0〜$YUM9: ユーザー定義変数 (/etc/yum/vars/)

[epel]
name=Extra Packages for Enterprise Linux $releasever - $basearch
baseurl=https://dl.fedoraproject.org/pub/epel/$releasever/Everything/$basearch/
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-$releasever&arch=$basearch
gpgcheck=1
gpgkey=https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-$releasever

よく使われるリポジトリの追加例

# EPEL (Extra Packages for Enterprise Linux) の追加
$ sudo dnf install epel-release

# RHEL 9の場合
$ sudo subscription-manager repos --enable codeready-builder-for-rhel-9-$(arch)-rpms
$ sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm

# RPM Fusion (Fedora) の追加
$ sudo dnf install \
  https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm \
  https://mirrors.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm

# リポジトリの一覧表示
$ dnf repolist
repo id               repo name                           status
appstream             Rocky Linux 9 - AppStream           enabled
baseos                Rocky Linux 9 - BaseOS              enabled
epel                  Extra Packages for Enterprise Linux  enabled
extras                Rocky Linux 9 - Extras              enabled
nginx-stable          nginx stable repo                   enabled

# 全リポジトリ (無効含む)
$ dnf repolist all

/etc/dnf/dnf.conf — DNF 設定ファイル

# /etc/dnf/dnf.conf
[main]
gpgcheck=1              # GPG検証を常に有効化
installonly_limit=3     # カーネルの保持数
clean_requirements_on_remove=True  # 依存不要になったパッケージを削除
best=True               # 利用可能な最高バージョンをインストール
skip_if_unavailable=False  # リポジトリ不達時にエラー
fastestmirror=True      # 最速ミラーを使用
max_parallel_downloads=10  # 並列ダウンロード数
timeout=30              # タイムアウト秒数
proxy=http://proxy.example.com:3128  # プロキシ設定

4. Zypper (openSUSE / SLES)

Zypper は openSUSE および SUSE Linux Enterprise Server (SLES) の標準パッケージマネージャです。libsolv (SAT Solver) を使用した高精度な依存関係解決が特徴で、YASTとも統合されています。

4.1 基本コマンド

# リポジトリの更新
$ sudo zypper refresh
Repository 'openSUSE-Leap-15.5-1' is up to date.
Repository 'Update' is up to date.
Repository 'Update Non-Oss' is up to date.
All repositories have been refreshed.

# パッケージのインストール
$ sudo zypper install nginx
Loading repository data...
Reading installed packages...
Resolving package dependencies...

The following 2 NEW packages are going to be installed:
  nginx nginx-default-server

2 new packages to install.
Overall download size: 621.8 KiB. Already cached: 0 B. After the operation,
additional 1.7 MiB will be used.
Continue? [y/n/v/...? shows all options] (y):

# 省略形
$ sudo zypper in nginx      # install
$ sudo zypper rm nginx      # remove
$ sudo zypper up            # update (すべてのパッケージ)
$ sudo zypper up nginx      # 特定パッケージの更新
$ sudo zypper dup           # distribution upgrade

# パッケージの検索
$ zypper search nginx
$ zypper se nginx           # 省略形

# パッケージ情報の表示
$ zypper info nginx
$ zypper if nginx           # 省略形

Loading repository data...
Reading installed packages...
Information for package nginx:
Repository     : Update
Name           : nginx
Version        : 1.21.5-150400.3.6.1
Arch           : x86_64
Vendor         : SUSE LLC <https://www.suse.com>
Installed Size : 1.7 MiB
Installed      : Yes
Status         : up-to-date
Source package : nginx-1.21.5-150400.3.6.1.src
Upstream URL   : https://nginx.org
Summary        : A HTTP server and mail proxy server
Description    :
    nginx is a HTTP and reverse proxy server, a mail proxy server, and
    a generic TCP/UDP proxy server.

# ファイルの所属パッケージを検索
$ zypper search --provides /usr/sbin/nginx

# パッケージのファイル一覧
$ rpm -ql nginx   # zypperはrpmを利用

4.2 リポジトリ管理

# リポジトリ一覧
$ zypper repos
$ zypper lr          # 省略形

# | Alias                    | Name                    | Enabled | GPG Check | Refresh
# --+--------------------------+-------------------------+---------+-----------+--------
#  1 | repo-non-oss             | Non-OSS                 | Yes     | (r ) Yes  | Yes
#  2 | repo-oss                 | OSS                     | Yes     | (r ) Yes  | Yes
#  3 | repo-update              | Update                  | Yes     | (r ) Yes  | Yes
#  4 | repo-update-non-oss      | Update Non-Oss          | Yes     | (r ) Yes  | Yes

# リポジトリの追加
$ sudo zypper addrepo https://download.opensuse.org/repositories/server:http/15.5/server:http.repo
Adding repository 'Web and LAMP stack (openSUSE_Leap_15.5)' ...
Repository 'Web and LAMP stack (openSUSE_Leap_15.5)' successfully added

# URLを指定してリポジトリ追加
$ sudo zypper addrepo -n "NGINX Repo" \
    https://nginx.org/packages/opensuse/leap/15.5/ nginx-stable

# リポジトリの削除
$ sudo zypper removerepo nginx-stable
$ sudo zypper rr nginx-stable    # 省略形

# リポジトリの有効/無効
$ sudo zypper modifyrepo --enable nginx-stable
$ sudo zypper modifyrepo --disable nginx-stable
$ sudo zypper mr -e nginx-stable
$ sudo zypper mr -d nginx-stable

# リポジトリの優先度変更 (低い数字 = 高優先度)
$ sudo zypper modifyrepo --priority 50 nginx-stable
$ sudo zypper mr -p 50 nginx-stable

# GPG検証の有効/無効
$ sudo zypper modifyrepo --gpgcheck-strict nginx-stable
$ sudo zypper modifyrepo --no-gpgcheck nginx-stable  # 非推奨

4.3 Zypper のパターンとパッチ

# パターン (パッケージグループ) の操作
$ zypper patterns
$ zypper install -t pattern lamp_server
$ zypper remove -t pattern lamp_server

# 利用可能なパッチ (セキュリティアップデート) の確認
$ zypper patches
$ zypper lp    # 省略形

# セキュリティパッチのみ適用
$ sudo zypper patch --category security

# 特定パッチの適用
$ sudo zypper patch --bugzilla=1234567

# パッチ情報の詳細
$ zypper info -t patch openSUSE-SLE-15.5-2024-1234

4.4 Zypper のロックと履歴

# パッケージのロック (更新/削除防止)
$ sudo zypper addlock nginx
Specified lock has been successfully added.

# ロック一覧
$ zypper locks
$ zypper ll    # 省略形
# | Name  | Type    | Repository
# --+-------+---------+-----------
#  1 | nginx | package | (any)

# ロックの削除
$ sudo zypper removelock nginx
$ sudo zypper rl nginx

# 変更履歴の確認
$ sudo zypper history
# (rpm -qiを使うことも多い)

# ドライラン
$ sudo zypper --dry-run install nginx
$ sudo zypper -D install nginx   # 省略形

# 非対話モード
$ sudo zypper --non-interactive install nginx
$ sudo zypper -n install nginx   # 省略形

4.5 /etc/zypp/zypp.conf — Zypper 設定ファイル

# /etc/zypp/zypp.conf (主要設定項目)

[main]
## リポジトリキャッシュの有効期間 (分, 0=常に更新)
repo.refresh.delay = 10

## GPG署名の検証
gpgcheck = on

## ダウンロードディレクトリ
cachepath = /var/cache/zypp

## ソルバー設定
solver.dupAllowDowngrade = true
solver.dupAllowNameChange = true
solver.dupAllowArchChange = true
solver.dupAllowVendorChange = false

## プロキシ設定
# proxy = http://proxy.example.com:3128
# proxyuser = user
# proxypass = password

5. パッケージクエリと検索

5.1 インストール済みパッケージの検索

Debian/Ubuntu (dpkg/apt)

# インストール済みパッケージ名の検索
$ dpkg -l | grep nginx
ii  nginx          1.18.0-6ubuntu14.4  all    small, powerful, scalable web/proxy server
ii  nginx-common   1.18.0-6ubuntu14.4  all    small, powerful, scalable web/proxy - common files
ii  nginx-core     1.18.0-6ubuntu14.4  amd64  nginx web/proxy server (standard version)

# パターンマッチで検索
$ apt list --installed 2>/dev/null | grep python
python3/jammy,now 3.10.6-1~22.04 amd64 [installed]
python3-apt/jammy-updates,now 2.4.0ubuntu2 amd64 [installed]

# パッケージの詳細情報
$ dpkg -s nginx
Package: nginx
Status: install ok installed
Priority: optional
Section: httpd
Installed-Size: 51
Maintainer: Ubuntu Developers
Architecture: all
Version: 1.18.0-6ubuntu14.4
Depends: nginx-core (<< 1.18.0-6ubuntu14.4.1~) | ...
Conffiles:
 /etc/init.d/nginx 2c1ad3b9ab55148ae13ad0f83c81dd35
 /etc/logrotate.d/nginx e8c380e24bfbc78f0e16f3fca92b02d6
Description: small, powerful, scalable web/proxy server

RHEL/CentOS/Fedora (rpm/dnf)

# インストール済みパッケージを検索
$ rpm -qa | grep nginx
nginx-1:1.24.0-1.fc38.x86_64
nginx-filesystem-1:1.24.0-1.fc38.noarch

# クエリ形式でリスト
$ dnf list installed | grep nginx

# 詳細情報
$ dnf info nginx

# 特定ファイルを含むパッケージを検索 (インストール済みから)
$ rpm -qf /usr/sbin/nginx
nginx-1:1.24.0-1.fc38.x86_64

# 特定ファイルを含むパッケージを検索 (リポジトリから)
$ dnf provides /usr/sbin/nginx
Last metadata expiration check: 0:15:00 ago
nginx-1:1.24.0-1.fc38.x86_64 : A high performance web server and reverse proxy server
Repo        : @System
Matched from:
Filename    : /usr/sbin/nginx

nginx-1:1.24.0-1.fc38.x86_64 : A high performance web server and reverse proxy server
Repo        : updates
Matched from:
Filename    : /usr/sbin/nginx

# パッケージが提供するコマンドを検索
$ dnf provides '*/vim'

# カスタムクエリフォーマット
$ rpm -qa --queryformat "%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n" | sort | head -20
NetworkManager-1.44.0-3.fc38.x86_64
NetworkManager-libnm-1.44.0-3.fc38.x86_64
abattis-cantarell-fonts-0.303.1-4.fc38.noarch
acl-2.3.1-5.fc38.x86_64
...

# インストール日時でソート
$ rpm -qa --queryformat "%{INSTALLTIME:date} %{NAME}-%{VERSION}\n" | sort -r | head -10
Thu Apr 10 09:00:00 2026 nginx-1.24.0
Wed Apr  9 15:30:00 2026 curl-7.85.0
...

5.2 リポジトリからのパッケージ検索

APT での検索

# テキスト検索 (名前 + 説明)
$ apt-cache search web server
apache2 - Apache HTTP Server
nginx - small, powerful, scalable web/proxy server
lighttpd - fast webserver with minimal memory footprint

# 名前のみで検索
$ apt-cache search --names-only nginx

# 正規表現による検索
$ apt-cache search '^python3-' | head -5
python3-acme - ACME protocol library for Python 3
python3-aiofiles - file support for asyncio
python3-aiohttp - http client/server for asyncio

# パッケージのファイル内容から検索 (apt-file)
$ sudo apt install apt-file
$ sudo apt-file update
$ apt-file search nginx.conf
nginx-common: /etc/nginx/nginx.conf
nginx-full: /usr/share/doc/nginx-full/examples/nginx.conf

# 詳細情報 (全バージョン含む)
$ apt-cache showpkg nginx
Package: nginx
Versions:
1.18.0-6ubuntu14.4 (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_jammy-updates_...)
Dependencies:
1.18.0-6ubuntu14.4 - nginx-core (4 1.18.0-6ubuntu14.4.1~) nginx-full ...

DNF/YUM での検索

# テキスト検索
$ dnf search nginx
$ dnf search all nginx    # 名前+説明+URLなど全フィールド

# 正確な名前で検索
$ dnf info nginx

# ワイルドカード検索
$ dnf list 'python3-*' | head -10

# リポジトリを指定した検索
$ dnf search --repo epel nginx

# whatprovides - 機能/ファイルからパッケージを逆引き
$ dnf whatprovides 'config(nginx)'
$ dnf whatprovides httpd

5.3 パッケージの変更・差分確認

# インストール済みファイルの変更を確認 (rpm)
$ rpm -Va 2>/dev/null | grep -v "^...........  /etc"
SM5....T.    /usr/sbin/sshd          ← バイナリが変更されている!
.M.......    /etc/nginx/nginx.conf   ← パーミッションが変更
..5......    /etc/hosts              ← チェックサムが変更

# debsum による整合性確認 (Debian)
$ sudo apt install debsums
$ debsums nginx-common
/etc/nginx/conf.d/default.conf                                FAILED
/etc/nginx/mime.types                                         OK
/etc/nginx/nginx.conf                                         OK
/usr/share/doc/nginx-common/changelog.Debian.gz               OK

# 設定ファイルの変更確認
$ debsums -c nginx-common   # 変更されたもののみ表示

5.4 パッケージのサイズと統計

# インストール済みパッケージのサイズ上位20個 (Debian)
$ dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -rn | head -20
1048576    linux-image-6.5.0-25-generic
524288     nvidia-driver-535
312439     llvm-15
298765     gcc-12
...

# インストール済みパッケージのサイズ上位20個 (RPM)
$ rpm -qa --queryformat "%{SIZE} %{NAME}\n" | sort -rn | head -20
2831726592 kernel
1624455    nginx
...

# 合計インストールサイズ
$ dpkg-query -Wf '${Installed-Size}\n' | awk '{sum+=$1} END {print sum/1024 " MB"}'
3421.5 MB

6. 依存関係の解決

6.1 依存関係の種類

依存関係の種類Debian (.deb)RPM (.rpm)説明
必須依存DependsRequiresインストール・実行に必須
事前依存Pre-DependsRequires(pre)インストール前に必要
推奨Recommends強く推奨 (デフォルトでインストール)
提案Suggestsあると便利 (デフォルトでは不要)
補完Enhances他パッケージの機能を強化
仮想提供ProvidesProvides仮想パッケージ名を提供
競合ConflictsConflicts共存不可
置換ReplacesObsoletes旧パッケージを置き換える
ビルド依存Build-DependsBuildRequiresコンパイル時に必要

6.2 依存関係の確認方法

APT での依存関係確認

# パッケージの依存関係を確認
$ apt-cache depends nginx
nginx
  Depends: nginx-core
  |Depends: nginx-full
  |Depends: nginx-extras
  |Depends: nginx-light
  Suggests: fcgiwrap
  Suggests: nginx-doc

# 再帰的な依存関係ツリー
$ apt-cache depends --recurse nginx | grep "^\w" | sort -u | head -20
libcrypt1
libc6
libpcre3
libssl3
libz-dev
nginx
nginx-common
nginx-core
...

# 逆依存 (このパッケージを必要としているもの)
$ apt-cache rdepends nginx

# debtree による依存関係グラフ生成
$ sudo apt install debtree
$ debtree nginx > nginx_deps.dot
$ dot -Tpng nginx_deps.dot -o nginx_deps.png

DNF/RPM での依存関係確認

# パッケージの依存関係
$ rpm -qR nginx
$ dnf repoquery --requires nginx

# 依存関係ツリー
$ dnf repoquery --requires --recursive nginx 2>/dev/null | sort -u

# 逆依存 (このパッケージを必要としているもの)
$ rpm -q --whatrequires nginx
$ dnf repoquery --whatrequires nginx

# パッケージが提供するもの
$ rpm -q --provides nginx
nginx = 1:1.24.0-1.fc38
nginx(x86-64) = 1:1.24.0-1.fc38
webserver

# 依存関係ツリーの視覚化
$ sudo dnf install dnf-utils
$ dnfdragora  # GUIツール (オプション)

6.3 依存関係の問題と解決

壊れた依存関係の修正 (APT)

# 壊れた依存関係の確認
$ dpkg -l | grep -E "^(iF|iU|iH|rH|pH)"
iU  broken-package   1.0-1   amd64  Broken package

# 壊れた依存関係の修正
$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Correcting dependencies... Done
The following packages will be REMOVED:
  broken-package
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.

# dpkg の問題を修正
$ sudo dpkg --configure -a
Setting up broken-package (1.0-1) ...
dpkg: error processing package broken-package (--configure):
 installed broken-package package post-installation script subprocess ...
Errors were encountered while processing:
 broken-package

# 強制的に削除
$ sudo dpkg --remove --force-remove-reinstreq broken-package

# インストール済みだが設定されていないパッケージの一覧
$ dpkg --get-selections | grep -v install

依存関係の競合解決 (DNF)

# 依存関係の競合を確認
$ sudo dnf install package-a package-b
Error: Problem:
  - package-a-1.0-1.fc38.x86_64 conflicts with package-b < 2.0
  - package-b-1.9-1.fc38.x86_64 is installed
  - conflicting requests

# 解決策: 特定バージョンを指定
$ sudo dnf install package-a package-b-2.0

# 解決策: 代替パッケージを使用
$ sudo dnf install package-a-compat

# 解決策: --allowerasing オプション (競合パッケージを削除して解決)
$ sudo dnf install package-a --allowerasing

# RPM の依存関係チェック (インストール前)
$ rpm -ivh --test package.rpm
error: Failed dependencies:
    libfoo.so.1()(64bit) is needed by package-1.0-1.x86_64

# 不足している依存関係を提供するパッケージを検索
$ dnf provides 'libfoo.so.1()(64bit)'

6.4 SAT Solver の仕組み

現代のパッケージマネージャ (APT, DNF, Zypper) はSAT (Boolean Satisfiability) Solverを使用して依存関係を解決しています。

依存関係の問題 → 論理式 (CNF形式) に変換 → SAT Solverが解を探索

例:
- nginx をインストールしたい
- nginx は nginx-core または nginx-full または nginx-extras が必要
- nginx-core は libssl3 >= 3.0 が必要
- libssl3 3.0.2 がインストール済み

CNF形式:
  (nginx-core ∨ nginx-full ∨ nginx-extras)  ← nginxの依存
  (nginx-core → libssl3-3.0.2)               ← nginx-coreの依存
  (libssl3-3.0.2 は True)                    ← インストール済み

SAT Solverの解: nginx, nginx-core, libssl3 をインストール ✓

libsolv (ZypperとDNFで使用) は業界最速のSAT Solverの一つで、数千パッケージの依存関係を秒単位で解決できます。


7. リポジトリ管理

7.1 リポジトリの構造

APT リポジトリの構造

http://archive.ubuntu.com/ubuntu/
├── dists/
│   ├── jammy/              ← ディストリビューション名 (スイート)
│   │   ├── InRelease       ← GPG署名付きリリースファイル
│   │   ├── Release         ← リリースメタデータ
│   │   ├── Release.gpg     ← GPG署名 (分離)
│   │   ├── main/           ← コンポーネント
│   │   │   ├── binary-amd64/
│   │   │   │   ├── Packages.gz   ← パッケージメタデータ
│   │   │   │   └── Packages.xz
│   │   │   └── source/
│   │   │       └── Sources.gz
│   │   ├── restricted/
│   │   ├── universe/
│   │   └── multiverse/
│   ├── jammy-updates/
│   └── jammy-security/
└── pool/                   ← 実際のパッケージファイル
    ├── main/
    │   └── n/
    │       └── nginx/
    │           ├── nginx_1.18.0-6ubuntu14.4_all.deb
    │           └── nginx-common_1.18.0-6ubuntu14.4_all.deb
    ├── restricted/
    ├── universe/
    └── multiverse/

RPM リポジトリの構造

https://nginx.org/packages/centos/9/x86_64/
├── repodata/
│   ├── repomd.xml          ← リポジトリメタデータのインデックス
│   ├── repomd.xml.asc      ← GPG署名
│   ├── primary.xml.gz      ← パッケージ情報 (名前, バージョン, 依存関係)
│   ├── filelists.xml.gz    ← ファイルリスト
│   ├── other.xml.gz        ← チェンジログなど
│   └── modules.yaml.gz     ← モジュール情報 (RHEL 8+)
├── nginx-1.24.0-1.el9.ngx.x86_64.rpm
├── nginx-debuginfo-1.24.0-1.el9.ngx.x86_64.rpm
└── nginx-1.24.0-1.el9.ngx.src.rpm

7.2 リポジトリミラーリング

APT ミラーの作成 (apt-mirror)

# apt-mirrorのインストール
$ sudo apt install apt-mirror

# 設定ファイル
$ cat /etc/apt/mirror.list
############# config ##################
set base_path    /var/spool/apt-mirror
set mirror_path  $base_path/mirror
set skel_path    $base_path/skel
set var_path     $base_path/var
set cleanscript  $var_path/clean.sh
set defaultarch  amd64
set nthreads     20
set _tilde 0

############# end config ##############

deb http://archive.ubuntu.com/ubuntu jammy main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu jammy-updates main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu jammy-security main restricted universe multiverse

clean http://archive.ubuntu.com/ubuntu

# ミラーリング実行
$ sudo apt-mirror
Downloading 46 index files using 20 threads...

# Apache/Nginxで公開
$ sudo ln -s /var/spool/apt-mirror/mirror/archive.ubuntu.com/ubuntu \
    /var/www/html/ubuntu

Debmirror を使ったミラー

$ sudo apt install debmirror
$ debmirror \
    --host=archive.ubuntu.com \
    --root=/ubuntu \
    --dist=jammy,jammy-updates,jammy-security \
    --section=main,restricted,universe \
    --arch=amd64 \
    --ignore-missing-info \
    /var/www/mirror/ubuntu

RPM リポジトリのミラーリング (reposync)

# dnf-utils/yum-utils のインストール
$ sudo dnf install dnf-utils

# リポジトリの同期
$ sudo reposync \
    --repoid=epel \
    --download-path=/var/repos/epel \
    --newest-only \
    --download-metadata

# 全有効リポジトリを同期
$ sudo reposync --download-path=/var/repos/

# cronで定期同期
$ cat /etc/cron.d/repo-sync
0 2 * * * root reposync --repoid=epel --download-path=/var/repos/epel \
    --newest-only --download-metadata 2>&1 | logger -t reposync

7.3 Nginx/Apache でリポジトリをサービス

# /etc/nginx/conf.d/local-repo.conf
server {
    listen 80;
    server_name repo.internal.example.com;

    root /var/repos;
    autoindex on;

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

    # セキュリティヘッダー
    add_header X-Content-Type-Options nosniff;

    # ログ
    access_log /var/log/nginx/repo-access.log;
    error_log /var/log/nginx/repo-error.log;
}

8. GPGキー検証

8.1 GPG署名の仕組み

パッケージの改ざんを防ぐため、現代のLinuxパッケージマネージャはGPG (GNU Privacy Guard) 署名を使用します。

パッケージのビルド・配布の流れ:
┌──────────────┐     ┌───────────────────────────────┐
│ パッケージ    │     │ GPG秘密鍵でパッケージに署名     │
│ メンテナー    │────▶│ $ gpg --detach-sign pkg.rpm    │
└──────────────┘     └───────────────┬───────────────┘
                                     │ pkg.rpm + pkg.rpm.asc
                                     ▼
                      ┌──────────────────────────────┐
                      │       リポジトリサーバー        │
                      │  (署名付きパッケージを配布)     │
                      └──────────────┬───────────────┘
                                     │
                     ┌───────────────▼───────────────┐
                     │          エンドユーザー          │
                     │ 1. GPG公開鍵をシステムに登録     │
                     │ 2. パッケージダウンロード         │
                     │ 3. 署名検証 → インストール       │
                     └──────────────────────────────┘

8.2 APT での GPG 管理

旧来の方法 (非推奨: apt-key)

# GPGキーのインポート (非推奨: 全リポジトリに適用されるため)
$ curl -fsSL https://packages.example.com/gpg | sudo apt-key add -
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead
OK

# インポート済みキーの一覧
$ sudo apt-key list
/etc/apt/trusted.gpg
--------------------
pub   rsa2048 2023-01-01 [SC]
      1234 5678 9ABC DEF0 1234 5678 9ABC DEF0 1234 5678
uid           [ unknown] Package Maintainer <maint@example.com>
sub   rsa2048 2023-01-01 [E]

推奨方法: /etc/apt/keyrings/ への配置

# キーリングディレクトリの作成
$ sudo install -m 0755 -d /etc/apt/keyrings

# GPGキーのダウンロードと変換 (armor → binary)
$ curl -fsSL https://packages.example.com/gpg.key | \
    gpg --dearmor | \
    sudo tee /etc/apt/keyrings/example.gpg > /dev/null

# キーの確認
$ gpg --no-default-keyring \
    --keyring /etc/apt/keyrings/example.gpg \
    --fingerprint
/etc/apt/keyrings/example.gpg
-------------------------------
pub   rsa4096 2023-01-01 [SC]
      A8D3 6847 3246 4127 B8E1  7A23 9D4E 5F1A B2C3 D4E5
uid           [ unknown] Example Repository <repo@example.com>
sub   rsa4096 2023-01-01 [E]

# signed-by を指定してリポジトリを追加
$ echo "deb [signed-by=/etc/apt/keyrings/example.gpg] \
    https://packages.example.com/ubuntu jammy stable" | \
    sudo tee /etc/apt/sources.list.d/example.list

# GPG鍵の有効期限確認
$ gpg --no-default-keyring \
    --keyring /etc/apt/keyrings/example.gpg \
    --list-keys --with-colons | grep "^pub" | \
    awk -F: '{print $7}' | \
    while read exp; do
        if [ -n "$exp" ]; then
            echo "有効期限: $(date -d @$exp '+%Y-%m-%d')"
        fi
    done

InRelease ファイルの検証プロセス

# APTが内部的に行う検証の確認
$ gpg --no-default-keyring \
    --keyring /usr/share/keyrings/ubuntu-archive-keyring.gpg \
    --verify /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_jammy_InRelease

# Packagesファイルのハッシュ確認
# InReleaseファイル内のSHA256ハッシュと実際のPackagesファイルを照合
$ grep "Packages" /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_jammy_InRelease | \
    head -5
 sha256:abc123... 12345 main/binary-amd64/Packages
 sha256:def456... 67890 main/binary-amd64/Packages.gz

8.3 RPM での GPG 管理

# GPGキーのインポート
$ sudo rpm --import https://nginx.org/keys/nginx_signing.key

# インポート済みキーの確認
$ rpm -qa gpg-pubkey --qf "%{NAME}-%{VERSION}-%{RELEASE}\t%{SUMMARY}\n"
gpg-pubkey-7bd9bf62-5762b5f8  gpg(nginx signing key <signing-key@nginx.com>)
gpg-pubkey-fd431d51-4ae0493b  gpg(Fedora (38) <fedora-38-primary@fedoraproject.org>)

# キーの詳細情報
$ rpm -qi gpg-pubkey-7bd9bf62-5762b5f8
Name        : gpg-pubkey
Version     : 7bd9bf62
Release     : 5762b5f8
Install Date: Thu Apr 10 09:00:00 2026
Group       : Public Keys
Size        : 0
License     : pubkey
Summary     : gpg(nginx signing key <signing-key@nginx.com>)

# パッケージの署名確認
$ rpm --checksig nginx-1.24.0-1.el9.ngx.x86_64.rpm
nginx-1.24.0-1.el9.ngx.x86_64.rpm: digests signatures OK

# 署名の詳細確認
$ rpm -K --verbose nginx-1.24.0-1.el9.ngx.x86_64.rpm
nginx-1.24.0-1.el9.ngx.x86_64.rpm:
    Header V4 RSA/SHA256 Signature, key ID 7bd9bf62: OK
    Header SHA256 digest: OK
    V4 RSA/SHA256 Signature, key ID 7bd9bf62: OK
    MD5 digest: OK

# GPGキーの削除
$ sudo rpm -e gpg-pubkey-7bd9bf62-5762b5f8

# /etc/yum.repos.d/*.repo から GPGキーをインポート
$ sudo dnf config-manager --add-repo https://nginx.org/packages/rhel/nginx.repo
$ sudo dnf install nginx  # 初回インストール時にキーのインポート確認

8.4 Zypper での GPG 管理

# リポジトリのGPGキーをインポート
$ sudo zypper --gpg-auto-import-keys refresh

# GPGキーの一覧
$ sudo zypper keys
Key ID     | Key Name                       | Key Fingerprint              | Expires
-----------+--------------------------------+------------------------------+--------
7BD9BF62   | nginx signing key              | 573B FD6B 3D8F BC64 1079 A6A- | (none)

# キーの信頼設定
$ sudo zypper modifyrepo --gpgcheck-strict nginx-stable  # 厳格な検証
$ sudo zypper modifyrepo --gpgcheck-allow-unsigned nginx-stable  # 署名なし許可 (非推奨)

8.5 独自 GPG キーペアの作成 (ローカルリポジトリ用)

# GPGキーペアの生成
$ gpg --full-generate-key
gpg (GnuPG) 2.2.40; Copyright (C) 2022 g10 Code GmbH
Please select what kind of key you want:
   (1) RSA and RSA (default)
   (4) RSA (sign only)
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (3072) 4096
Key is valid for? (0) 2y
...
Real name: My Repo Key
Email address: repo@internal.example.com
Comment: Internal Repository Signing Key
...

# 公開鍵のエクスポート
$ gpg --armor --export repo@internal.example.com > repo-key.pub

# 秘密鍵のバックアップ (安全な場所に保管)
$ gpg --armor --export-secret-keys repo@internal.example.com > repo-key-private.asc

# キーの指紋確認
$ gpg --fingerprint repo@internal.example.com
pub   rsa4096 2026-04-10 [SC] [expires: 2028-04-09]
      A1B2 C3D4 E5F6 7890 1234 5678 9ABC DEF0 1234 5678
uid           [ultimate] My Repo Key (Internal Repository Signing Key) <repo@internal.example.com>
sub   rsa4096 2026-04-10 [E] [expires: 2028-04-09]

9. ローカルリポジトリの作成

9.1 APT ローカルリポジトリの作成

reprepro を使った本格的なリポジトリ

# reprepro のインストール
$ sudo apt install reprepro

# ディレクトリ構造の作成
$ sudo mkdir -p /var/repos/apt/conf

# distributions ファイルの作成
$ cat /var/repos/apt/conf/distributions
Origin: My Company
Label: My Internal Repo
Codename: jammy
Architectures: amd64 arm64
Components: main
Description: Internal package repository
SignWith: repo@internal.example.com
Log: /var/log/reprepro.log

# options ファイル
$ cat /var/repos/apt/conf/options
verbose
ask-passphrase
basedir /var/repos/apt

# パッケージの追加
$ reprepro -b /var/repos/apt includedeb jammy /path/to/package.deb
Exporting indices...

# 特定バージョンの追加
$ reprepro -b /var/repos/apt includedeb jammy my-app_1.0-1_amd64.deb

# パッケージの削除
$ reprepro -b /var/repos/apt remove jammy my-app

# リポジトリの一覧表示
$ reprepro -b /var/repos/apt list jammy

# Nginxで公開
$ cat /etc/nginx/conf.d/apt-repo.conf
server {
    listen 80;
    server_name apt.internal.example.com;
    root /var/repos/apt;
    autoindex on;
    location / {
        try_files $uri $uri/ =404;
    }
}

# クライアント側の設定
$ echo "deb [signed-by=/etc/apt/keyrings/internal-repo.gpg] \
    http://apt.internal.example.com jammy main" | \
    sudo tee /etc/apt/sources.list.d/internal.list

apt-ftparchive を使った簡易リポジトリ

# パッケージを配置するディレクトリ
$ mkdir -p /var/repos/simple/{pool,dists/stable/main/binary-amd64}

# パッケージのコピー
$ cp *.deb /var/repos/simple/pool/

# Packagesファイルの生成
$ cd /var/repos/simple
$ apt-ftparchive packages pool > dists/stable/main/binary-amd64/Packages
$ gzip -k dists/stable/main/binary-amd64/Packages

# Releaseファイルの生成
$ cat > apt-release.conf << 'EOF'
APT::FTPArchive::Release::Origin "My Repo";
APT::FTPArchive::Release::Label "My Repo";
APT::FTPArchive::Release::Suite "stable";
APT::FTPArchive::Release::Codename "stable";
APT::FTPArchive::Release::Architectures "amd64";
APT::FTPArchive::Release::Components "main";
APT::FTPArchive::Release::Description "My Local Repository";
EOF

$ apt-ftparchive -c apt-release.conf release dists/stable > dists/stable/Release

# GPG署名
$ gpg --default-key repo@internal.example.com \
    --clearsign \
    -o dists/stable/InRelease \
    dists/stable/Release

$ gpg --default-key repo@internal.example.com \
    --detach-sign \
    --armor \
    -o dists/stable/Release.gpg \
    dists/stable/Release

9.2 RPM ローカルリポジトリの作成

createrepo_c を使ったリポジトリ作成

# createrepo_c のインストール
$ sudo dnf install createrepo_c

# ディレクトリの作成と RPM の配置
$ sudo mkdir -p /var/repos/rpm/el9/x86_64
$ sudo cp *.rpm /var/repos/rpm/el9/x86_64/

# リポジトリメタデータの生成
$ sudo createrepo_c /var/repos/rpm/el9/x86_64/
Directory walk started
Directory walk done - 15 packages
Temporary output repo path: /var/repos/rpm/el9/x86_64/.repodata/
Preparing sqlite DBs
Pool started (with 5 workers)
Pool finished
15 packages to process
Done.

# GPG署名でリポジトリに署名
$ sudo gpg --default-key repo@internal.example.com \
    --detach-sign --armor \
    /var/repos/rpm/el9/x86_64/repodata/repomd.xml

# 更新時の増分更新 (差分のみ更新: 高速)
$ sudo createrepo_c --update /var/repos/rpm/el9/x86_64/

# worker数を増やして高速化
$ sudo createrepo_c --workers 8 /var/repos/rpm/el9/x86_64/

# .repo ファイルの作成
$ cat > /var/repos/rpm/my-internal.repo << 'EOF'
[my-internal]
name=My Internal Repository - $basearch
baseurl=http://repo.internal.example.com/rpm/el$releasever/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://repo.internal.example.com/RPM-GPG-KEY-MyRepo
EOF

# Nginxで公開
$ cat /etc/nginx/conf.d/rpm-repo.conf
server {
    listen 80;
    server_name repo.internal.example.com;
    root /var/repos;
    autoindex on;
    location / {
        try_files $uri $uri/ =404;
    }
}

# クライアント側のリポジトリ追加
$ sudo dnf config-manager \
    --add-repo http://repo.internal.example.com/rpm/my-internal.repo

# GPGキーのインポート
$ sudo rpm --import http://repo.internal.example.com/RPM-GPG-KEY-MyRepo

9.3 Pulp / Nexus による高度なリポジトリ管理

企業環境では、Pulp や Nexus Repository などのリポジトリマネージャが使われます。

# Pulp 3 のインストール (概要)
# https://pulpproject.org/

# Nexus Repository Manager の起動 (Docker)
$ docker run -d \
    --name nexus \
    -p 8081:8081 \
    -v nexus-data:/nexus-data \
    sonatype/nexus3

# Nexus でのAPTリポジトリ作成:
# 1. Repositories → Create repository
# 2. apt (hosted) を選択
# 3. 名前、ディストリビューション設定
# 4. クライアント設定
$ echo "deb http://nexus.internal.example.com/repository/apt-internal \
    jammy main" | sudo tee /etc/apt/sources.list.d/nexus.list

9.4 ローカルファイルシステムリポジトリ (オフライン環境)

# APT: ローカルディレクトリをリポジトリとして使用
$ echo "deb [trusted=yes] file:/var/repos/apt stable main" | \
    sudo tee /etc/apt/sources.list.d/local.list
$ sudo apt update

# RPM: ローカルディレクトリをリポジトリとして使用
$ cat /etc/yum.repos.d/local.repo
[local]
name=Local Repository
baseurl=file:///var/repos/rpm/
enabled=1
gpgcheck=0      # ローカルの場合はGPG検証を無効化することがある

# インストール済みパッケージからオフラインリポジトリ作成
$ mkdir /var/repos/local
$ cp /var/cache/apt/archives/*.deb /var/repos/local/
$ (cd /var/repos/local && dpkg-scanpackages . | gzip > Packages.gz)

10. Snap / Flatpak 概要

10.1 ユニバーサルパッケージの背景

従来のディストリビューション依存パッケージ管理の課題を解決するため、ユニバーサルパッケージ形式が開発されました。

課題解決策
ディストリビューション間の非互換性単一パッケージが複数ディストリで動作
依存関係の「地獄」依存関係を全てパッケージ内に同梱
古いライブラリへの縛り最新ライブラリを独自にバンドル可能
開発者の配布負担単一ストアから全ディストリに配布

10.2 Snap

Snapは Canonical (Ubuntu) が開発したユニバーサルパッケージ形式です。

アーキテクチャ

┌────────────────────────────────────────┐
│              Snap Store                │
│   (snapcraft.io - クラウドストア)        │
└──────────────────┬─────────────────────┘
                   │ HTTPS
┌──────────────────▼─────────────────────┐
│            snapd デーモン               │
│  ・スナップのダウンロード・管理           │
│  ・Squashfsのマウント                   │
│  ・セキュリティサンドボックス (AppArmor) │
│  ・自動更新                             │
└──────────────────┬─────────────────────┘
                   │
┌──────────────────▼─────────────────────┐
│     Snap パッケージ (.snap)              │
│   (SquashFS形式 - 読み取り専用)          │
│   /snap/<name>/<revision>/              │
└────────────────────────────────────────┘

Snap の基本コマンド

# snapd のインストール (Ubuntu以外)
$ sudo apt install snapd            # Debian
$ sudo dnf install snapd            # Fedora/RHEL
$ sudo zypper install snapd         # openSUSE
$ sudo systemctl enable --now snapd.socket

# パッケージのインストール
$ sudo snap install firefox
firefox 124.0-1 from Mozilla✓ installed

# クラシックモード (サンドボックス制限を緩和)
$ sudo snap install code --classic

# 利用可能なスナップを検索
$ snap find text-editor
Name          Version   Publisher       Notes  Summary
gedit         41.0      snapcrafters    -      The GNOME text editor
kate          23.08.5   kde             -      KDE Advanced Text Editor
mousepad      0.6.1     snapcrafters    -      Lightweight text editor

# インストール済みスナップの一覧
$ snap list
Name        Version          Rev    Tracking         Publisher     Notes
core20      20231123         2182   latest/stable    canonical✓    base
core22      20240111         1122   latest/stable    canonical✓    base
firefox     124.0-1          3922   latest/stable    mozilla✓      -
snapd       2.61.3           21185  latest/stable    canonical✓    snapd

# スナップの更新
$ sudo snap refresh
$ sudo snap refresh firefox

# スナップの削除
$ sudo snap remove firefox

# リビジョンの確認と切り替え (ロールバック)
$ snap list --all firefox
Name     Version  Rev   Tracking        Publisher  Notes
firefox  124.0-1  3922  latest/stable   mozilla✓   -
firefox  123.0-1  3850  latest/stable   mozilla✓   disabled

$ sudo snap revert firefox

# 自動更新の確認
$ snap refresh --time
timer: 00:00~24:00/4
last: today at 08:15 JST
next: today at 14:15 JST

# 自動更新の一時停止
$ sudo snap set system refresh.hold="$(date --date='2 days' +%Y-%m-%dT%H:%M:%S%:z)"

# インターフェース (権限) の管理
$ snap connections firefox
Interface         Plug                         Slot           Notes
browser-support   firefox:browser-support      :browser-support  -
camera            firefox:camera               -              -
home              firefox:home                 :home          -
network           firefox:network              :network       -

$ sudo snap connect firefox:camera :camera

Snap のストレージ構造

/snap/                          # マウントポイント
├── bin/                        # snapコマンドのシムリンク
├── firefox/
│   ├── current -> 3922/        # 現在のリビジョン
│   └── 3922/                   # 展開されたsnap内容
/var/lib/snapd/
├── snaps/                      # ダウンロードされた.snapファイル
│   ├── firefox_3922.snap
│   └── firefox_3850.snap       # 前のリビジョン
├── assertions/                 # 署名済みアサーション
└── state.json                  # snapdの状態

10.3 Flatpak

Flatpakはディストリビューション非依存のデスクトップアプリ配布形式で、主にGNOME/KDEコミュニティが推進しています。

アーキテクチャ

┌────────────────────────────────────────┐
│          Flathub / Remote              │
│   (flathub.org または カスタム)         │
└──────────────────┬─────────────────────┘
                   │ OSTree (Git風差分更新)
┌──────────────────▼─────────────────────┐
│         Flatpak ランタイム              │
│  ・GNOME Platform Runtime              │
│  ・KDE Runtime                         │
│  ・freedesktop Runtime                 │
└──────────────────┬─────────────────────┘
                   │ bubblewrap サンドボックス
┌──────────────────▼─────────────────────┐
│     Flatpak アプリケーション             │
│   ~/.local/share/flatpak/ または        │
│   /var/lib/flatpak/                    │
└────────────────────────────────────────┘

Flatpak の基本コマンド

# Flatpakのインストール
$ sudo apt install flatpak            # Ubuntu/Debian
$ sudo dnf install flatpak            # Fedora
$ sudo zypper install flatpak         # openSUSE

# Flathubリポジトリの追加
$ flatpak remote-add --if-not-exists flathub \
    https://dl.flathub.org/repo/flathub.flatpakrepo

# リモートリポジトリの一覧
$ flatpak remotes
Name     Options
flathub  system,oci

# アプリの検索
$ flatpak search firefox
Application ID          Branch  Remotes  Description
org.mozilla.firefox     stable  flathub  Fast, Private & Safe Web Browser

# アプリのインストール (システム全体)
$ sudo flatpak install flathub org.mozilla.firefox
Looking for matches…
Required runtime for org.mozilla.firefox/x86_64/stable (runtime/org.freedesktop.Platform/...

# アプリのインストール (ユーザー単位)
$ flatpak install --user flathub org.mozilla.firefox

# インストール済みアプリの一覧
$ flatpak list
Application ID                    Branch  Origin  Installation
com.visualstudio.code             stable  flathub system
org.mozilla.firefox               stable  flathub system
org.gimp.GIMP                     stable  flathub system

# アプリの実行
$ flatpak run org.mozilla.firefox

# アプリの更新
$ flatpak update
$ flatpak update org.mozilla.firefox

# アプリの削除
$ flatpak uninstall org.mozilla.firefox
$ flatpak uninstall --unused   # 不要なランタイムも削除

# 権限 (パーミッション) の管理
$ flatpak info --show-permissions org.mozilla.firefox
[Context]
sockets=x11;wayland;pulseaudio;
shared=network;ipc;
filesystems=xdg-download;

# Flatseal (GUI権限管理ツール)
$ flatpak install flathub com.github.tchx84.Flatseal

# 環境変数の上書き
$ flatpak override --user --env=LANG=ja_JP.UTF-8 org.mozilla.firefox

# ファイルシステムアクセスの付与
$ flatpak override --user --filesystem=home org.mozilla.firefox

# ネットワークアクセスの無効化
$ flatpak override --user --no-share=network org.mozilla.firefox

10.4 Snap vs Flatpak 比較

項目SnapFlatpak
開発元Canonical独立コミュニティ (freedesktop)
主な用途デスクトップ + サーバー + IoTデスクトップアプリ
ストアSnap Store (1箇所のみ)Flathub + カスタムリモート
サンドボックスAppArmor + seccompbubblewrap + seccomp
更新方式差分 (delta snap)OSTree (差分)
ストレージSquashFS (圧縮)OSTree
デーモンsnapd (常駐必須)不要
起動速度やや遅い (SquashFSマウント)標準
カスタムリモート不可
サーバーアプリ対応デスクトップのみ
CLIアプリ対応限定的
オープン性Snap Store はプロプライエタリ完全オープン

10.5 AppImage

AppImageはインストール不要で単一実行ファイルとして配布される形式です。

# AppImageのダウンロードと実行
$ wget https://example.com/MyApp.AppImage
$ chmod +x MyApp.AppImage
$ ./MyApp.AppImage

# AppImageLauncherでシステム統合
$ sudo apt install appimagelauncher

# SquashFSの中身を確認
$ ./MyApp.AppImage --appimage-extract
# squashfs-root/ に展開される

11. ソースからのパッケージコンパイル

11.1 コンパイルの基本フロー

ソースコード取得
      │
      ▼
ビルド依存関係のインストール
      │
      ▼
./configure (または cmake, meson)
  ・機能の有効/無効設定
  ・インストールパスの指定
  ・ライブラリの検出
      │
      ▼
make (またはninja)
  ・コンパイル・リンク
      │
      ▼
make test (テスト実行)
      │
      ▼
make install (またはパッケージ化)

11.2 autotools (./configure && make && make install)

最も伝統的なビルドシステムです。

# ビルド依存関係のインストール (Debian)
$ sudo apt install build-essential autoconf automake libtool
$ sudo apt install libssl-dev libpcre3-dev zlib1g-dev

# ビルド依存関係のインストール (RHEL/Fedora)
$ sudo dnf install gcc make autoconf automake libtool
$ sudo dnf install openssl-devel pcre-devel zlib-devel

# ソースコードの取得
$ wget https://nginx.org/download/nginx-1.24.0.tar.gz
$ tar -xzf nginx-1.24.0.tar.gz
$ cd nginx-1.24.0/

# configureオプションの確認
$ ./configure --help | head -30
  --help                             print this message
  --prefix=PATH                      set installation prefix
  --sbin-path=PATH                   set nginx binary pathname
  --modules-path=PATH                set modules path
  --conf-path=PATH                   set nginx.conf pathname
  --error-log-path=PATH              set error log pathname
  ...
  --with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
  ...

# 設定 (本番環境向け)
$ ./configure \
    --prefix=/etc/nginx \
    --sbin-path=/usr/sbin/nginx \
    --modules-path=/usr/lib64/nginx/modules \
    --conf-path=/etc/nginx/nginx.conf \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --pid-path=/var/run/nginx.pid \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_gzip_static_module \
    --with-threads \
    --with-stream \
    --with-pcre \
    --with-openssl=/usr/local/openssl

checking for OS
 + Linux 6.5.0-25-generic x86_64
checking for C compiler ... found
 + using GNU C compiler
 + gcc version: 12.3.0 (Ubuntu 12.3.0-1ubuntu1~22.04)
...
Configuration summary
  + using system PCRE2 library
  + using system OpenSSL library
  + using system zlib library

  nginx path prefix: "/etc/nginx"
  nginx binary file: "/usr/sbin/nginx"
  ...

# コンパイル (並列ビルドで高速化)
$ make -j$(nproc)
make -f objs/Makefile
make[1]: Entering directory '/home/user/nginx-1.24.0'
cc -c -pipe -O -W -Wall ...
...

# テスト (オプション)
$ make test

# インストール
$ sudo make install

# または パッケージ管理下でのインストール (checkinstall推奨)
$ sudo apt install checkinstall
$ sudo checkinstall --install=yes \
    --pkgname=nginx-custom \
    --pkgversion=1.24.0 \
    --pkgrelease=1 \
    make install
# → nginx-custom_1.24.0-1_amd64.deb が生成され、dpkgで管理される

11.3 CMake によるビルド

# CMake のインストール
$ sudo apt install cmake ninja-build

# ソースコードの取得と設定
$ git clone https://github.com/example/project.git
$ cd project
$ mkdir build && cd build

# CMakeの設定
$ cmake .. \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=/usr/local \
    -DENABLE_SSL=ON \
    -DENABLE_TESTS=OFF
-- The C compiler identification is GNU 12.3.0
-- The CXX compiler identification is GNU 12.3.0
-- Detecting C compiler ABI info - done
-- Build files have been written to: /home/user/project/build

# Ninja を使ったビルド (高速)
$ cmake .. -GNinja
$ ninja -j$(nproc)
[1/50] Building C object src/CMakeFiles/project.dir/main.c.o
...
[50/50] Linking CXX executable project

# または make を使用
$ make -j$(nproc)

# インストール
$ sudo make install
$ sudo ninja install   # Ninja の場合

11.4 Meson によるビルド

# Meson のインストール
$ sudo apt install meson ninja-build
$ sudo pip3 install meson   # または pip で最新版

# ビルド設定
$ meson setup builddir \
    --prefix=/usr/local \
    --buildtype=release \
    -Denable_docs=false
The Meson build system
Version: 1.2.0
Build type: release
...

# ビルド
$ meson compile -C builddir
ninja: Entering directory 'builddir'
[1/30] Compiling C source ...
...

# テスト
$ meson test -C builddir

# インストール
$ sudo meson install -C builddir

11.5 RPM パッケージの作成 (rpmbuild)

ソースからRPMパッケージを作成することで、パッケージ管理下に置けます。

# rpmbuildのインストール
$ sudo dnf install rpm-build rpmdevtools

# RPMビルド環境のセットアップ
$ rpmdev-setuptree
$ ls ~/rpmbuild/
BUILD  BUILDROOT  RPMS  SOURCES  SPECS  SRPMS

# ソースのダウンロード
$ wget https://nginx.org/download/nginx-1.24.0.tar.gz \
    -O ~/rpmbuild/SOURCES/nginx-1.24.0.tar.gz

# SPECファイルの作成
$ cat ~/rpmbuild/SPECS/nginx.spec
Name:           nginx
Version:        1.24.0
Release:        1%{?dist}
Summary:        A high performance web server and reverse proxy server

License:        BSD
URL:            https://nginx.org/
Source0:        https://nginx.org/download/%{name}-%{version}.tar.gz

BuildRequires:  gcc
BuildRequires:  openssl-devel
BuildRequires:  pcre-devel
BuildRequires:  zlib-devel

%description
nginx [engine x] is an HTTP and reverse proxy server.

%prep
%autosetup

%build
./configure \
    --prefix=%{_sysconfdir}/nginx \
    --sbin-path=%{_sbindir}/nginx \
    --with-http_ssl_module \
    --with-http_v2_module

%{__make} %{?_smp_mflags}

%install
%{__make} install DESTDIR=%{buildroot}

%files
%doc CHANGES README
%{_sbindir}/nginx
%{_sysconfdir}/nginx/
%dir %{_localstatedir}/log/nginx/

%changelog
* Thu Apr 10 2026 Builder <builder@example.com> - 1.24.0-1
- Initial package build

# RPMのビルド
$ rpmbuild -ba ~/rpmbuild/SPECS/nginx.spec
Executing(%prep): ...
+ cd /root/rpmbuild/BUILD
+ tar -xzf /root/rpmbuild/SOURCES/nginx-1.24.0.tar.gz
...
Wrote: /root/rpmbuild/RPMS/x86_64/nginx-1.24.0-1.fc38.x86_64.rpm
Wrote: /root/rpmbuild/SRPMS/nginx-1.24.0-1.fc38.src.rpm

# 生成されたRPMのインストール
$ sudo rpm -ivh ~/rpmbuild/RPMS/x86_64/nginx-1.24.0-1.fc38.x86_64.rpm

11.6 Debian パッケージの作成 (debuild)

# ビルドツールのインストール
$ sudo apt install devscripts debhelper dh-make build-essential

# ソースの準備
$ mkdir nginx-1.24.0
$ cd nginx-1.24.0
$ wget https://nginx.org/download/nginx-1.24.0.tar.gz
$ tar -xzf nginx-1.24.0.tar.gz --strip-components=1

# Debianパッケージング初期化
$ dh_make --single --createorig --file nginx-1.24.0.tar.gz
Type of package: (single, indep, library, python)
[s/i/l/p]? s
...
Done. Please edit the files in the debian/ subdirectory now.

# debian/control の編集
$ cat debian/control
Source: nginx
Section: httpd
Priority: optional
Maintainer: Your Name <you@example.com>
Build-Depends: debhelper-compat (= 13), libssl-dev, libpcre3-dev, zlib1g-dev
Standards-Version: 4.6.0

Package: nginx
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: A high performance web server
 nginx is an HTTP and reverse proxy server.

# debian/rules の編集
$ cat debian/rules
#!/usr/bin/make -f
%:
	dh $@

override_dh_auto_configure:
	./configure \
		--prefix=/etc/nginx \
		--sbin-path=/usr/sbin/nginx \
		--with-http_ssl_module

# パッケージのビルド
$ debuild -us -uc   # 署名なし
dpkg-buildpackage -us -uc -ui
...
dpkg-deb: building package 'nginx' in '../nginx_1.24.0-1_amd64.deb'

# または GPG署名付きビルド
$ debuild -k"your-key-id"

11.7 コンパイル時のデバッグ情報とオプション

# デバッグビルド
$ ./configure --enable-debug
$ make CFLAGS="-g -O0 -DDEBUG"

# プロファイリングビルド
$ make CFLAGS="-pg -O2"
$ gprof ./program gmon.out > analysis.txt

# アドレスサニタイザー (メモリバグの検出)
$ make CFLAGS="-fsanitize=address -g" LDFLAGS="-fsanitize=address"

# インストール先の確認
$ make -n install   # ドライラン

# ライブラリパスの確認
$ ldd /usr/sbin/nginx
	linux-vdso.so.1 (0x00007ffd6a9b7000)
	libssl.so.3 => /lib/x86_64-linux-gnu/libssl.so.3
	libcrypto.so.3 => /lib/x86_64-linux-gnu/libcrypto.so.3
	libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6

# pkg-config を使ったライブラリ情報の確認
$ pkg-config --libs --cflags openssl
-lssl -lcrypto
$ pkg-config --modversion openssl
3.0.2

# 代替インストール方法 (DESTDIR)
$ sudo make install DESTDIR=/tmp/staging
$ ls /tmp/staging/usr/sbin/nginx
/tmp/staging/usr/sbin/nginx

12. パッケージマネージャ比較表

12.1 主要コマンド対応表

操作apt (Debian/Ubuntu)dnf/yum (RHEL/Fedora)zypper (SUSE)pacman (Arch)
リスト更新apt updatednf check-updatezypper refreshpacman -Sy
インストールapt install PKGdnf install PKGzypper install PKGpacman -S PKG
削除apt remove PKGdnf remove PKGzypper remove PKGpacman -R PKG
完全削除apt purge PKGdnf remove PKGzypper purge PKGpacman -Rn PKG
更新(全体)apt upgradednf upgradezypper updatepacman -Su
更新+依存apt full-upgradednf distro-synczypper duppacman -Syu
不要削除apt autoremovednf autoremovezypper autoremovepacman -Rns $(pacman -Qdtq)
キャッシュクリアapt cleandnf clean allzypper cleanpacman -Sc
検索apt search PKGdnf search PKGzypper search PKGpacman -Ss PKG
情報表示apt show PKGdnf info PKGzypper info PKGpacman -Si PKG
インストール済み一覧dpkg -lrpm -qazypper packages --installedpacman -Q
ファイル→パッケージdpkg -S FILErpm -qf FILEzypper search --provides FILEpacman -Qo FILE
パッケージ→ファイルdpkg -L PKGrpm -ql PKGrpm -ql PKGpacman -Ql PKG
依存関係確認apt-cache depends PKGdnf deplist PKGzypper info -r PKGpactree PKG
逆依存確認apt-cache rdepends PKGdnf repoquery --whatrequires PKGpactree -r PKG
リポジトリ一覧apt-cache policydnf repolistzypper reposcat /etc/pacman.d/mirrorlist
リポジトリ追加add-apt-repositorydnf config-manager --add-repozypper addrepomirrorlistを編集
整合性確認debsums PKGrpm -V PKGrpm -V PKGpacman -Qk PKG
ホールドapt-mark hold PKGdnf versionlock add PKGzypper addlock PKGpacman -D --asexplicit PKG
ダウングレードapt install PKG=VERdnf downgrade PKGzypper install PKG=VERpacman -U /path/to/pkg
GPGキー追加gpg --dearmorrpm --import KEYzypper --gpg-auto-import-keys refreshpacman-key --add KEY

12.2 設定ファイルの比較

項目Debian/UbuntuRHEL/CentOS/FedoraopenSUSE/SLES
リポジトリ設定/etc/apt/sources.list /etc/apt/sources.list.d/*.list/etc/yum.repos.d/*.repo/etc/zypp/repos.d/*.repo
GPGキー/etc/apt/keyrings/ /usr/share/keyrings//etc/pki/rpm-gpg//etc/zypp/repos.d/
メイン設定/etc/apt/apt.conf.d//etc/dnf/dnf.conf/etc/zypp/zypp.conf
優先度設定/etc/apt/preferences.d/リポジトリの priority=zypper modifyrepo --priority
プロキシ設定/etc/apt/apt.conf.d//etc/dnf/dnf.conf/etc/zypp/zypp.conf
パッケージDB/var/lib/dpkg//var/lib/rpm//var/lib/rpm/
キャッシュ/var/cache/apt//var/cache/dnf//var/cache/zypp/
ログ/var/log/apt/ /var/log/dpkg.log/var/log/dnf.log/var/log/zypp/history.log

12.3 パッケージ形式の比較

特性.deb.rpm.snap.flatpakAppImage
圧縮形式tar.gz/xzcpioSquashFSOSTreeSquashFS
依存関係外部依存外部依存同梱ランタイム共有同梱
サンドボックスなしなしAppArmorbubblewrapなし
インストール先/usr, /etc等/usr, /etc等/snap//var/lib/flatpak任意
スクリプトpre/postinst, pre/postrmpre/post/preun/postunなしなしなし
デルタ更新あり (apt)あり (delta rpm)ありあり (OSTree)なし
署名検証GPGGPGStore署名GPGGnuPG
対象Debian系Red Hat系/SUSE全Linux全Linux全Linux

12.4 パッケージ管理方針の比較

方針Debian stableUbuntu LTSFedoraRHEL/CentOS
更新頻度年1〜2回2年ごと6ヶ月ごと3〜5年ごと
パッケージ数~59,000~60,000~60,000~5,000
安定性重視度最高最高
最新性重視度低〜中最低
サポート期間5年 (LTS)10年 (ESM)13ヶ月10年
バックポートありあり限定的あり
適合用途サーバー/デスクトップサーバー/クラウド開発/最新エンタープライズ

13. トラブルシューティング

13.1 APT 系のトラブルシューティング

問題1: ロックファイルのエラー

# エラーメッセージ
E: Could not get lock /var/lib/dpkg/lock-frontend.
   It is held by process 12345 (apt-get)

# 確認: 実際にaptが動作しているか確認
$ ps aux | grep -E 'apt|dpkg'
root     12345  0.5  1.2 apt-get upgrade

# 別のaptプロセスが動いている場合は待つ
$ sudo lsof /var/lib/dpkg/lock-frontend
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apt-get 12345 root    4uW  REG    8,1        0  ... lock-frontend

# プロセスが終了している (ゾンビ) 場合はロックを削除
$ sudo rm /var/lib/dpkg/lock-frontend
$ sudo rm /var/lib/dpkg/lock
$ sudo rm /var/cache/apt/archives/lock
$ sudo dpkg --configure -a   # 中断した設定を完了

# unattended-upgradesが動いている場合
$ sudo systemctl status unattended-upgrades
$ sudo systemctl stop unattended-upgrades
$ sudo apt upgrade
$ sudo systemctl start unattended-upgrades

問題2: 壊れたパッケージの修正

# エラー: dpkg was interrupted
$ sudo apt update
E: dpkg was interrupted, you must manually run
   'sudo dpkg --configure -a' to correct the problem.

# 解決手順
$ sudo dpkg --configure -a
Setting up nginx-common (1.18.0-6ubuntu14.4) ...
...

# それでも失敗する場合
$ sudo dpkg --configure -a 2>&1 | tail -20
dpkg: error processing package nginx-common (--configure):
 subprocess installed post-installation script returned error exit status 1

# 問題のパッケージを強制削除して再インストール
$ sudo dpkg --remove --force-remove-reinstreq nginx-common
$ sudo apt install nginx-common

# 依存関係の修正
$ sudo apt-get -f install

# パッケージDBの再構築
$ sudo dpkg --clear-avail
$ sudo apt update

問題3: GPG エラー

# エラーメッセージ
W: GPG error: https://packages.example.com jammy InRelease:
   The following signatures couldn't be verified because the public key
   is not available: NO_PUBKEY A8D368473246413B

# 解決: 公開鍵の取得と追加
$ sudo apt-key adv --keyserver keyserver.ubuntu.com \
    --recv-keys A8D368473246413B
# または
$ curl -fsSL https://packages.example.com/gpg.key | \
    sudo gpg --dearmor -o /etc/apt/keyrings/example.gpg
$ sudo apt update

# 鍵が期限切れの場合
$ sudo apt-key list
pub   rsa4096 2020-01-01 [SC] [expired: 2023-01-01]
$ sudo apt-key del KEYID
# 新しいキーをダウンロードして追加

問題4: リポジトリの接続エラー

# エラーメッセージ
Err:1 http://archive.ubuntu.com/ubuntu jammy InRelease
  Could not connect to archive.ubuntu.com:80 (91.189.91.38)

# ネットワーク確認
$ ping -c 3 archive.ubuntu.com
$ curl -I http://archive.ubuntu.com/ubuntu/dists/jammy/InRelease

# プロキシ設定
$ export http_proxy=http://proxy.example.com:3128
$ export https_proxy=http://proxy.example.com:3128
$ sudo -E apt update

# または apt.conf に設定
$ echo 'Acquire::http::Proxy "http://proxy.example.com:3128";' | \
    sudo tee /etc/apt/apt.conf.d/99proxy

# ミラーサイトに切り替え
$ sudo sed -i 's|archive.ubuntu.com|jp.archive.ubuntu.com|g' \
    /etc/apt/sources.list
$ sudo apt update

問題5: パッケージのバージョン競合

# エラーメッセージ
The following packages have unmet dependencies:
 package-a : Depends: libfoo (>= 2.0) but 1.9 is to be installed

# 利用可能なバージョン確認
$ apt-cache policy libfoo
libfoo:
  Installed: 1.9
  Candidate: 1.9
  Version table:
 *** 1.9 500
        500 http://archive.ubuntu.com/ubuntu jammy/main

# バックポートリポジトリを追加して新バージョンを取得
$ sudo add-apt-repository ppa:example/ppa
$ sudo apt update
$ sudo apt install libfoo

# またはaptitude (インタラクティブな依存関係解決)
$ sudo apt install aptitude
$ sudo aptitude install package-a
# aptitudeは複数の解決策を提示する

13.2 DNF/YUM 系のトラブルシューティング

問題1: メタデータの問題

# エラー: Failed to synchronize cache for repo
$ sudo dnf update
Failed to synchronize cache for repo 'appstream'

# キャッシュのクリアと再試行
$ sudo dnf clean all
$ sudo dnf makecache
$ sudo dnf update

# 特定リポジトリを無効化して続行
$ sudo dnf update --disablerepo=appstream

# タイムアウトの調整
$ sudo dnf update --setopt=timeout=120

問題2: RPM データベースの破損

# エラー: error: rpmdb: BDB0113 Thread/process ...

# RPMデータベースの再構築
$ sudo rpm --rebuilddb

# または
$ sudo rm -f /var/lib/rpm/__db.*
$ sudo rpm --rebuilddb

# dnf の状態確認
$ sudo dnf --enablerepo=* list installed 2>&1 | head -20

# SQLite DBの修復 (RHEL 8+)
$ sudo rpm --rebuilddb --define "_dbpath /var/lib/rpm"

問題3: 依存関係の競合

# エラーメッセージ
Error: Problem: package-a-1.0 conflicts with package-b < 2.0

# 競合の詳細確認
$ dnf repoquery --conflicts package-a

# 解決策1: 両パッケージの最新版を使う
$ sudo dnf update package-a package-b

# 解決策2: 競合パッケージを削除して対象をインストール
$ sudo dnf install package-a --allowerasing

# 解決策3: 別の互換パッケージを使用
$ dnf search "package-a compatible"

# Python依存関係の問題
$ sudo dnf install python3-package
# それでも失敗する場合
$ sudo pip3 install package --user

問題4: GPG 署名エラー

# エラーメッセージ
Error: GPG check FAILED

# GPGキーのインポート
$ sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-9
$ sudo rpm --import https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-9

# 一時的にGPG検証を無効化 (本番環境では非推奨)
$ sudo dnf install package --nogpgcheck

# リポジトリのGPG設定確認
$ cat /etc/yum.repos.d/epel.repo | grep gpg
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-9

# キーファイルの存在確認
$ ls -la /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-9

13.3 Zypper のトラブルシューティング

# ロックの問題
$ sudo zypper refresh
System management is locked by the application with pid 1234 (zypper).
Close this application before trying again.

# プロセスの確認と終了
$ sudo fuser /var/run/zypp.pid
$ sudo kill -9 1234
$ sudo rm /var/run/zypp.pid

# リポジトリの問題
$ sudo zypper refresh
Download (curl) error for 'http://download.opensuse.org/...':
Error code: Connection failed

$ sudo zypper modifyrepo --disable broken-repo
$ sudo zypper refresh

# 依存関係の問題
$ sudo zypper install package-a
Problem: package-a requires lib-b >= 2.0, but this requirement cannot be provided

# 解決策の確認
$ sudo zypper install --details package-a
# zypper は複数の解決策を提示し、ユーザーが選択できる

13.4 共通ユーティリティとデバッグ技法

# ログの確認
# APT
$ tail -100 /var/log/apt/history.log
$ tail -100 /var/log/dpkg.log

# DNF
$ tail -100 /var/log/dnf.log
$ tail -100 /var/log/dnf.rpm.log

# Zypper
$ tail -100 /var/log/zypp/history.log

# ネットワークのデバッグ
$ apt-get -o Debug::Acquire::http=true update 2>&1 | head -50
$ dnf update -v 2>&1 | head -50

# パッケージのダウンロードのみ (インストールなし)
$ apt-get download nginx
$ dnf download nginx
$ zypper download nginx

# オフラインインストール用のパッケージ収集
$ sudo apt-get install --download-only nginx
$ sudo dnf install --downloadonly --downloaddir=/tmp/packages nginx

# strace でパッケージマネージャの動作追跡
$ sudo strace -f apt-get install nginx 2>&1 | grep "open\|write" | head -30

# インストールシミュレーション
$ apt-get install --simulate nginx
$ dnf install --assumeno nginx
$ zypper install --dry-run nginx

14. ベストプラクティス

14.1 セキュリティ

1. 常に GPG 検証を有効化する

# APT: GPG検証を強制
# /etc/apt/apt.conf.d/99security
APT::Get::AllowUnauthenticated "false";

# DNF: GPGを常に検証
# /etc/dnf/dnf.conf
[main]
gpgcheck=1
localpkg_gpgcheck=1    # ローカルRPMにも検証を強制

# Zypper: 厳格なGPG検証
$ sudo zypper modifyrepo --gpgcheck-strict <repo>

2. 不要なリポジトリを無効化する

# 本当に必要なリポジトリのみ有効化
$ sudo dnf config-manager --disable rpmfusion-nonfree-tainted

# 定期的にリポジトリを監査
$ dnf repolist enabled
$ apt-cache policy | grep "^http"

3. 自動セキュリティアップデートの設定

# Ubuntu/Debian: unattended-upgrades
$ sudo apt install unattended-upgrades
$ sudo dpkg-reconfigure --priority=low unattended-upgrades

# RHEL/Fedora: dnf-automatic
$ sudo dnf install dnf-automatic
$ sudo vi /etc/dnf/automatic.conf
[commands]
apply_updates = yes
upgrade_type = security    # セキュリティアップデートのみ

$ sudo systemctl enable --now dnf-automatic-install.timer

# メールによる通知設定 (dnf-automatic.conf)
[emitters]
emit_via = motd, command_email
[email]
email_from = dnf-automatic@server.example.com
email_to = admin@example.com
email_host = localhost

4. パッケージの整合性を定期確認

# 週次整合性チェックのcron設定 (RPM)
$ cat /etc/cron.weekly/rpm-verify
#!/bin/bash
rpm -Va 2>/dev/null | \
    grep -v "^.......\.  /etc" | \
    grep -v "^.......\.  /var" | \
    mail -s "RPM Integrity Check: $(hostname)" admin@example.com

$ sudo chmod +x /etc/cron.weekly/rpm-verify

# debsums による定期チェック (Debian)
$ cat /etc/cron.weekly/debsums-check
#!/bin/bash
debsums --all --changed 2>/dev/null | \
    mail -s "debsums check: $(hostname)" admin@example.com

14.2 パフォーマンス

5. 並列ダウンロードの設定

# DNF: 並列ダウンロード数の増加
# /etc/dnf/dnf.conf
max_parallel_downloads=10
fastestmirror=True

# APT: 並列ダウンロード
# /etc/apt/apt.conf.d/99parallel
Acquire::Queue-Mode "access";
Acquire::http::Pipeline-Depth "5";

6. ローカルキャッシュの活用

# APT: キャッシュを使ったオフラインインストール
$ sudo apt-get download $(apt-cache depends --recurse nginx | grep "^\w")
$ sudo dpkg -i *.deb   # オフライン環境で使用

# DNF: ローカルキャッシュの保持
# /etc/dnf/dnf.conf
keepcache=1

# apt-cacher-ng: APTキャッシュプロキシ (チーム共有)
$ sudo apt install apt-cacher-ng
# クライアント設定
$ echo 'Acquire::http::Proxy "http://cache-server:3142";' | \
    sudo tee /etc/apt/apt.conf.d/01proxy

# dnf-plugin-local: ローカルキャッシュリポジトリ
$ sudo dnf install dnf-plugin-local

7. 適切なミラーの選択

# Debian: 最速ミラーの選択
$ sudo apt install netselect-apt
$ sudo netselect-apt stable
# → /etc/apt/sources.list を最速ミラーで更新

# Fedora: metalinkによる自動ミラー選択
# metalink=https://mirrors.fedoraproject.org/metalink?repo=fedora-$releasever&arch=$basearch

# Ubuntu: apt-select
$ pip install apt-select
$ apt-select --country JP --top-number 5

14.3 管理・運用

8. 変更管理とロールバック

# DNF: トランザクション履歴と安全なロールバック
$ dnf history                          # 履歴一覧
$ dnf history info 25                  # 特定トランザクションの詳細
$ sudo dnf history undo 25             # 特定トランザクションを取り消し
$ sudo dnf history rollback 24         # 特定時点までロールバック

# Debian: 変更の記録
$ sudo apt-get install apt-listchanges # 変更ログの表示
$ cat /var/log/apt/history.log         # APT操作の完全ログ

# スナップショット (LVMまたはBtrfs使用時)
$ sudo lvcreate --snapshot --name snap_root -L 5G /dev/vg/root
$ sudo btrfs subvolume snapshot / /snap_before_update

9. 大規模環境でのパッケージ管理

# Ansible によるパッケージ管理の自動化
$ cat playbook.yml
---
- name: Ensure packages are installed
  hosts: all
  become: yes
  tasks:
    - name: Update package cache
      ansible.builtin.package:
        update_cache: yes

    - name: Install common packages
      ansible.builtin.package:
        name:
          - vim
          - curl
          - git
          - htop
        state: present

    - name: Ensure nginx is at specific version
      ansible.builtin.package:
        name: nginx=1.24.0-1
        state: present
      when: ansible_os_family == "Debian"

# Puppet によるパッケージ管理
package { 'nginx':
  ensure => '1.24.0',
}

# Chef によるパッケージ管理
package 'nginx' do
  version '1.24.0'
  action :install
end

10. パッケージのバージョン固定 (Pin/Lock)

# APT: 重要パッケージのバージョン固定
# /etc/apt/preferences.d/pin-nginx
Package: nginx nginx-common nginx-core
Pin: version 1.18.*
Pin-Priority: 1001

# 確認
$ apt-cache policy nginx

# DNF: バージョンロック
$ sudo dnf install 'dnf-command(versionlock)'
$ sudo dnf versionlock add nginx
$ sudo dnf versionlock list
Loaded plugins: versionlock
nginx-1:1.24.0-1.fc38.*

# Zypper: ロック
$ sudo zypper addlock nginx
$ sudo zypper locks

11. クリーンなシステム維持

# 不要パッケージの定期クリーンアップ
$ sudo apt autoremove --purge          # Debian
$ sudo dnf autoremove                  # RHEL/Fedora
$ sudo zypper packages --unneeded      # SUSE

# 古いカーネルの削除
$ sudo apt autoremove --purge          # 自動的に古いカーネルを削除
$ sudo dnf remove $(dnf repoquery --installonly --latest-limit=-2 -q)

# パッケージキャッシュのクリーンアップ
$ sudo apt clean
$ sudo dnf clean all
$ sudo zypper clean --all

# deborphan: Debianの孤立パッケージ検出
$ sudo apt install deborphan
$ deborphan | xargs sudo apt-get -y remove --purge

# 手動インストールされた不要パッケージの確認
$ apt-mark showmanual | sort

14.4 ドキュメンテーション

12. パッケージ変更のドキュメント化

# インストール済みパッケージ一覧のエクスポート
# Debian
$ dpkg --get-selections > installed-packages.txt
$ apt-mark showmanual > manually-installed.txt

# RPM
$ rpm -qa --queryformat "%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n" | \
    sort > installed-packages.txt

# 復元用
$ sudo dpkg --set-selections < installed-packages.txt
$ sudo apt-get dselect-upgrade

# 変更ログの確認
$ zcat /usr/share/doc/nginx/changelog.Debian.gz | head -30
$ rpm -q --changelog nginx | head -30

14.5 セキュリティチェックリスト

定期的なセキュリティ監査チェックリスト:

□ セキュリティアップデートを毎日適用 (自動化推奨)
□ パッケージの整合性を週次確認 (rpm -Va / debsums)
□ インストールリポジトリを最小限に維持
□ GPG検証が全リポジトリで有効化されていることを確認
□ 不要パッケージを月次で削除
□ インストール済みパッケージ一覧をバックアップ
□ EOLを迎えたパッケージの確認 (debian-security-support等)
□ CVEデータベースとの照合 (trivy, grype等のツールを使用)
□ サードパーティリポジトリの信頼性を確認
□ 開発/テスト用パッケージが本番環境にないことを確認

# CVEスキャンツールの例
$ trivy fs --security-checks vuln /
$ grype dir:/

15. 参考文献・リソース

15.1 公式ドキュメント

APT / Debian

リソースURL
Debian パッケージ管理マニュアルhttps://www.debian.org/doc/manuals/debian-reference/ch02.en.html
APT ユーザーガイドhttps://www.debian.org/doc/manuals/apt-guide/
dpkg マニュアルhttps://manpages.debian.org/dpkg
Debian Policy Manual (パッケージ形式)https://www.debian.org/doc/debian-policy/
Ubuntu パッケージ管理https://ubuntu.com/server/docs/package-management
Debian セキュリティ情報https://www.debian.org/security/

YUM / DNF / RPM

リソースURL
DNF ドキュメントhttps://dnf.readthedocs.io/
RPM.org ドキュメントhttps://rpm.org/documentation.html
RPM Packaging Guidehttps://rpm-packaging-guide.github.io/
RHEL パッケージ管理https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html/managing_software_with_the_dnf_tool/
Fedora パッケージガイドhttps://docs.fedoraproject.org/en-US/packaging-guidelines/

Zypper / SUSE

リソースURL
Zypper ユーザーガイドhttps://documentation.suse.com/sles/15-SP5/html/SLES-all/cha-sw-cl.html
openSUSE Zypper Wikihttps://en.opensuse.org/SDB:Zypper_usage
SUSE パッケージハブhttps://packagehub.suse.com/

Snap / Flatpak

リソースURL
Snapcraft ドキュメントhttps://snapcraft.io/docs
Snap Storehttps://snapcraft.io/store
Flatpak ドキュメントhttps://docs.flatpak.org/
Flathubhttps://flathub.org/
AppImage ドキュメントhttps://docs.appimage.org/

15.2 man ページ

# APT関連
$ man apt
$ man apt-get
$ man apt-cache
$ man apt-mark
$ man apt.conf
$ man sources.list
$ man dpkg
$ man dpkg-query
$ man dpkg-reconfigure

# RPM/DNF関連
$ man dnf
$ man yum
$ man rpm
$ man rpm2cpio
$ man rpmbuild
$ man repoquery

# GPG関連
$ man gpg
$ man gpg2

# ソースビルド関連
$ man make
$ man autoconf
$ man cmake
$ man checkinstall

15.3 便利なオンラインツール

ツール説明URL
packages.debian.orgDebianパッケージ検索https://packages.debian.org/
packages.ubuntu.comUbuntuパッケージ検索https://packages.ubuntu.com/
pkgs.org複数ディストリでのパッケージ検索https://pkgs.org/
repology.orgパッケージバージョン追跡https://repology.org/
koji.fedoraproject.orgFedoraビルドシステムhttps://koji.fedoraproject.org/
copr.fedorainfracloud.orgFedora COPRビルドhttps://copr.fedorainfracloud.org/
launchpad.net/ubuntu/+ppasUbuntu PPA検索https://launchpad.net/ubuntu/+ppas
security.debian.orgDebianセキュリティ追跡https://security-tracker.debian.org/

15.4 セキュリティ追跡ツール

# trivy: コンテナ/OS脆弱性スキャナ
$ docker run aquasec/trivy fs /

# grype: OSSパッケージの脆弱性スキャン
$ curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | \
    sh -s -- -b /usr/local/bin
$ grype dir:/

# debian-security-support: EOLパッケージの確認
$ sudo apt install debian-security-support
$ check-support-status

# RHEL/CentOS: セキュリティアドバイザリ
$ dnf updateinfo list security --installed

15.5 学習リソース

リソース種類説明
Linux Foundation LFS101無料コースLinux入門
LPIC-1 / CompTIA Linux+資格Linuxパッケージ管理含む
"The Debian Administrator's Handbook"書籍 (無料)Debianの深い理解
"Fedora System Administration Guide"公式ドキュメントRPM系の管理
Arch Linux WikiWikiパッケージ管理の高度なトピック

まとめ

Linuxのパッケージ管理は、システム管理者にとって最も基本的かつ重要なスキルの一つです。本記事で学んだ主要ポイントをまとめます。

キーポイント

  1. 適切なツールの選択: ディストリビューションに応じてAPT、DNF/YUM、Zypperを使い分ける
  2. 高レベルと低レベルの使い分け: 日常操作はapt/dnf/zypper、詳細操作はdpkg/rpmを使う
  3. GPG署名の徹底: 全リポジトリでGPG検証を有効化し、パッケージの改ざんを防ぐ
  4. リポジトリ管理: 必要最小限のリポジトリのみ有効化し、ローカルリポジトリで帯域・セキュリティを制御
  5. 自動セキュリティ更新: unattended-upgrades/dnf-automaticでセキュリティパッチを迅速に適用
  6. ソースコンパイル: 標準リポジトリにない場合や特定ビルドオプションが必要な場合はcheckinstall/rpmbuildでパッケージ化
  7. 定期的な整合性確認: rpm -Va/debsumsでシステムの改ざん検出
  8. 構成管理の統合: AnsibleやPuppetでパッケージ管理を自動化・標準化

現代のLinux環境ではSnapやFlatpakなどのユニバーサルパッケージも増えていますが、サーバー環境ではネイティブパッケージマネージャが依然として主流です。ベストプラクティスを守りながら適切なツールを選択することで、安全で安定したシステム運用が実現できます。