0

I am using docker sdk for python.

I am creating a network like so

    try:
        client.networks.create(name=network_name, check_duplicate=True)
    except docker.errors.APIError as ex:
        print(f"not recreating existing docker network: '{network_name}'")
        pass

which works fine.

I want to delete this network.

I am trying like so

def remove_docker_network(network_name: str, client: docker.client.DockerClient):
    try:
        client.networks.prune(filters={"name": network_name})
    except docker.errors.APIError as ex:
        print(f"not removing non existing docker network: '{network_name}'")
        pass

but network remains.

Doc only shows prune. There is no rm.

How to do it correctly?

Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • According to the docs to which you've linked, there's a `remove` method on Networks. – larsks Jan 27 '22 at 16:43
  • @larsks Wow I missed that completely. Still, it is not clear how to remove that network by name, as the doc needs a network object to remove, and that is returned by `get`, which accepts id and not a name. Couldn't find a `get_id_by_name` or similar – Gulzar Jan 27 '22 at 16:47

1 Answers1

3

Use remove:

network_name = 'hello'
client.networks.create(name=network_name, check_duplicate=True)

# docker network ls
# NETWORK ID     NAME                DRIVER    SCOPE
# 9b4262356615   bridge              bridge    local
# f6fb876e8a2b   hello               bridge    local
# 92f69ef02a1e   host                host      local
# 7dff8097025d   mailtrain_default   bridge    local
# 8326691aaf3b   none                null      local

client.networks.get(network_name).remove()

# docker network ls
# NETWORK ID     NAME                DRIVER    SCOPE
# 9b4262356615   bridge              bridge    local
# 92f69ef02a1e   host                host      local
# 7dff8097025d   mailtrain_default   bridge    local
# 8326691aaf3b   none                null      local

Corralien
  • 109,409
  • 8
  • 28
  • 52