or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cache-messaging.mdcloud-services.mdcompose.mdcore-containers.mddatabase-containers.mdindex.mdsearch-analytics.mdwaiting-strategies.mdweb-testing.md

core-containers.mddocs/

0

# Core Container Management

1

2

The fundamental Docker container lifecycle management capabilities that form the foundation of all testcontainers functionality. The DockerContainer class provides comprehensive configuration options, networking, volume mounting, and environment setup through a fluent API.

3

4

## Capabilities

5

6

### Basic Container Operations

7

8

Core container lifecycle management including creation, startup, shutdown, and resource cleanup with automatic or manual control.

9

10

```python { .api }

11

class DockerContainer:

12

def __init__(

13

self,

14

image: str,

15

docker_client_kw: Optional[dict[str, Any]] = None,

16

command: Optional[str] = None,

17

env: Optional[dict[str, str]] = None,

18

name: Optional[str] = None,

19

ports: Optional[list[int]] = None,

20

volumes: Optional[list[tuple[str, str, str]]] = None,

21

network: Optional[Network] = None,

22

network_aliases: Optional[list[str]] = None,

23

**kwargs: Any

24

):

25

"""

26

Initialize a Docker container.

27

28

Args:

29

image: Docker image name and tag

30

docker_client_kw: Docker client configuration

31

command: Container command to execute

32

env: Environment variables dictionary

33

name: Container name

34

ports: Ports to expose

35

volumes: Volume mounts as (host_path, container_path, mode) tuples

36

network: Network to connect to

37

network_aliases: Network aliases for the container

38

**kwargs: Additional Docker container options

39

"""

40

41

def start(self) -> "DockerContainer":

42

"""

43

Start the container.

44

45

Returns:

46

Self for method chaining

47

"""

48

49

def stop(self, force: bool = True, delete_volume: bool = True) -> None:

50

"""

51

Stop and remove the container.

52

53

Args:

54

force: Force container removal

55

delete_volume: Delete associated volumes

56

"""

57

58

def __enter__(self) -> "DockerContainer":

59

"""Context manager entry - starts container."""

60

61

def __exit__(self, exc_type, exc_val, exc_tb) -> None:

62

"""Context manager exit - stops container."""

63

```

64

65

### Container Configuration

66

67

Fluent API for configuring container properties including environment variables, ports, volumes, networking, and Docker-specific options.

68

69

```python { .api }

70

def with_env(self, key: str, value: str) -> "DockerContainer":

71

"""

72

Add environment variable.

73

74

Args:

75

key: Environment variable name

76

value: Environment variable value

77

78

Returns:

79

Self for method chaining

80

"""

81

82

def with_envs(self, **variables: str) -> "DockerContainer":

83

"""

84

Add multiple environment variables.

85

86

Args:

87

**variables: Environment variables as keyword arguments

88

89

Returns:

90

Self for method chaining

91

"""

92

93

def with_env_file(self, env_file: Union[str, PathLike]) -> "DockerContainer":

94

"""

95

Load environment variables from file.

96

97

Args:

98

env_file: Path to environment file

99

100

Returns:

101

Self for method chaining

102

"""

103

104

def with_command(self, command: Union[str, list[str]]) -> "DockerContainer":

105

"""

106

Set container command.

107

108

Args:

109

command: Command to execute in container

110

111

Returns:

112

Self for method chaining

113

"""

114

115

def with_name(self, name: str) -> "DockerContainer":

116

"""

117

Set container name.

118

119

Args:

120

name: Container name

121

122

Returns:

123

Self for method chaining

124

"""

125

126

def with_kwargs(self, **kwargs: Any) -> "DockerContainer":

127

"""

128

Add Docker container creation arguments.

129

130

Args:

131

**kwargs: Docker client container creation arguments

132

133

Returns:

134

Self for method chaining

135

"""

136

137

def with_user(self, user: str) -> "DockerContainer":

138

"""

139

Set container user.

140

141

Args:

142

user: User to run container as (user or user:group)

143

144

Returns:

145

Self for method chaining

146

"""

147

148

def with_working_directory(self, working_directory: str) -> "DockerContainer":

149

"""

150

Set container working directory.

151

152

Args:

153

working_directory: Working directory path

154

155

Returns:

156

Self for method chaining

157

"""

158

```

159

160

### Port Management

161

162

Configure port exposure and binding for container network access, supporting both automatic port assignment and explicit host port binding.

163

164

```python { .api }

165

def with_exposed_ports(self, *ports: int) -> "DockerContainer":

166

"""

167

Expose ports without binding to host ports.

168

169

Args:

170

*ports: Port numbers to expose

171

172

Returns:

173

Self for method chaining

174

"""

175

176

def with_bind_ports(self, container: int, host: Optional[int] = None) -> "DockerContainer":

177

"""

178

Bind container port to specific host port.

179

180

Args:

181

container: Container port number

182

host: Host port number (random if None)

183

184

Returns:

185

Self for method chaining

186

"""

187

188

def get_exposed_port(self, port: int) -> str:

189

"""

190

Get the host port mapped to container port.

191

192

Args:

193

port: Container port number

194

195

Returns:

196

Host port number as string

197

198

Raises:

199

NoSuchPortExposed: If port not exposed

200

"""

201

202

def get_container_host_ip(self) -> str:

203

"""

204

Get the IP address to connect to the container.

205

206

Returns:

207

IP address string

208

"""

209

```

210

211

### Volume Management

212

213

Mount host directories and files into containers with configurable access modes and path mapping.

214

215

```python { .api }

216

def with_volume_mapping(self, host: str, container: str, mode: str = "ro") -> "DockerContainer":

217

"""

218

Mount host path into container.

219

220

Args:

221

host: Host filesystem path

222

container: Container filesystem path

223

mode: Mount mode ('ro', 'rw', 'z', 'Z')

224

225

Returns:

226

Self for method chaining

227

"""

228

```

229

230

### Network Configuration

231

232

Connect containers to Docker networks with custom aliases and network-specific configuration.

233

234

```python { .api }

235

def with_network(self, network: Network) -> "DockerContainer":

236

"""

237

Connect container to network.

238

239

Args:

240

network: Network instance to connect to

241

242

Returns:

243

Self for method chaining

244

"""

245

246

def with_network_aliases(self, *aliases: str) -> "DockerContainer":

247

"""

248

Set network aliases for container.

249

250

Args:

251

*aliases: Network alias names

252

253

Returns:

254

Self for method chaining

255

"""

256

```

257

258

### Container Inspection and Control

259

260

Access container runtime information, execute commands, and retrieve logs for debugging and integration.

261

262

```python { .api }

263

def get_wrapped_container(self) -> "Container":

264

"""

265

Get the underlying Docker container object.

266

267

Returns:

268

Docker container instance

269

"""

270

271

def get_docker_client(self) -> DockerClient:

272

"""

273

Get the Docker client instance.

274

275

Returns:

276

Docker client

277

"""

278

279

def get_logs(self) -> tuple[bytes, bytes]:

280

"""

281

Get container logs.

282

283

Returns:

284

Tuple of (stdout, stderr) as bytes

285

"""

286

287

def exec(self, command: Union[str, list[str]]) -> ExecResult:

288

"""

289

Execute command in running container.

290

291

Args:

292

command: Command to execute

293

294

Returns:

295

Execution result with exit_code and output

296

"""

297

```

298

299

### Platform Compatibility

300

301

Handle cross-platform differences and architecture emulation for consistent behavior across development environments.

302

303

```python { .api }

304

def maybe_emulate_amd64(self) -> "DockerContainer":

305

"""

306

Enable AMD64 emulation on ARM platforms.

307

308

Returns:

309

Self for method chaining

310

"""

311

```

312

313

## Usage Examples

314

315

### Basic Container Usage

316

317

```python

318

from testcontainers.core.container import DockerContainer

319

320

# Simple container with automatic cleanup

321

with DockerContainer("nginx:alpine") as container:

322

container.with_exposed_ports(80)

323

host_port = container.get_exposed_port(80)

324

host_ip = container.get_container_host_ip()

325

print(f"Nginx available at http://{host_ip}:{host_port}")

326

```

327

328

### Advanced Configuration

329

330

```python

331

from testcontainers.core.container import DockerContainer

332

from testcontainers.core.network import Network

333

334

# Create custom network

335

with Network() as network:

336

# Configure container with multiple options

337

container = DockerContainer("postgres:13") \

338

.with_env("POSTGRES_DB", "testdb") \

339

.with_env("POSTGRES_USER", "testuser") \

340

.with_env("POSTGRES_PASSWORD", "testpass") \

341

.with_exposed_ports(5432) \

342

.with_volume_mapping("./data", "/var/lib/postgresql/data", "rw") \

343

.with_network(network) \

344

.with_network_aliases("database", "db") \

345

.with_name("test-postgres")

346

347

with container:

348

# Container is now running with full configuration

349

connection_host = container.get_container_host_ip()

350

connection_port = container.get_exposed_port(5432)

351

```

352

353

### Command Execution

354

355

```python

356

with DockerContainer("ubuntu:20.04") as container:

357

container.with_command("sleep 30")

358

359

# Execute commands in running container

360

result = container.exec("ls -la /")

361

print(f"Exit code: {result.exit_code}")

362

print(f"Output: {result.output.decode()}")

363

364

# Get container logs

365

stdout, stderr = container.get_logs()

366

print(f"Container output: {stdout.decode()}")

367

```

368

369

## Types

370

371

```python { .api }

372

class Mount(TypedDict):

373

bind: str # Container path

374

mode: str # Mount mode ('ro', 'rw', etc.)

375

376

class Network:

377

def __init__(

378

self,

379

docker_client_kw: Optional[dict] = None,

380

docker_network_kw: Optional[dict] = None

381

): ...

382

383

def create(self) -> "Network": ...

384

def remove(self) -> None: ...

385

def connect(self, container_id: str, network_aliases: Optional[list[str]] = None) -> None: ...

386

387

@property

388

def name(self) -> str: ...

389

390

@property

391

def id(self) -> str: ...

392

```