How to determine if a docker container is damaged

I run the process every 5 minutes and check every container. If the container does not respond, I can point it down. I have the IP address of the containers and I go through each ip and check if it responds to ping. If not, I mark it as down. Is there a better way to do this? My code is:

@Transactional
@Scheduled(fixedRate = 1000 * 60)   //5 min
public void monitorHosts(){
    Iterable<Ncl> ncls = nclRepository.findAll();

    for(Ncl ncl: ncls){
        for(String host: ncl.getHosts()){
            Boolean isHostAlive = isHostAlive(host);
            if(!isHostAlive){
                Ncl nclWorking = nclRepository.findOne(ncl.getUuid());
                if(nclWorking != null){
                    Set<String> hosts = nclWorking.getHosts().stream().filter(x -> x.equals(host)).collect(Collectors.toSet());
                    nclWorking.getHosts().clear();
                    nclWorking = nclRepository.save(nclWorking);
                    nclWorking.setHosts(hosts);
                    nclRepository.save(nclWorking);
                }
            }
        }
    }
}

private Boolean isHostAlive(String host){
    try{
        InetAddress address = InetAddress.getByName(host);
        boolean reachable = address.isReachable(10000);
        return reachable;
    } catch (Exception e){
        e.printStackTrace();
        return false;
    }
}
+4
source share
3 answers

It basically depends on what you need to do with the information about your containers.

There are several monitoring solutions available that can track your containers and notify you if there are some problems.

- , , Consul.io , ( , ). docker-api Java, ICMP- , .

+2

docker events

https://docs.docker.com/engine/reference/commandline/events/#examples

-

docker events --filter 'event=stop'

+2

, :

HEALTHCHECK, docker

. - :

HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1

:

docker inspect --format='{{json .State.Health}}' <container_id>

docker ps STATUS:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                    PORTS                  NAMES
225426fc7c93        ubuntu              "tail -f /dev/null"      5 seconds ago       Up 4 seconds (healthy)

API :

curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json

PS: You can set the health check time to docker run(without modifying the Docker file). Docs

+1
source

Source: https://habr.com/ru/post/1677998/


All Articles