Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/features/containers.md
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,9 @@ const container2 = await new GenericContainer("alpine")
expect(container1.getId()).toBe(container2.getId());
```

The configuration includes the network and network aliases. A container started on a newly created `Network` is not re-used, as every new network has a different name. Re-used containers are not removed when the session ends, so each run then leaves another container running. To re-use a container on a network, use a network with a fixed name (`withNetworkMode`).
Files, directories and content copied into the container are compared by their content, except readable streams and archives, which are compared by their target only.

You can also re-use stopped but not removed containers.

```js
Expand Down
4 changes: 2 additions & 2 deletions packages/testcontainers/src/common/hash.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import crypto from "node:crypto";

export function hash(str: string): string {
return crypto.createHash("sha256").update(str).digest("hex");
export function hash(data: string | Buffer): string {
return crypto.createHash("sha256").update(data).digest("hex");
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
cristianrgreco marked this conversation as resolved.
Dismissed
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { promises as fs } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { Readable } from "node:stream";
import { randomUuid } from "../common/uuid";
import { Network } from "../network/network";
import type { StartedTestContainer } from "../test-container";
import { TestContainers } from "../test-containers";
import { RandomPortGenerator } from "../utils/port-generator";
import { checkContainerIsHealthy } from "../utils/test-helper";
import { GenericContainer } from "./generic-container";

Expand Down Expand Up @@ -162,6 +170,141 @@ describe("GenericContainer reuse", { concurrent: false, timeout: 180_000 }, () =
expect(container.getLabels()).toEqual(expect.objectContaining({ test: "foo" }));
});

it.each<[string, (container: GenericContainer) => GenericContainer]>([
["tmpfs", (container) => container.withTmpFs({ "/data": "rw" })],
["privileged mode", (container) => container.withPrivilegedMode()],
["extra host", (container) => container.withExtraHosts([{ host: "foo", ipAddress: "10.0.0.1" }])],
[
"bind mount",
(container) =>
container.withBindMounts([
{
source: path.resolve(__dirname, "..", "..", "fixtures", "docker", "docker", "test.txt"),
target: "/tmp/test.txt",
},
]),
],
[
"copied content",
(container) => container.withCopyContentToContainer([{ content: "second", target: "/tmp/marker.txt" }]),
],
])("should not reuse the container when the %s differs", async (_, configure) => {
const labels = { "reuse-test": randomUuid() };
await using container1 = await new GenericContainer("cristianrgreco/testcontainer:1.1.14")
.withLabels(labels)
.withExposedPorts(8080)
.withReuse()
.start();

const container2 = await configure(
new GenericContainer("cristianrgreco/testcontainer:1.1.14").withLabels(labels).withExposedPorts(8080).withReuse()
).start();
stopUnlessReused(container2, container1);

expect(container2.getId()).not.toBe(container1.getId());
});

it("should not reuse the container when the network aliases differ", async () => {
const labels = { "reuse-test": randomUuid() };
const network = await new Network().start();
onTestFinished(async () => {
await network.stop();
});
await using container1 = await new GenericContainer("cristianrgreco/testcontainer:1.1.14")
.withLabels(labels)
.withNetwork(network)
.withNetworkAliases("foo")
.withReuse()
.start();

const container2 = await new GenericContainer("cristianrgreco/testcontainer:1.1.14")
.withLabels(labels)
.withNetwork(network)
.withNetworkAliases("bar")
.withReuse()
.start();
stopUnlessReused(container2, container1);

expect(container2.getId()).not.toBe(container1.getId());
});

it("should reuse the container when the host config and copied content are the same", async () => {
const labels = { "reuse-test": randomUuid() };
const createContainer = () =>
new GenericContainer("cristianrgreco/testcontainer:1.1.14")
.withLabels(labels)
.withExposedPorts(8080)
.withTmpFs({ "/data": "rw" })
.withCopyContentToContainer([{ content: "first", target: "/tmp/marker.txt" }])
.withReuse();
await using container1 = await createContainer().start();

const container2 = await createContainer().start();
stopUnlessReused(container2, container1);

expect(container2.getId()).toBe(container1.getId());
});

it.each<[string, (container: GenericContainer, directory: string) => GenericContainer]>([
[
"file",
(container, directory) =>
container.withCopyFilesToContainer([
{ source: path.join(directory, "nested", "marker.txt"), target: "/tmp/marker.txt" },
]),
],
[
"directory",
(container, directory) =>
container.withCopyDirectoriesToContainer([{ source: directory, target: "/tmp/markers" }]),
],
])("should reuse the container only while the content of the copied %s is the same", async (_, copy) => {
const labels = { "reuse-test": randomUuid() };
const directory = await fs.mkdtemp(path.join(tmpdir(), "testcontainers-"));
const marker = path.join(directory, "nested", "marker.txt");
await fs.mkdir(path.dirname(marker));
await fs.writeFile(marker, "first");
const createContainer = () =>
copy(
new GenericContainer("cristianrgreco/testcontainer:1.1.14")
.withLabels(labels)
.withExposedPorts(8080)
.withReuse(),
directory
);

try {
await using container1 = await createContainer().start();
const container2 = await createContainer().start();
stopUnlessReused(container2, container1);
expect(container2.getId()).toBe(container1.getId());

await fs.writeFile(marker, "other");
const container3 = await createContainer().start();
stopUnlessReused(container3, container1);
expect(container3.getId()).not.toBe(container1.getId());
} finally {
await fs.rm(directory, { recursive: true, force: true });
}
});

it("should copy stream content into a reusable container and reuse it", async () => {
const labels = { "reuse-test": randomUuid() };
const createContainer = () =>
new GenericContainer("cristianrgreco/testcontainer:1.1.14")
.withLabels(labels)
.withExposedPorts(8080)
.withCopyContentToContainer([{ content: Readable.from(["first"]), target: "/tmp/marker.txt" }])
.withReuse();
await using container1 = await createContainer().start();

const container2 = await createContainer().start();
stopUnlessReused(container2, container1);

expect(container2.getId()).toBe(container1.getId());
expect((await container1.exec(["cat", "/tmp/marker.txt"])).output).toBe("first");
});

it("should not create multiple reusable containers if called in parallel", async () => {
const [container1, container2] = await Promise.all([
new GenericContainer("cristianrgreco/testcontainer:1.1.14").withExposedPorts(8080).withReuse().start(),
Expand All @@ -171,4 +314,32 @@ describe("GenericContainer reuse", { concurrent: false, timeout: 180_000 }, () =
expect(container1.getId()).toBe(container2.getId());
await container2.stop();
});

// Must run last: exposing host ports keeps the port forwarder running for the rest of the file.
describe("when host ports are exposed", () => {
it("should keep the reuse hash of a container created before host ports were exposed", async () => {
const labels = { "reuse-test": randomUuid() };
const createContainer = () =>
new GenericContainer("cristianrgreco/testcontainer:1.1.14")
.withLabels(labels)
.withExposedPorts(8080)
.withExtraHosts([{ host: "foo", ipAddress: "10.0.0.1" }])
.withReuse();
await using container1 = await createContainer().start();

await TestContainers.exposeHostPorts(await new RandomPortGenerator().generatePort());
const container2 = await createContainer().start();
stopUnlessReused(container2, container1);

expect(container2.getId()).toBe(container1.getId());
});
});
});

function stopUnlessReused(container: StartedTestContainer, reusedContainer: StartedTestContainer) {
onTestFinished(async () => {
if (container.getId() !== reusedContainer.getId()) {
await container.stop();
}
});
}
79 changes: 70 additions & 9 deletions packages/testcontainers/src/generic-container/generic-container.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { promises as fs } from "node:fs";
import path from "node:path";
import type { Readable } from "node:stream";
import archiver from "archiver";
import AsyncLock from "async-lock";
Expand Down Expand Up @@ -109,13 +110,6 @@ export class GenericContainer implements TestContainer {
await this.beforeContainerCreated();
}

if (!this.isHelperContainer() && PortForwarderInstance.isRunning()) {
const portForwarder = await PortForwarderInstance.getInstance();
this.hostConfig.ExtraHosts = [
...(this.hostConfig.ExtraHosts ?? []),
`host.testcontainers.internal:${portForwarder.getIpAddress()}`,
];
}
this.hostConfig.NetworkMode = this.networkAliases.length > 0 ? undefined : this.networkMode;

this.createOpts.Labels = { ...createLabels(), ...this.createOpts.Labels };
Expand Down Expand Up @@ -146,7 +140,7 @@ export class GenericContainer implements TestContainer {
}

private async reuseOrStartContainer(client: ContainerRuntimeClient) {
const containerHash = hash(JSON.stringify(this.createOpts));
const containerHash = await this.createContainerHash();
this.createOpts.Labels = { ...this.createOpts.Labels, [LABEL_TESTCONTAINERS_CONTAINER_HASH]: containerHash };
log.debug(`Container reuse has been enabled with hash "${containerHash}"`);

Expand All @@ -165,6 +159,38 @@ export class GenericContainer implements TestContainer {
});
}

private async createContainerHash(): Promise<string> {
return hash(
JSON.stringify({
...this.createOpts,
HostConfig: this.hostConfig,
networkMode: this.networkMode,
networkAliases: this.networkAliases,
filesToCopy: await Promise.all(
this.filesToCopy.map(async ({ source, target, mode }) => ({
target,
mode,
...(await hashCopiedFile(source)),
}))
),
directoriesToCopy: await Promise.all(
this.directoriesToCopy.map(async ({ source, target, mode }) => ({
target,
mode,
entries: await hashCopiedDirectory(source),
}))
),
contentsToCopy: this.contentsToCopy.map(({ content, target, mode }) => ({
target,
mode,
content: typeof content === "string" || Buffer.isBuffer(content) ? hash(content) : undefined,
})),
archivesToCopy: this.archivesToCopy.map(({ target }) => ({ target })),
copyToContainerOptions: this.copyToContainerOptions,
})
);
}

private async reuseContainer(client: ContainerRuntimeClient, container: Container) {
let inspectResult = await client.container.inspect(container);
if (!inspectResult.State.Running) {
Expand Down Expand Up @@ -196,7 +222,8 @@ export class GenericContainer implements TestContainer {
}

private async startContainer(client: ContainerRuntimeClient): Promise<StartedTestContainer> {
const container = await client.container.create({ ...this.createOpts, HostConfig: this.hostConfig });
const hostConfig = await this.createHostConfig();
const container = await client.container.create({ ...this.createOpts, HostConfig: hostConfig });

await this.connectContainerToNetworks(client, container);
await this.copyToCreatedContainer(client, container);
Expand Down Expand Up @@ -248,6 +275,19 @@ export class GenericContainer implements TestContainer {
return startedContainer;
}

// The port forwarder entry is added here, not to this.hostConfig, so the reuse hash does not change with its IP.
private async createHostConfig(): Promise<HostConfig> {
const hostConfig = { ...this.hostConfig };
if (!this.isHelperContainer() && PortForwarderInstance.isRunning()) {
const portForwarder = await PortForwarderInstance.getInstance();
hostConfig.ExtraHosts = [
...(hostConfig.ExtraHosts ?? []),
`host.testcontainers.internal:${portForwarder.getIpAddress()}`,
];
}
return hostConfig;
}

private async connectContainerToNetworks(client: ContainerRuntimeClient, container: Container): Promise<void> {
if (!this.isHelperContainer() && PortForwarderInstance.isRunning()) {
await this.connectContainerToPortForwarder(client, container);
Expand Down Expand Up @@ -579,3 +619,24 @@ export class GenericContainer implements TestContainer {
return this;
}
}

async function hashCopiedFile(source: string) {
const stats = await fs.stat(source);
return { fileMode: stats.mode, content: hash(await fs.readFile(source)) };
}

async function hashCopiedDirectory(directory: string) {
const entries = [];
for (const entry of (await fs.readdir(directory, { recursive: true })).sort()) {
const entryPath = path.join(directory, entry);
const stats = await fs.lstat(entryPath);
let content: string | undefined;
if (stats.isFile()) {
content = hash(await fs.readFile(entryPath));
} else if (stats.isSymbolicLink()) {
content = await fs.readlink(entryPath);
}
entries.push({ path: entry, fileMode: stats.mode, content });
}
return entries;
}
Loading