or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

container-management.mddocker-compose.mdindex.mdnetworking.mdutilities.mdwait-strategies.md
tile.json

networking.mddocs/

Networking

Create and manage Docker networks for container communication and isolation.

Capabilities

Network Class

Creates Docker networks for connecting containers.

/**
 * Creates a new Docker network
 */
class Network {
  /**
   * Create and start a new network
   * @returns Promise resolving to started network
   */
  start(): Promise<StartedNetwork>;
}

Usage Example:

import { Network, GenericContainer } from 'testcontainers';

// Create a network
const network = await new Network().start();

// Start containers on the network
const redis = await new GenericContainer('redis:7-alpine')
  .withNetwork(network)
  .withNetworkAliases('redis-server')
  .withExposedPorts(6379)
  .start();

const app = await new GenericContainer('myapp:latest')
  .withNetwork(network)
  .withEnvironment({
    REDIS_HOST: 'redis-server', // Use network alias
    REDIS_PORT: '6379'
  })
  .withExposedPorts(8080)
  .start();

// Containers can communicate using network aliases
// App can connect to Redis via 'redis-server:6379'

// Cleanup
await app.stop();
await redis.stop();
await network.stop();

StartedNetwork Interface

Represents a running Docker network.

/**
 * Running Docker network
 */
interface StartedNetwork {
  /**
   * Get the network ID
   * @returns Docker network ID
   */
  getId(): string;

  /**
   * Get the network name
   * @returns Docker network name
   */
  getName(): string;

  /**
   * Stop and remove the network
   * @returns Promise resolving to stopped network
   */
  stop(): Promise<StoppedNetwork>;

  /**
   * Async disposal support for automatic cleanup
   */
  [Symbol.asyncDispose](): Promise<void>;
}

Usage Examples:

import { Network, GenericContainer } from 'testcontainers';

// Create isolated network for testing
const network = await new Network().start();
const networkId = network.getId();
const networkName = network.getName();

console.log(`Network ${networkName} (${networkId}) created`);

// Use with multiple containers
const db = await new GenericContainer('postgres:14')
  .withNetwork(network)
  .withNetworkAliases('db', 'database')
  .withEnvironment({
    POSTGRES_PASSWORD: 'test'
  })
  .start();

const app = await new GenericContainer('myapp:latest')
  .withNetwork(network)
  .withEnvironment({
    DATABASE_HOST: 'database',
    DATABASE_PORT: '5432'
  })
  .start();

// Check container networking
const appNetworks = app.getNetworkNames();
console.log('App networks:', appNetworks);

const appIp = app.getIpAddress(networkName);
console.log('App IP on network:', appIp);

// Cleanup
await app.stop();
await db.stop();
await network.stop();

// Using async disposal (automatic cleanup)
{
  await using network = await new Network().start();

  const container = await new GenericContainer('redis:alpine')
    .withNetwork(network)
    .start();

  // Use container...

  await container.stop();
  // Network automatically cleaned up when scope exits
}

StoppedNetwork Interface

Terminal state representing a removed network.

/**
 * Stopped/removed network (terminal state)
 */
interface StoppedNetwork {
  // No operations available - network is removed
}

Advanced Networking Examples

Multi-Container Communication

Example showing containers communicating on a custom network:

import { Network, GenericContainer, Wait } from 'testcontainers';

// Create a network for the application stack
const network = await new Network().start();

// Start database with network alias
const postgres = await new GenericContainer('postgres:14')
  .withNetwork(network)
  .withNetworkAliases('postgres', 'db')
  .withEnvironment({
    POSTGRES_USER: 'app',
    POSTGRES_PASSWORD: 'secret',
    POSTGRES_DB: 'appdb'
  })
  .withExposedPorts(5432)
  .withWaitStrategy(Wait.forLogMessage('database system is ready'))
  .start();

// Start cache with network alias
const redis = await new GenericContainer('redis:7-alpine')
  .withNetwork(network)
  .withNetworkAliases('redis', 'cache')
  .withExposedPorts(6379)
  .withWaitStrategy(Wait.forLogMessage('Ready to accept connections'))
  .start();

// Start application connected to both services
const app = await new GenericContainer('myapp:latest')
  .withNetwork(network)
  .withEnvironment({
    DATABASE_URL: 'postgresql://app:secret@postgres:5432/appdb',
    REDIS_URL: 'redis://redis:6379',
    PORT: '3000'
  })
  .withExposedPorts(3000)
  .withWaitStrategy(Wait.forHttp('/health', 3000))
  .start();

// Access app from host
const appHost = app.getHost();
const appPort = app.getMappedPort(3000);
console.log(`App available at http://${appHost}:${appPort}`);

// Get network information
const appIp = app.getIpAddress(network.getName());
const dbIp = postgres.getIpAddress(network.getName());
const redisIp = redis.getIpAddress(network.getName());

console.log('Network topology:');
console.log(`  App:      ${appIp}`);
console.log(`  Postgres: ${dbIp}`);
console.log(`  Redis:    ${redisIp}`);

// Cleanup
await app.stop();
await redis.stop();
await postgres.stop();
await network.stop();

Network Isolation

Example showing network isolation for parallel tests:

import { Network, GenericContainer } from 'testcontainers';

// Create isolated networks for parallel test suites
async function createTestEnvironment() {
  const network = await new Network().start();

  const db = await new GenericContainer('postgres:14')
    .withNetwork(network)
    .withNetworkAliases('db')
    .withEnvironment({ POSTGRES_PASSWORD: 'test' })
    .start();

  const app = await new GenericContainer('myapp:latest')
    .withNetwork(network)
    .withEnvironment({ DATABASE_HOST: 'db' })
    .start();

  return { network, db, app };
}

// Each test suite gets isolated environment
const suite1 = await createTestEnvironment();
const suite2 = await createTestEnvironment();

// Tests run in parallel without interference
// suite1 and suite2 have separate networks

// Cleanup
await suite1.app.stop();
await suite1.db.stop();
await suite1.network.stop();

await suite2.app.stop();
await suite2.db.stop();
await suite2.network.stop();

Using Network Modes

Example showing different network modes:

import { GenericContainer } from 'testcontainers';

// Host network mode - share host's network stack
const hostContainer = await new GenericContainer('myapp:latest')
  .withNetworkMode('host')
  .start();
// App binds directly to host ports

// Bridge network mode (default) - isolated network with port mapping
const bridgeContainer = await new GenericContainer('myapp:latest')
  .withNetworkMode('bridge')
  .withExposedPorts(8080)
  .start();

// Container network mode - share another container's network
const nginx = await new GenericContainer('nginx:alpine')
  .withExposedPorts(80)
  .start();

const sidecar = await new GenericContainer('monitoring:latest')
  .withNetworkMode(`container:${nginx.getId()}`)
  .start();
// Sidecar shares nginx's network stack

// None network mode - no networking
const isolatedContainer = await new GenericContainer('utility:latest')
  .withNetworkMode('none')
  .start();
// Container has no network access

// Cleanup
await hostContainer.stop();
await bridgeContainer.stop();
await sidecar.stop();
await nginx.stop();
await isolatedContainer.stop();

Container Network Methods

When using networks, containers provide these additional networking methods:

import { GenericContainer, Network } from 'testcontainers';

const network = await new Network().start();

const container = await new GenericContainer('alpine:latest')
  .withNetwork(network)
  .withNetworkAliases('app', 'service')
  .withExtraHosts([
    { host: 'external-api', ipAddress: '192.168.1.100' },
    { host: 'mock-service', ipAddress: '10.0.0.50' }
  ])
  .start();

// Get network information
const networks = container.getNetworkNames(); // ['custom_network_name']
const networkId = container.getNetworkId(network.getName()); // 'abc123...'
const ipAddress = container.getIpAddress(network.getName()); // '172.18.0.2'

await container.stop();
await network.stop();