1

I have the following integration test setup for Kafka producer consumer application.

@Testcontainer
@DirtiesContext
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class KafkaIntegrationTest {
        
   @Container
   private static final KafkaContainer kafkaContainer = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"))
          .withFileSystemBind("/var/run/docker.sock", "/var/run/docker.sock", BindMode.READ_WRITE);
    
   @DynamicPropertySource
   private static void kafkaProperties(DynamicPropertyRegistry registry) {
      registry.add("spring.kafka.bootstrap-servers", KafkaContainer::getBootstrapServers);
   }
        
   @Test
   public void givenKafkaContainerWhenSendingWithProducerThenMessageReceived() {
      // Consumer integration test here
   }
                
}

Moreover, I have added these additional configurations in Dockerfile and Jenkinsfile to mount the host's Docker socket into the Docker container.

Dockerfile

...
FROM docker:latest
...
VOLUME /var/run/docker.sock:/var/run/docker.sock
...
RUN ./gradlew --no-daemon testClasses processIntegrationTests
...

Jenkinsfile

    ...
    agent {
        docker {
            image 'docker:latest'
            args '-v /var/run/docker.sock:/var/run/docker.sock --privileged'
        }
    }
    ...
    stage('Test') {
        steps {
            sh "docker build --target test-result ."
        }
    ...
    }

The integration tests are working fine when running the Gradle task in IDE, but still not pulling the Kafka image programmatically using Testcontainers in the Docker based CI/CD pipeline and failing with the following error.

environment initializationError FAILED 
java.lang.IllegalStateException at DockerClientProviderStrategy.java
Dave
  • 25
  • 5
  • You can't ever connect to the host's Docker socket in a Dockerfile. (That `VOLUME` instruction does not do what you think; the Dockerfile cannot grant either the build or the final image access to the host filesystem.) Can you run these sorts of system tests from your host system, before you start building your image? – David Maze May 14 '23 at 10:23
  • Also see [Running test with testcontainers as part of a Dockerfile](https://stackoverflow.com/questions/61015787/running-test-with-testcontainers-as-part-of-a-dockerfile). [How do I get Java testcontainers to work in Docker Multistage builds?](https://stackoverflow.com/questions/62174634/how-do-i-get-java-testcontainers-to-work-in-docker-multistage-builds) has a potential workaround, if you have the right insecure Docker Desktop configuration. You might need [Gradle build without tests](https://stackoverflow.com/questions/4597850/gradle-build-without-tests) in the Dockerfile. – David Maze May 14 '23 at 10:26

0 Answers0