Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static container name when running Testcontainers with docker compose

My application consists of a Spring Boot app and a database. I can successfully run them in Docker using docker-compose. I now want to use a similar Docker compose file along with testcontainers to write some automated tests. I am failing because the hostname in the application.yml file of the Spring Boot app doesn't match the random name assigned to the database container and therefore the app is unable to connect to the database.

docker-compose

version: '2'

services:
  api:
    image: simon/api:1.0.0-SNAPSHOT
    networks:
      - my_network

  api-db:
    image: simon/api-db:1.0.0-SNAPSHOT
    networks:
      - my_network

  networks:
    my_network:
      external: false

Class rule set-up

@ClassRule public static DockerComposeContainer<?> dockerEnvironment =
        new DockerComposeContainer<>(new File("docker-compose.yml"))
                .withPull(false)
                .withLocalCompose(true)
                .withExposedService("api", "8080");

application.yml

spring:
  profiles: docker
  datasource:
    url: jdbc:postgresql://api-db:5432/api

When the test runs, the containers are assigned names such as:

wtdopq2hneev_api_1 wtdopq2hneev_api-db_1

The fact that it seems to be assigning a random network name (wtdopq2hneev) rather than using my_network, is ultimately my problem.

I can specify the name of the container in the docker-compose.yml file, but then I can't 'expose' the services which I need to be able to so that I can call my API from my tests:

Am I going about this in the wrong way?

  • Java version: 1.8.0_144
  • Testcontainers version: 1.8.3
  • Docker for Mac version: 17.09.0-ce-mac35 (19611)

The Docker version is a little old but I don't think that's the issue

like image 483
s1mm0t Avatar asked Apr 26 '26 17:04

s1mm0t


1 Answers

The container name shouldn't matter here, it's the hostname that is important, and in your case this will be api and api-db. For this simple use case there is probably no need for a custom network, did you try it without one?

like image 132
Yanick Nedderhoff Avatar answered Apr 30 '26 08:04

Yanick Nedderhoff