1- import { AbstractStartedContainer , GenericContainer , log , StartedTestContainer , Wait } from "testcontainers" ;
1+ import {
2+ AbstractStartedContainer ,
3+ GenericContainer ,
4+ getContainerRuntimeClient ,
5+ log ,
6+ StartedTestContainer ,
7+ Wait ,
8+ } from "testcontainers" ;
9+ import { getReaper } from "testcontainers/src/reaper/reaper" ;
10+ import { LABEL_TESTCONTAINERS_SESSION_ID } from "testcontainers/src/utils/labels" ;
211
312export const LOCALSTACK_PORT = 4566 ;
413
514export class LocalstackContainer extends GenericContainer {
615 constructor ( image = "localstack/localstack:2.2.0" ) {
716 super ( image ) ;
17+
818 this . withExposedPorts ( LOCALSTACK_PORT ) . withWaitStrategy ( Wait . forLogMessage ( "Ready" , 1 ) ) . withStartupTimeout ( 120_000 ) ;
919 }
1020
@@ -25,8 +35,19 @@ export class LocalstackContainer extends GenericContainer {
2535 log . info ( `${ envVar } environment variable set to "${ this . environment [ envVar ] } " (${ hostnameExternalReason } )` ) ;
2636 }
2737
38+ /**
39+ * Configure the LocalStack container to add sessionId when starting lambda container.
40+ * This allows the lambda container to be identified by the {@link Reaper} and cleaned up on exit.
41+ */
42+ private async flagLambdaSessionId ( ) : Promise < void > {
43+ const client = await getContainerRuntimeClient ( ) ;
44+ const reaper = await getReaper ( client ) ;
45+ this . withEnvironment ( { LAMBDA_DOCKER_FLAGS : `-l ${ LABEL_TESTCONTAINERS_SESSION_ID } =${ reaper . sessionId } ` } ) ;
46+ }
47+
2848 protected override async beforeContainerCreated ( ) : Promise < void > {
2949 this . resolveHostname ( ) ;
50+ await this . flagLambdaSessionId ( ) ;
3051 }
3152
3253 public override async start ( ) : Promise < StartedLocalStackContainer > {
0 commit comments