or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

containers.mddocker-compose.mdimages-files.mdindex.mdjunit-integration.mdnetworks.mdoutput-logging.mdtestcontainers-utility.mdwait-strategies.md

containers.mddocs/

0

# Container Management

1

2

Core container lifecycle management providing full Docker container control including startup, configuration, networking, and cleanup through the GenericContainer class and related interfaces.

3

4

## Capabilities

5

6

### GenericContainer

7

8

The primary container class providing comprehensive Docker container lifecycle management with fluent configuration API.

9

10

```java { .api }

11

/**

12

* Generic container implementation providing full Docker lifecycle management

13

* @param <SELF> Self-referencing generic type for fluent API

14

*/

15

public class GenericContainer<SELF extends GenericContainer<SELF>> implements Container<SELF> {

16

17

/** Create container with specified Docker image */

18

public GenericContainer(DockerImageName dockerImageName);

19

public GenericContainer(String dockerImageName);

20

public GenericContainer(Future<String> image);

21

22

/** Configure exposed ports */

23

public SELF withExposedPorts(Integer... ports);

24

public List<Integer> getExposedPorts();

25

26

/** Configure environment variables */

27

public SELF withEnv(String key, String value);

28

public SELF withEnv(Map<String, String> env);

29

public Map<String, String> getEnvMap();

30

31

/** Configure container command */

32

public SELF withCommand(String... commandParts);

33

public SELF withCommand(List<String> commandParts);

34

35

/** Configure networking */

36

public SELF withNetworkMode(String networkMode);

37

public SELF withNetwork(Network network);

38

public SELF withNetworkAliases(String... aliases);

39

40

/** Configure volumes and file mounting */

41

public SELF withFileSystemBind(String hostPath, String containerPath);

42

public SELF withFileSystemBind(String hostPath, String containerPath, BindMode mode);

43

public SELF withVolumesFrom(Container container, BindMode mode);

44

public SELF withCopyFileToContainer(MountableFile mountableFile, String containerPath);

45

46

/** Configure container lifecycle */

47

public SELF waitingFor(WaitStrategy waitStrategy);

48

public SELF withStartupTimeout(Duration startupTimeout);

49

public SELF withStartupCheckStrategy(StartupCheckStrategy strategy);

50

public SELF withMinimumRunningDuration(Duration minimumRunningDuration);

51

public SELF withStartupAttempts(int attempts);

52

53

/** Configure logging */

54

public SELF withLogConsumer(Consumer<OutputFrame> logConsumer);

55

56

/** Configure resource limits */

57

public SELF withSharedMemorySize(Long bytes);

58

public SELF withTmpFs(Map<String, String> mapping);

59

60

/** Configure security and privileges */

61

public SELF withPrivilegedMode(boolean mode);

62

public SELF withUser(String user);

63

public SELF withWorkingDirectory(String workDir);

64

65

/** Configure labels and metadata */

66

public SELF withLabel(String key, String value);

67

public SELF withLabels(Map<String, String> labels);

68

69

/** Configure image handling */

70

public SELF withImagePullPolicy(ImagePullPolicy imagePullPolicy);

71

72

/** Configure reuse */

73

public SELF withReuse(boolean reusable);

74

75

/** Configure host access */

76

public SELF withAccessToHost(boolean accessToHost);

77

public SELF withExtraHost(String hostname, String ipAddress);

78

79

/** Configure advanced Docker options */

80

public SELF withCreateContainerCmdModifier(Consumer<CreateContainerCmd> modifier);

81

82

/** Configure classpath resource mounting */

83

public SELF withClasspathResourceMapping(String resourcePath, String containerPath, BindMode mode);

84

public SELF withCopyToContainer(Transferable transferable, String containerPath);

85

86

/** Lifecycle management */

87

public void start();

88

public void stop();

89

public boolean isRunning();

90

91

/** Access container information */

92

public String getHost();

93

public Integer getMappedPort(int originalPort);

94

public Integer getFirstMappedPort();

95

public String getContainerId();

96

public DockerImageName getDockerImageName();

97

public String getLogs();

98

public String getLogs(OutputFrame.OutputType... types);

99

public boolean isCreated();

100

public boolean isHealthy();

101

public InspectContainerResponse getContainerInfo();

102

public WaitStrategy getWaitStrategy();

103

104

/** Execute commands in container */

105

public Container.ExecResult execInContainer(String... command) throws UnsupportedOperationException, IOException, InterruptedException;

106

public Container.ExecResult execInContainer(Charset outputCharset, String... command) throws UnsupportedOperationException, IOException, InterruptedException;

107

108

/** File operations */

109

public void copyFileToContainer(MountableFile mountableFile, String containerPath);

110

public void copyFileFromContainer(String containerPath, String destinationPath);

111

}

112

```

113

114

**Usage Examples:**

115

116

```java

117

import org.testcontainers.containers.GenericContainer;

118

import org.testcontainers.containers.wait.strategy.Wait;

119

import org.testcontainers.utility.DockerImageName;

120

121

// Basic container setup

122

GenericContainer<?> nginx = new GenericContainer<>(DockerImageName.parse("nginx:alpine"))

123

.withExposedPorts(80)

124

.waitingFor(Wait.forHttp("/"));

125

126

// Container with environment variables

127

GenericContainer<?> postgres = new GenericContainer<>("postgres:13")

128

.withExposedPorts(5432)

129

.withEnv("POSTGRES_DB", "testdb")

130

.withEnv("POSTGRES_USER", "testuser")

131

.withEnv("POSTGRES_PASSWORD", "testpass")

132

.waitingFor(Wait.forListeningPort());

133

134

// Container with volume mounting

135

GenericContainer<?> app = new GenericContainer<>("myapp:latest")

136

.withExposedPorts(8080)

137

.withFileSystemBind("/host/path/config", "/app/config", BindMode.READ_ONLY)

138

.withCopyFileToContainer(MountableFile.forClasspathResource("app.properties"), "/app/app.properties");

139

```

140

141

### Container Interface

142

143

Core container contract defining the fluent API for all container implementations.

144

145

```java { .api }

146

/**

147

* Core container interface defining fluent configuration API

148

* @param <SELF> Self-referencing generic type for method chaining

149

*/

150

public interface Container<SELF extends Container<SELF>> extends AutoCloseable {

151

152

/** Port configuration */

153

SELF withExposedPorts(Integer... ports);

154

List<Integer> getExposedPorts();

155

156

/** Environment configuration */

157

SELF withEnv(String key, String value);

158

SELF withEnv(Map<String, String> env);

159

160

/** Command configuration */

161

SELF withCommand(String... commandParts);

162

SELF withCommand(List<String> commandParts);

163

164

/** Network configuration */

165

SELF withNetworkMode(String networkMode);

166

SELF withNetwork(Network network);

167

SELF withNetworkAliases(String... aliases);

168

169

/** Wait strategy configuration */

170

SELF waitingFor(WaitStrategy waitStrategy);

171

172

/** Lifecycle methods */

173

void start();

174

void stop();

175

void close(); // From AutoCloseable

176

177

/** Container information access */

178

String getHost();

179

Integer getMappedPort(int originalPort);

180

String getContainerId();

181

boolean isRunning();

182

String getLogs();

183

}

184

```

185

186

### Container State

187

188

Interface providing access to container runtime state information.

189

190

```java { .api }

191

/**

192

* Provides access to container runtime state and connection information

193

*/

194

public interface ContainerState {

195

/** Get the Docker container ID */

196

String getContainerId();

197

198

/** Get the host where the container is running */

199

String getHost();

200

201

/** Get the host port mapped to the specified container port */

202

Integer getMappedPort(int originalPort);

203

204

/** Get all container logs */

205

String getLogs();

206

207

/** Get logs of specific output types */

208

String getLogs(OutputFrame.OutputType... types);

209

210

/** Check if container is currently running */

211

boolean isRunning();

212

213

/** Get container IP address within Docker network */

214

String getNetworkAddress(String networkAlias);

215

216

/** Get all exposed ports */

217

List<Integer> getExposedPorts();

218

219

/** Get environment variables */

220

Map<String, String> getEnvMap();

221

}

222

```

223

224

### Execution Results

225

226

Results from executing commands within containers.

227

228

```java { .api }

229

/**

230

* Result of executing a command within a container

231

*/

232

public static class ExecResult {

233

/** Exit code of the executed command */

234

public int getExitCode();

235

236

/** Standard output from the command */

237

public String getStdout();

238

239

/** Standard error from the command */

240

public String getStderr();

241

242

/** Combined stdout and stderr */

243

public String toString();

244

}

245

```

246

247

### Fixed Host Port Container

248

249

Specialized container allowing fixed host port binding instead of random port assignment.

250

251

```java { .api }

252

/**

253

* Container that binds to fixed host ports instead of random ports

254

* @param <SELF> Self-referencing generic type for fluent API

255

*/

256

@Deprecated

257

public class FixedHostPortGenericContainer<SELF extends FixedHostPortGenericContainer<SELF>>

258

extends GenericContainer<SELF> {

259

260

public FixedHostPortGenericContainer(String dockerImageName);

261

262

/** Bind container port to specific host port */

263

public SELF withFixedExposedPort(int hostPort, int containerPort);

264

public SELF withFixedExposedPort(int hostPort, int containerPort, InternetProtocol protocol);

265

}

266

```

267

268

### Specialized Containers

269

270

Additional container implementations for specific use cases.

271

272

```java { .api }

273

/**

274

* Container for SOCAT proxy functionality

275

*/

276

public class SocatContainer extends GenericContainer<SocatContainer> {

277

public SocatContainer();

278

public SocatContainer withTarget(int port, String host);

279

public SocatContainer withTarget(int port, String host, InternetProtocol protocol);

280

}

281

282

/**

283

* Container providing VNC recording capabilities

284

*/

285

public class VncRecordingContainer extends GenericContainer<VncRecordingContainer> {

286

public VncRecordingContainer(Network network);

287

public File saveRecordingToFile(File file);

288

}

289

```

290

291

### Container Traits

292

293

Behavioral interfaces that can be mixed in to provide additional capabilities.

294

295

```java { .api }

296

/**

297

* Marker interface for containers that can be linked to other containers

298

*/

299

public interface LinkableContainer {

300

String getNetworkAlias();

301

}

302

303

/**

304

* Interface for containers providing VNC access

305

*/

306

public interface VncService {

307

String getVncAddress();

308

int getVncPort();

309

}

310

```

311

312

## Type Definitions

313

314

```java { .api }

315

/**

316

* Volume binding modes for file system mounts

317

*/

318

public enum BindMode {

319

/** Read-only access to mounted volume */

320

READ_ONLY,

321

/** Read-write access to mounted volume */

322

READ_WRITE

323

}

324

325

/**

326

* Internet protocol specification for port binding

327

*/

328

public enum InternetProtocol {

329

TCP, UDP

330

}

331

332

/**

333

* SELinux context options for volume mounting

334

*/

335

public enum SelinuxContext {

336

SHARED, PRIVATE, SINGLE

337

}

338

```