How to use “docker run” for troubleshooting container issues in DevOps?

106    Asked by debbieJha in Devops , Asked on Jun 5, 2024

 I am a DevOps engineer and I am tasked with maintaining a suite of microservices that can run in docker contains. One of my services has begun to behave unexpectedly thus I need to fix it or debug it in real time. How can I use the “docker run” command in interactive mode to start a new container from the same image as “my microservices” ensuring to diagnose and troubleshoot issues within the container? 

Answered by Charles Parr

In the context of DevOps, you can easily debug the microservices by running a new container interactively by using the docker run command. Here are the appropriate approaches given:-

Finding the image of the running containers

First, you should ensure that you are using the correct image. For this, you can check the running “my microservices” container to determine this particular image. This command would help you in retrieving the image names used by the “my microservices” containers.

Running a new interactive container

Once you have identified the image, then you can run a new container actively.

Comprehensive script

Here is a comprehensive script given which would combine the steps and also handle the potential errors or issues:-

#!/bin/bash
# Define the container name
CONTAINER_NAME=”my_microservice”
# Get the image name from the running container
IMAGE_NAME=$(docker inspect –format=’{{.Config.Image}}’ $CONTAINER_NAME 2>/dev/null)
# Check if the container is running and the image name was retrieved
If [ -z “$IMAGE_NAME” ]; then
  Echo “Error: Unable to retrieve image name for container $CONTAINER_NAME.”
  Exit 1
Fi
Echo “Running new container from image: $IMAGE_NAME”
# Run a new container interactively with the retrieved image
Docker run -it $IMAGE_NAME /bin/bash
If [ $? -ne 0 ]; then
  Echo “Error: Failed to run the interactive container.”
  Exit 1
Fi

Echo “Interactive session started in new container based on image $IMAGE_NAME.”

Save and execute the script

Now you would be need to save the above script to a file for example “run _ interactive. Sh”

This script does the following:-

This script helps in defining the name of the existing container.

This would help in retrieving the image name which was used by this container.

You can check if the image was successfully retrived or not.

This can run a new container interactively by using the retrieved image.

It can provide a feedback on either the new interactive container was successfully started or not.

By using this approach, you can easily ensure that you are using the right images and provide a strong method to launch an interactive session for debugging.

Here is also the Java example given below, however, you would need to ensure first that you should add the following dependencies to your “pom.xml” file:-


    com.github.docker-java

    docker-java

    3.2.13


Now here is the java coding:-

Import com.github.dockerjava.api.DockerClient;
Import com.github.dockerjava.api.DockerClientBuilder;
Import com.github.dockerjava.api.command.CreateContainerResponse;
Import com.github.dockerjava.api.command.InspectContainerResponse;
Import com.github.dockerjava.api.exception.DockerException;
Import com.github.dockerjava.api.model.Bind;
Import com.github.dockerjava.api.model.HostConfig;
Import com.github.dockerjava.api.model.PortBinding;
Import com.github.dockerjava.api.model.Ports;
Public class DockerInteractiveRun {
    Public static void main(String[] args) {
        // Container name
        String containerName = “my_microservice”;
        // Initialize Docker client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        Try {
            // Inspect the running container to get its image name
            InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(containerName).exec();
            String imageName = containerResponse.getConfig().getImage();
            If (imageName == null || imageName.isEmpty()) {
                System.out.println(“Error: Unable to retrieve image name for container “ + containerName);
                Return;
            }
            System.out.println(“Running new container from image: “ + imageName);
            // Create a new container interactively with a shell
            CreateContainerResponse newContainer = dockerClient.createContainerCmd(imageName)
                    .withCmd(“/bin/bash”)
                    .withTty(true)
                    .withStdinOpen(true)
                    .exec();
            String newContainerId = newContainer.getId();
            // Start the newly created container
            dockerClient.startContainerCmd(newContainerId).exec();
            // Attach to the container to interact with it
            dockerClient.attachContainerCmd(newContainerId)
                    .withLogs(true)
                    .withFollowStream(true)
                    .withStdOut(true)
                    .withStdErr(true)
                    .exec(new AttachContainerResultCallback())
                    .awaitCompletion();
            System.out.println(“Interactive session started in new container based on image “ + imageName);
        } catch (DockerException | InterruptedException e) {
            e.printStackTrace();
            System.out.println(“Error: Failed to run the interactive container.”);
        } finally {
            dockerClient.close();
        }
    }
}


Your Answer

Interviews

Parent Categories