从集群获取正在运行的容器的列表

我通过ECS在AWS上运行Docker容器。 我已经build立了一些基本configuration的集群。

现在我期待着没有。 此群集上所有正在运行的容器(分布在2-3个EC2实例中)? AWS / Docker是否为此提供了任何API?

我知道一个容器实例,做docker ps -a将返回所有运行/停止容器的列表,而docker ps将返回运行容器在一个系统上。 但是我想要一个API(可以从外部调用)或命令(我可以在集群的任何实例部分运行),它显示了跨集群运行的容器总数?

在ECS中,您正在查看任务。 您可以使用ECS API列出所有正在运行的任务。 例如,以aws cli为例,你可以这样做:

 aws ecs list-tasks --cluster <cluster_name> 

如果您使用其中一个SDK,例如boto3,您可以轻松获得计数:

 import boto3 client = boto3.client('ecs') tasks = client.list_tasks(cluster='YouCluster') print(len(tasks['taskArns']) 

我不确定在AWS环境中获取容器信息。 但是Docker在单个服务器或运行集群方面对API有非常好的支持 ,尤其是使用Docker Swarm的集群。

对于使用Docker API,您需要在集群中的pipe理器节点上configurationdocker守护进程端口 (如果集群正在docker swarm中运行),或者单独configuration所有节点并可以访问这些API。

两种configurationdocker守护进程的方法

1)在/ etc / default / docker文件中configuration:

 DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock" 

2)在/etc/docker/daemon.jsonconfiguration:

 { "hosts": ["tcp://127.0.0.1:6000", "unix:///var/run/docker.sock"] } 

一旦端口被configuration,重新启动docker服务。

如果未configurationdocker默认套接字(unix:///var/run/docker.sock),则Docker可能没有正确configuration,将等待无限期。

注意:但不要configuration两个configuration文件 ,可能会出现以下错误:

 Waiting for /var/run/docker.sock unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000) 

添加用户端口[tcp://127.0.0.1:5000]默认docker套接字[unix:///var/run/docker.sock]的原因是用户端口允许访问dockerAPI,而默认套接字启用CLI。 如果/ etc / default / docker文件中没有提到默认端口[unix:///var/run/docker.sock],则可能会出现以下错误:

 #docker ps Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? 

这个错误不是因为docker没有运行, 而是因为默认的docker socket没有启用。

一旦启用Docker守护进程端口,您就可以使用Docker API访问运行集群服务

curl -X GET http://127.0.0.1:6000/services?id=all

个人服务器API

curl -X GET http://127.0.0.1:6000/containers/json?all

更多的dockerAPI请参考这里

注意:testing了Docker版本17.04和Docker Swarm

通过群集中的CLI检查信息:

群集信息:

 #docker node ls ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS 7pl9bab4g2yjwctjxq2aax3ud radisysuser-VirtualBox Ready Active o45wire6qhu8i5eujl6iyon2p * labadmin-VirtualBox Ready Active Leader odwdr5uey085hpb8tnwtj11e0 radisysuser-VirtualBox Ready Active 

服务/容器信息:

 # docker service ls ID NAME MODE REPLICAS IMAGE sccuf1jgkphn redis replicated 3/3 redis:latest 

个人服务信息:

 # docker service ps redis ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS jgix9p141pxt redis.1 redis:latest radisysuser-VirtualBox Running Running less than a second ago 1i4yc8f9cqm5 redis.2 redis:latest radisysuser-VirtualBox Running Running less than a second ago dk1tubki2dg8 \_ redis.2 redis:latest radisysuser-VirtualBox Shutdown Shutdown less than a second ago stpl55l6wwci redis.3 redis:latest labadmin-VirtualBox Running Running 4 hours ago 

希望这会有所帮助。