Skip to content

Executing commands

Container startup command

By default the container will execute whatever command is specified in the image's Dockerfile. To override this, and specify a different command, use withCommand. For example:

public GenericContainer redisWithCustomPort = new GenericContainer(DockerImageName.parse("redis:5.0"))
    .withCommand("redis-server --port 7777")

Executing a command

Your test can execute a command inside a running container, similar to a docker exec call:

container.execInContainer("touch", "/somefile.txt");

This can be useful for software that has a command line administration tool. You can also get the output (stdout/stderr) and exit code from the command - for example:

Container.ExecResult lsResult = container.execInContainer("ls", "-al", "/");
String stdout = lsResult.getStdout();
int exitCode = lsResult.getExitCode();
assertThat(stdout).contains("somefile.txt");
assertThat(exitCode).isZero();

Environment variables

To add environment variables to the container, use withEnv:

new GenericContainer(...)
        .withEnv("API_TOKEN", "foo")