Skip to main content

在TestContainers中实现Docker registry认证

· 2 min read
orange
programmer on jvm platform

docker registry配置了认证后, 项目中CICD中运行的test case失败, 错误日志如下

Caused by: org.testcontainers.containers.ContainerFetchException: Can't get Docker image: RemoteDockerImage(imageName=hub.fastonetech.com/cce/fastone-auditing:latest, imagePullPolicy=AlwaysPullPolicy(), imageNameSubstitutor=org.testcontainers.utility.ImageNameSubstitutor$LogWrappedImageNameSubstitutor@3b68a50c)
at app//org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1371)
at app//org.testcontainers.containers.GenericContainer.logger(GenericContainer.java:651)
at app//org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:331)
... 153 more
Caused by: org.testcontainers.containers.ContainerFetchException: Failed to pull image: hub.fastonetech.com/cce/fastone-auditing:latest
at app//org.testcontainers.images.RemoteDockerImage.resolve(RemoteDockerImage.java:119)
at app//org.testcontainers.images.RemoteDockerImage.resolve(RemoteDockerImage.java:28)
at app//org.testcontainers.utility.LazyFuture.getResolvedValue(LazyFuture.java:17)
at app//org.testcontainers.utility.LazyFuture.get(LazyFuture.java:39)
at app//org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1369)
... 155 more
Caused by: com.github.dockerjava.api.exception.InternalServerErrorException: Status 500: {"message":"unauthorized: unauthorized to access repository: cce/fastone-auditing, action: pull: unauthorized to access repository: cce/fastone-auditing, action: pull"}

at app//org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.execute(DefaultInvocationBuilder.java:247)
at app//org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.lambda$executeAndStream$1(DefaultInvocationBuilder.java:269)
at java.base@17.0.1/java.lang.Thread.run(Thread.java:833)

解决方案

根据上述日志中的关键信息得出由于docker registry未认证导致该问题的出现

Caused by: com.github.dockerjava.api.exception.InternalServerErrorException: Status 500: {"message":"unauthorized: unauthorized to access repository: cce/fastone-auditing, action: pull: unauthorized to access repository: cce/fastone-auditing, action: pull"}

执行docker login命令,然后从~/.docker/config.json中获取认证信息作为DOCKER_AUTH_CONFIG环境变量的值

docker login -u <username> -p <password> <registry>
DOCKER_AUTH_CONFIG=""
DOCKER_AUTH_CONFIG=$(cat ~/.docker/config.json)
export DOCKER_AUTH_CONFIG

参考