Spring Boot测试中用TestContainers运行Docker-Compose遇问题求解
解决Testcontainers运行Samba DC Docker Compose的问题
1. 修复网络连接错误
你遇到的Cannot link to ... as it does not belong to the default network错误,是因为Testcontainers默认创建的网络与容器所属网络不匹配。显式在docker-compose.yml中定义自定义网络即可解决:
修改后的docker-compose.yml:
version: '3.4' services: samba: image: instantlinux/samba-dc:latest hostname: my.org environment: DOMAIN_ACTION: provision REALM: my.org volumes: - etc:/etc/samba - lib:/var/lib/samba ports: - "389:389" secrets: - samba-admin-password networks: - test-network # 让服务加入自定义网络 volumes: etc: lib: secrets: samba-admin-password: file: secrets.yaml networks: test-network: # 显式定义网络 driver: bridge
2. 正确获取Testcontainers映射的端口
Testcontainers会自动重新映射端口(避免本地端口冲突),不会使用你compose中指定的389:389固定映射,需要通过API获取实际映射的端口:
修改测试类:
@Testcontainers @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") class IntegrationTestBase { @Container val ldapContainer = DockerComposeContainer(File("C:\\path\\to\\compose\\docker-compose.yml")) .withExposedService("samba", 389) .waitingFor("samba", Wait.forListeningPort()) // 等待服务端口就绪 .waitingFor("samba", Wait.forLogMessage(".*provision complete.*", 1)) // 等待Samba初始化完成 // 获取实际映射的端口 val sambaLdapPort: Int get() = ldapContainer.getServicePort("samba", 389) // 测试示例 @Test fun testLdapConnection() { val ldapUrl = "ldap://localhost:$sambaLdapPort" // 编写LDAP连接测试逻辑 } }
3. 确保Secrets文件路径正确
Testcontainers运行时的工作目录可能与本地执行docker-compose up的目录不同,建议将secrets.yaml放到测试资源目录(如src/test/resources),然后修改compose中的路径:
secrets: samba-admin-password: file: src/test/resources/secrets.yaml
4. 补充必要依赖
使用DockerComposeContainer需要添加Testcontainers的compose模块依赖:
testImplementation("org.testcontainers:compose")
内容的提问来源于stack exchange,提问作者gstackoverflow
相关产品推荐
相关产品推荐

