docker-py icon indicating copy to clipboard operation
docker-py copied to clipboard

Question: Ulimit with services.create ?

Open adb014 opened this issue 6 months ago • 1 comments

I'm trying to migrate some of my code to docker swarm and even though I can do

docker service create --ulimit nofile=66535 alpine sleep infinity

and I can do

import docker
_client = docker.from_env()
_container = _client.containers.run(image="alpine", command="sleep infinity", ulimits=[docker.types.Ulimit(name="nofile", soft=65535, hard=65535)], detach=True)

or even

import docker

_client= docker.from_env()
_service = _client.services.create(image="alpine", command="sleep infinity")

I however have no way of passing the ulimit value to the created service. Any ideas ?

adb014 avatar Jun 24 '25 16:06 adb014

Ok to answer my own question, this can be done with the low level API. Looking at the docker REST API for the ServiceCreate command, the json payload includes a TaskTemplate, that includes a ContainerSpec that includes a Ulimits value. However looking at the corresponding code for ContainerSpec in dockerpy there is no capablity to include ulimits. However, as ContainerSpec is just a DictType, the following works

import docker
_client = docker.APIClient()
_cont = docker.types.ContainerSpec(image="alpine", command="sleep infinity")
_cont['Ulimits'] = [docker.types.Ulimit(name = 'nofile', hard = 65535, soft = 65535)]
_client.service_create(docker.types.TaskTemplate(_cont))

though its a little ugly. It would be nice to patch the dockerpy ContainerSpec with

        if ulimits is not None:
            if not isinstance(ulimits, list):
                raise TypeError('ulimits must be a list')

            self['Ulimits'] = ulimits

adb014 avatar Jun 25 '25 09:06 adb014