Some docker images will have “CMD” instruction in their DockerFile out of the box.
In this post I will explain how to override that “CMD” instruction if present in DockerFile or provide our own instruction in the absence of “CMD” instruction in the DockerFile.
For our example I will use the nginx image from DockerHub.
Below is the “CMD” instruction of its DockerFile.
CMD ["nginx", "-g", "daemon off;"]
Basically it is telling to start the nginx server. We can change this just to print version number.
To achieve this I will use “withCommand” method available on “GenericContainer” class.
This method will variable number of String objects. The Strings when concatenated becomes the “CMD” instruction.
Below is the complete main code showing how to do it.
Main class
1 package package7;
2
3 import org.testcontainers.containers.GenericContainer;
4 import org.testcontainers.utility.DockerImageName;
5
6 public class Example7 {
7 public static void main(String[] args) {
8 DockerImageName dockerImageName = DockerImageName.parse("nginx");
9 try (GenericContainer<?> container = new GenericContainer<>(dockerImageName)) {
10 container.withCommand("nginx", "-v");
11 container.start();
12 String data = container.getLogs();
13 System.out.println(data);
14 }
15 }
16 }
In the above at line 8, I get “nginx” docker image from docker hub.
In the “try with resources” block, I will create an instance of “GenericContainer” class
At line 10, I use the “withCommand” method and pass two arguments.
At line 11, I start the container.
Please note if you overriding an existing “CMD” instruction present in DockerFile or providing a new one, it should be done before the call to “start” method.
At line 11, I start the container and we get the below output from the logs.
nginx version: nginx/1.27.2
In this way we can override the “CMD” instruction already present in DockerFile or provide a new “CMD” instruction for docker image without “CMD” instructions.