代码之家  ›  专栏  ›  技术社区  ›  koalo

根据可用CPU核数扩展docker服务

  •  0
  • koalo  · 技术社区  · 9 年前

    我将docker swarm用于CPU密集型计算应用程序。每个容器都运行相同的单线程应用程序。当然,可用的容器越多,整体计算速度就越快,但只取决于可用CPU核的数量。因此,在一个有8个核心的节点上,应该有8个正在运行的容器。

    备注:我的应用程序依赖于覆盖网络,据我所知,使用服务而不是手动处理容器是首选方法。

    1 回复  |  直到 9 年前
        1
  •  1
  •   koalo    9 年前

    我想到的一个选择是定期检查连接的节点,并为每个节点创建具有适当数量副本的服务。这可能不是一个非常优雅的解决方案,但至少可以与以下Python脚本一起使用。

    #!/usr/bin/env python3
    
    import docker
    
    def rescale(service_prefix,service_arguments):
        client = docker.from_env()
        service_names = [s.name for s in client.services.list()]
    
        for node in client.nodes.list():
            # Only handle ready nodes
            if node.attrs['Status']['State'] != 'ready':
                continue
    
            service_name = service_prefix+node.id
            if service_name not in service_names:
                # Service does not exist -> Create it
                cpus = node.attrs['Description']['Resources']['NanoCPUs']/1000000000
                print("Creating service %s with %i replicas"%(service_name,cpus))
                mode={'Replicated':{'Replicas':int(cpus)}}
                constraints=['node.id==%s'%node.id]
                client.services.create(name=service_name, mode=mode, constraints=constraints, **service_arguments)
            else:
                # Continue running this service
                service_names.remove(service_name)
    
        # Remove services of no longer existing nodes
        for service in service_names:
            print("Removing service %s"%service)
            client.services.get(service).remove()
    
    rescale(service_prefix="evaluation_",
            service_arguments={'image':'imagename','networks':['swarmnet']})