DNSキャッシュ時間の問題

Cloud Native Build Pack で Spring Boot アプリのコンテナイメージを作れるから簡単だと思っていると、いい感じにDNSキャッシュ時間の設定値を構成する方法が無くて困る。

blog.astj.space

1. $JAVA_HOME/lib/security/java.security に記述

初期設定では、Cloud Natie Buildpack でイメージを作成すると、JREpaketo-buildpack/bellsoft-libericaを使う。

このBuildpackは、環境変数JAVA_TOOLS_OPTS-Djava.security.properties=<path>を埋め込むようになっており、java.securityの代わりに別の場所へ配置したプロパティファイルを使うようになる。

起動時のログでも確認できる。

Setting Active Processor Count to 8
Calculating JVM memory based on 2708640K available memory
Calculated JVM Memory Configuration: -XX:MaxDirectMemorySize=10M -Xmx2327887K -XX:MaxMetaspaceSize=73552K -XX:ReservedCodeCacheSize=240M -Xss1M (Total Memory: 2708640K, Thread Count: 50, Loaded Class Count: 10572, Headroom: 0%)
Adding 129 container CA certificates to JVM truststore
Spring Cloud Bindings Enabled
Picked up JAVA_TOOL_OPTIONS: -Djava.security.properties=/layers/paketo-buildpacks_bellsoft-liberica/java-security-properties/java-security.properties -agentpath:/layers/paketo-buildpacks_bellsoft-liberica/jvmkill/jvmkill-1.16.0-RELEASE.so=printHeapHistogram=1 -XX:ActiveProcessorCount=8 -XX:MaxDirectMemorySize=10M -Xmx2327887K -XX:MaxMetaspaceSize=73552K -XX:ReservedCodeCacheSize=240M -Xss1M -Dorg.springframework.cloud.bindings.boot.enable=true
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.5)

つまり、Buildpackの作成したレイヤーに作成されていることがわかる。

ビルド時に内容を設定できるのか考えたけど、ただ作ってるだけでそういう機能はないらしい。(paketo-buildpacks/libjvm/blob/main/java_security_properties.go#L47

まとめ

  • Cloud Native Buildpackで作成したコンテナイメージは、標準と違う場所に置いたプロパティファイルを使用する
  • コンテナイメージを作成するとき、設定だけでプロパティファイルをカスタマイズする方法は不明
  • コンテナイメージを実行するとき、設定だけでプロパティファイルをカスタマイズする方法は不明
  • コンテナイメージ実行時に、ボリュームマウントして任意のファイルを読ませることはできる

2. java.security.Security.setProperty() で指定

Spring Bootアプリはmainメソッドを作ることが多いと思うので、リンク先の記事のようにInetAddressCachePolicyの読み込み順を意識せずに対応できると思う。

毎回書かないで済むようBuildpackが対応して欲しい。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    static {
        try {
            var cacheTTL = System.getProperty("networkaddress.cache.ttl", "1");
            var cacheNegativeTTL = System.getProperty("networkaddress.cache.negative.ttl", "1");
            java.security.Security.setProperty("networkaddress.cache.ttl", cacheTTL);
            java.security.Security.setProperty("networkaddress.cache.negative.ttl", cacheNegativeTTL);
        } catch (Exception ignore) {
            // XXX
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}