
docker-testcontainers
Guidance for Testcontainers — running Docker containers in automated integration tests. Covers Java (@Testcontainers, @Container, PostgreSQL/Redis/Kafka/Elasticsearch), Python (testcontainers-python with pytest), container lifecycle management (singleton, reuse), CI/CD integration (Docker-in-Docker, Ryuk), Testcontainer best practices, and database migration testing. Use when the user asks about testcontainers, integration testing with Docker, database testing, Java testcontainers, Python testcontainers, or needs to test with real Docker services. 使用场景:testcontainers、集成测试、docker 测试、数据库测试、Java Testcontainers、Python Testcontainers.
- Installs
- 106
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/full-stack-skills/docker-skills --skill docker-testcontainers- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads docker-testcontainers automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Docker Testcontainers — 集成测试容器
Guidance for running Docker containers in automated tests with Testcontainers.
When to Use
ALWAYS use this skill when the user mentions:
- "testcontainers", "Testcontainer", "测试容器"
- "集成测试", "docker 测试"
- "数据库测试", "PostgreSQL test", "MySQL test"
- "Java Testcontainers", "Python Testcontainers"
- "测试环境搭建"
Java — Testcontainers
PostgreSQL Example
@Testcontainers
@SpringBootTest
class OrderRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");
@DynamicPropertySource
static void configure(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Test
void shouldSaveAndFindOrder() {
Order saved = repository.save(new Order(...));
assertThat(repository.findById(saved.getId())).isPresent();
}
}
Redis Example
@Container
static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine")
.withExposedPorts(6379);
// Get connection string
String redisUrl = "redis://" + redis.getHost() + ":" + redis.getMappedPort(6379);
Kafka Example
@Container
static KafkaContainer kafka = new KafkaContainer(
DockerImageName.parse("confluentinc/cp-kafka:7.6.0"));
String bootstrapServers = kafka.getBootstrapServers();
Python — testcontainers-python
import pytest
from testcontainers.postgres import PostgresContainer
from testcontainers.redis import RedisContainer
@pytest.fixture(scope="module")
def postgres():
with PostgresContainer("postgres:16-alpine") as pg:
yield pg.get_connection_url()
def test_database_connection(postgres):
import psycopg2
conn = psycopg2.connect(postgres)
assert conn.status == psycopg2.STATUS_READY
Container Lifecycle
// Singleton: one container for all tests
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
// Per-test: new container for each test
@Test
void test() {
try (var redis = new GenericContainer<>("redis:7")) {
redis.start();
// test...
} // auto-closed by try-with-resources
}
CI/CD Configuration
# GitHub Actions — DinD (Docker-in-Docker)
jobs:
test:
runs-on: ubuntu-latest
services:
docker:
image: docker:27-dind
options: --privileged
steps:
- uses: actions/checkout@v4
- run: ./gradlew test
Workflow — 推荐集成流程
Step 1: 添加依赖: testImplementation 'org.testcontainers:testcontainers:1.20.6'
Step 2: 定义容器: @Container static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
Step 3: 注入配置: @DynamicPropertySource 将容器连接信息注入 Spring 配置
Step 4: 编写测试: @Test void shouldSaveAndFind() 正常业务测试
Step 5: CI 加速: 启用 withReuse(true) + GHA cache
Gotchas — Common Pitfalls
- CI slow startup: Container images need to be pulled in CI. → Recovery: Pre-warm by adding
docker pull postgres:16-alpinebefore test step; enablewithReuse(true)in.testcontainers.properties. - Port conflicts in CI: Testcontainers picks random ports — no conflicts. But hardcoded ports in tests will fail. → Recovery: Always use
container.getMappedPort(5432)instead of hardcoding port numbers. - Resource cleanup: Ryuk auto-removes containers. In CI, ensure DinD or socket access. → Recovery: If
TESTCONTAINERS_RYUK_DISABLED=true, add@AfterAllcleanup; check Docker socket is mounted in CI. - Static vs instance containers: Static
@Containerfields share ONE container across the class. Instance fields create per-test containers. → Recovery: Use static for databases (shared state OK); use instance for isolation-critical tests; check@TestInstance(TestInstance.Lifecycle.PER_CLASS)for JUnit 5.
Boundary — 能力边界(适用与不适用场景)
| 分类 | 场景 | 说明 |
|---|---|---|
| ✅ 能做 | Java/Python 集成测试 | PostgreSQL/MySQL/Redis/Kafka 等容器化数据库测试 |
| ✅ 能做 | Spring Boot 测试 | @Testcontainers + @DynamicPropertySource 自动注入 |
| ✅ 能做 | CI 集成 | GitHub Actions/Jenkins 中自动启动/清理 |
| ⚠️ 需条件 | 跨 JVM 复用 | 需配置 testcontainers.reuse.enable=true |
| ⚠️ 需条件 | 非 Java 语言测试 | 使用各语言对应 Testcontainers 库 |
| ❌ 超范围 | 手动测试/调试 | 使用 docker-run |
| ❌ 超范围 | 生产数据库测试 | 连接生产实例而非容器 |
| ❌ 超范围 | 性能/压测 | 专用工具(JMeter/K6) |
When NOT to Use This Skill
| ❌ Skip | ✅ Use Instead |
|---|---|
| Manual testing | docker-run |
| Production database testing | docker-storage + real instance |
| Mock testing | Use Mockito/unittest.mock |
| Docker basics | docker-basics |
Security & Stability
- Testcontainers use random ports — no port conflicts with running services.
- Containers are automatically cleaned up by Ryuk after test completion.
- Never use Testcontainers in production code — test scope only.
- Use
withReuse(true)for local development to speed up tests (container survives between runs).
📚 官方文档参考
| 文档 | 地址 |
|---|---|
| Testcontainers 概述 | https://docs.docker.com/testcontainers/ |
| Testcontainers for Java | https://java.testcontainers.org/ |
| Testcontainers Cloud | https://testcontainers.com/cloud/ |
| Spring Boot 集成 | https://java.testcontainers.org/modules/spring-boot/ |
| CI 配置 | https://java.testcontainers.org/supported_docker_environment/continuous_integration/ |
🧭 Docker Skills Journey
📍 You are here:
docker-testcontainers— 测试容器
← Prev: docker-troubleshooting — Problem debugging
→ Next: docker-ai-ml — AI/ML workloads
FAQ
Q1: 如何快速上手此技能? A: 参考上方的快速开始章节,按步骤操作即可。
Q2: 遇到版本不兼容问题怎么办? A: 检查依赖版本,使用 lock 文件锁定,参考常见陷阱章节。
Q3: 如何在生产环境使用? A: 参考最佳实践章节,确保配置正确,做好监控和日志。
Q4: 性能如何优化? A: 参考性能优化相关文档,使用缓存、索引等手段。
Q5: 如何贡献或反馈问题? A: 在 GitHub 仓库提交 Issue 或 Pull Request。
Q6: 是否支持中文? A: 支持中文文档和中文注释,详见国内适配章节。
FAQ
What does the docker-testcontainers skill do?
Guidance for Testcontainers — running Docker containers in automated integration tests. Covers Java (@Testcontainers, @Container, PostgreSQL/Redis/Kafka/Elasticsearch), Python (testcontainers-python with pytest), container lifecycle management (singleton, reuse), CI/CD integration (Docker-in-Docker, Ryuk), Testcontainer best practices, and database migration testing. Use when the user asks about testcontainers, integration testing with Docker, database testing, Java testcontainers, Python testcontainers, or needs to test with real Docker services. 使用场景:testcontainers、集成测试、docker 测试、数据库测试、Java Testcontainers、Python Testcontainers.
How do I install docker-testcontainers?
Run npx skills add https://github.com/full-stack-skills/docker-skills --skill docker-testcontainers in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/docker-testcontainers/ (personal) or .claude/skills/docker-testcontainers/ (project).
Which AI agents can use docker-testcontainers?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is docker-testcontainers safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains docker-testcontainers?
It is published by full-stack-skills in full-stack-skills/docker-skills. It has 106 recorded installs.
More from full-stack-skills/docker-skills
docker-compose
full-stack-skills/docker-skills
Expert guidance for Docker Compose — writing production-grade compose.yml files for multi-container applications. Covers complete Compose file syntax (services, networks, volumes, secrets, configs, profiles, extends, include), service configuration (image/build, ports, environment, envfile, dependson with health checks, deploy resources, restart policies), networking in Compose (default networks, custom networks, internal networks), volume management, environment variable strategies (.env vs environment vs envfile), override files for multi-environment, profiles for optional services, and migration to Kubernetes with kompose. Use when the user asks about docker compose, docker-compose.yml, compose file, multi-container, service orchestration, compose configuration, or needs to write/modify a compose file. 使用场景:docker compose、docker-compose.yml、compose 文件、多容器、服务编排、compose 配置、dependson、profiles.
docker-dockerfile
full-stack-skills/docker-skills
Open the skill to read its SKILL.md instructions.
docker-security
full-stack-skills/docker-skills
Guidance for Docker security hardening across the full lifecycle — image security (minimal base images, non-root users, pinned versions), runtime security (seccomp/AppArmor/SELinux, capabilities, read-only rootfs, no-new-privileges), secrets management (BuildKit secrets, Docker secrets in Swarm), Docker Bench Security auditing, CIS compliance checklist, and supply-chain security (image signing, content trust, SBOM). Use when the user asks about Docker security, image hardening, non-root containers, seccomp, AppArmor, Docker Bench, secrets management, or securing containers. 使用场景:docker 安全、镜像安全、非root运行、seccomp、AppArmor、security、Docker Bench、secret管理.
docker-troubleshooting
full-stack-skills/docker-skills
Open the skill to read its SKILL.md instructions.
docker-networking
full-stack-skills/docker-skills
Open the skill to read its SKILL.md instructions.
docker-basics
full-stack-skills/docker-skills
Open the skill to read its SKILL.md instructions.
Popular devops & cloud skills
microsoft-foundry
microsoft/azure-skills
Build, deploy, evaluate, optimize, fine-tune, and manage Microsoft Foundry agents, models, and resources end to end. USE FOR: foundry, azd ai agent, azd provision/deploy, hosted agent scaffold/develop/run/deploy/troubleshoot, prompt agent create, managed harness agent create, GitHub Copilot harness agent, create agent, update agent, add tool to agent, invoke agent, agent insights, evaluate agent, batch eval, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, Agent Optimizer scaffold, dataset curation from traces, deploy model, model fine-tuning (SFT/DPO/RFT), Foundry project, RBAC, role assignment, permissions, quota, capacity, region, deployment failure, AI Services, create Foundry resource, knowledge index, customize deployment, onboard, availability, training-data, grader, distillation, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure
azure-diagnostics
microsoft/azure-skills
Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, container app 503 or target port mismatch, troubleshoot functions, function telemetry missing or stopped after a config/connection-string change, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, lock renewal during long-running processing, service bus dead letter.
azure-prepare
microsoft/azure-skills
Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure.
azure-ai
microsoft/azure-skills
Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech.
azure-deploy
microsoft/azure-skills
Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: "run azd up", "run azd deploy", "execute deployment", "push to production", "push to cloud", "go live", "ship it", "bicep deploy", "terraform apply", "publish to Azure", "launch on Azure". DO NOT USE WHEN: "create and deploy", "build and deploy", "create a new app", "set up infrastructure", "create and deploy to Azure using Terraform" — use azure-prepare for these.
azure-validate
microsoft/azure-skills
Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment.