go-apt-cacherによるお手軽APT専用キャッシュサーバーの導入方法 - 2018-03-06 - ククログ

ククログ

株式会社クリアコード > ククログ > go-apt-cacherによるお手軽APT専用キャッシュサーバーの導入方法

go-apt-cacherによるお手軽APT専用キャッシュサーバーの導入方法

はじめに

DebianでDockerのイメージを検証用に作っては破棄するような使い方をする場合には、ネットワーク経由でのパッケージのインストールやアップデートの遅さが気になることがあります。 そういうときには、APTリポジトリのキャッシュが欲しくなります。定番どころでは apt-cacher-ng がありますが、今回は go-apt-cacher を導入する方法1を紹介します。

go-apt-cacherが開発された背景やその利点については以下の記事が詳しいのでそちらを参照されることをおすすめします。

go-apt-cacherのインストール

すでにGoを導入している環境であれば、go getでインストールすることができます。

go get -u github.com/cybozu-go/aptutil/...

go-apt-cacherの設定ファイルを用意する

go-apt-cacherの設定はTOMLファイルで行います。 go-apt-cacherのリポジトリにサンプルがあります。

適宜必要に応じて変更するとよいでしょう。

  • meta_dir メタ情報ファイルを保存するディレクトリのフルパス

  • cacher_dir キャッシュファイルを保存するディレクトリのフルパス

  • cache_capacity キャッシュの上限をGiB単位で指定します

  • [mapping] マッピング情報を指定します

Debianの場合には、[mapping]セクションに以下のようなエントリを追加するとよいでしょう。

debian = "http://ftp.jp.debian.org/debian"

サンプル設定の全体を以下に示します。

# listen_address is the listening address of go-apt-cacher.
# Default is ":3142".
listen_address = ":3142"

# Interval to check updates for Release/InRelease files.
# Default: 600 seconds
check_interval = 600

# Cache period for bad HTTP response statuses.
# Default: 3 seconds
cache_period = 3

# Directory for meta data files.
# The directory owner must be the same as the process owner of go-apt-cacher.
meta_dir = "/home/kenhys/.cache/go-apt-cacher/meta"

# Directory for non-meta data files.
# This directory must be different from meta_dir.
# The directory owner must be the same as the process owner of go-apt-cacher.
cache_dir = "/home/kenhys/.cache/go-apt-cacher/cache"

# Capacity for cache_dir.
# Default: 1 GiB
cache_capacity = 5

# Maximum concurrent connections for an upstream server.
# Setting this 0 disables limit on the number of connections.
# Default: 10
max_conns = 10

# log specifies logging configurations.
# Details at https://godoc.org/github.com/cybozu-go/cmd#LogConfig
[log]
filename = "/home/kenhys/.cache/go-apt-cacher/go-apt-cacher.log"
level = "info"
format = "plain"

# mapping declares which prefix maps to a Debian repository URL.
# prefix must match this regexp: ^[a-z0-9._-]+$
[mapping]
debian = "http://ftp.jp.debian.org/debian"

go-apt-cacherを起動する

サンプル設定が用意できたら、go-apt-cacherの引数に設定ファイルを明示的に指定して起動します。 引数を指定しなかった場合の既定値では /etc/go-apt-cacher.toml を参照するようになっています。

% go-apt-cacher -f go-apt-cacher.toml

DockerからホストのAPTリポジトリのキャッシュを参照する

go-apt-cacherを起動してAPTリポジトリのキャッシュをできるようになったら、実際にそれが機能しているのか、Dockerを使って試してみましょう。

% docker run -it debian:unstable

あとは、コンテナ内からAPTリポジトリへのプロキシ設定を行います。/etc/apt/apt.conf.d/02proxyなどとして設定します。 この部分はAPTの一般的なお作法の話なので、詳細についてはapt-transport-http(1)を参照してください。

Acquire::http::proxy "http://172.17.0.1:3142/";

172.17.0.1はホストのIPの例です。

あとはコンテナでaptコマンドでパッケージのインストールや更新ができれば成功です。

まとめ

今回は、go-apt-cacher を使ってAPTリポジトリのキャッシュを導入する方法を紹介しました。 DockerイメージのビルドやVMを頻繁に作っては壊すような事例では go-apt-cacher のようなAPT専用のキャッシュサーバを導入するのもよいかもしれません。

  1. あくまでユーザー権限でお試しで動かしてみた事例です。