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("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) from the command - for example:

Container.ExecResult lsResult = container.execInContainer("ls", "-al", "/");
String stdout = lsResult.getStdout();

Note that there is no way to get the return code of the executed command, only stdout/stderr.

Environment variables

To add environment variables to the container, use withEnv:

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